title
stringlengths
13
150
body
stringlengths
749
64.2k
label
int64
0
3
token_count
int64
1.02k
28.5k
Converting factor to integer
<p>Converting factor to integer from a .csv using RStudio.</p> <p>Hi, I know this question has been asked frequently but I've been trying to wrap my head around things for an hour with no success.</p> <p>In my .csv file 'Weighted.average' is a calculation of Weighted.count/count (before conversion), but when I use the file in R it is a factor, despite being completely numeric (with decimal points). </p> <p>I'm aiming to aggregate the data using Weighted.average's numeric values. But as it is still considered a factor it doesn't work. I'm newish to R so I'm having trouble converting other examples to my own. </p> <p>Thanks</p> <pre><code>RENA &lt;- read.csv('RENA.csv') RENAVG &lt;- aggregate(Weighted.average~Diet+DGRP.Line, data = RENA, FUN = sum) ggplot(RENAVG, aes(x=DGRP.Line, y=Weighted.average, colour=Diet)) + geom_point() </code></pre> <p>Expected to form a dot plot using Weighted.average, error</p> <blockquote> <p>Error in Summary.factor(c(3L, 4L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, : ‘sum’ not meaningful for factors</p> </blockquote> <p>occurs. I know it's due to it not being read as an integer, but I'm lost at how to convert.</p> <p>Thanks</p> <p>Output from dput</p> <pre><code>&gt; dput(head(RENA)) structure(list(DGRP.Line = structure(c(19L, 19L, 19L, 19L, 20L, 20L), .Label = c("105a", "105b", "348", "354", "362a", "362b", "391a", "391b", "392", "397", "405", "486a", "486b", "712", "721", "737", "757a", "757b", "853", "879"), class = "factor"), Diet = structure(c(1L, 1L, 2L, 2L, 1L, 1L), .Label = c("Control", "Rena"), class = "factor"), Sex = structure(c(2L, 1L, 2L, 1L, 2L, 1L), .Label = c("Female", "Male"), class = "factor"), Count = c(0L, 0L, 0L, 0L, 1L, 0L), Date = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("16/07/2019", "17/07/2019", "18/07/2019", "19/07/2019", "20/07/2019", "21/07/2019", "22/07/2019"), class = "factor"), Day = c(1L, 1L, 1L, 1L, 1L, 1L), Weighted.count = c(0L, 0L, 0L, 0L, 1L, 0L), Weighted.average = structure(c(60L, 59L, 52L, 63L, 44L, 36L), .Label = c("", "#DIV/0!", "1.8", "1.818181818", "2", "2.275862069", "2.282608696", "2.478873239", "2.635135135", "2.705882353", "2.824561404", "2.903614458", "2.911392405", "2.917525773", "3", "3.034090909", "3.038461538", "3.083333333", "3.119402985", "3.125", "3.154929577", "3.175438596", "3.1875", "3.220338983", "3.254237288", "3.263157895", "3.314606742", "3.341463415", "3.35", "3.435483871", "3.5", "3.6", "3.606557377", "3.666666667", "3.6875", "3.694214876", "3.797619048", "3.813953488", "3.833333333", "3.875", "3.909090909", "3.916666667", "4.045454545", "4.047169811", "4.111111111", "4.333333333", "4.40625", "4.444444444", "4.529411765", "4.617021277", "4.620689655", "4.666666667", "4.714285714", "4.732283465", "4.821428571", "4.823529412", "4.846153846", "4.851851852", "4.855263158", "4.884615385", "4.956521739", "5", "5.115384615", "5.230769231", "5.343283582", "5.45", "5.464285714", "5.484848485", "5.538461538", "5.551724138", "5.970588235", "6", "6.2"), class = "factor")), row.names = c(NA, 6L), class = "data.frame") </code></pre>
3
1,503
How to create a new column with values from previous row in exsisting column, in a tibble, in R
<p>I want to create a new column, that consists of the last value from a previous period for the same ID, placed in the same row as the first value for the next period. If there is no previous period NA should be applied.</p> <p>However, I can't find any functions in any packages to solve this issue for me, so I expect I have to write a loop?</p> <p>Does anyone out there have any idea how to solve this in a tidy manner (with or without a loop), that can be applied to a big tibble (+4 million observations)?</p> <p>My data is ordered like the following df, and the goal is df1:</p> <pre><code>df &lt;- tibble( ID = rep(c(77,88,99),each=6), PERIOD = rep(c(1,2,3,1,2,3,1,2,3),each=2), DATE = seq(as.Date(&quot;2020-06-01&quot;), as.Date(&quot;2020-06-18&quot;), by= &quot;days&quot;), RESULT = seq(from = 10, to = 44, by = 2) ) df # A tibble: 18 x 4 ID PERIOD DATE RESULT &lt;dbl&gt; &lt;dbl&gt; &lt;date&gt; &lt;dbl&gt; 1 77 1 2020-06-01 10 2 77 1 2020-06-02 12 3 77 2 2020-06-03 14 4 77 2 2020-06-04 16 5 77 3 2020-06-05 18 6 77 3 2020-06-06 20 7 88 1 2020-06-07 22 8 88 1 2020-06-08 24 9 88 2 2020-06-09 26 10 88 2 2020-06-10 28 11 88 3 2020-06-11 30 12 88 3 2020-06-12 32 13 99 1 2020-06-13 34 14 99 1 2020-06-14 36 15 99 2 2020-06-15 38 16 99 2 2020-06-16 40 17 99 3 2020-06-17 42 18 99 3 2020-06-18 44 df1 &lt;- tibble( ID = rep(c(77,88,99),each=6), PERIOD = rep(c(1,2,3,1,2,3,1,2,3),each=2), DATE = seq(as.Date(&quot;2020-06-01&quot;), as.Date(&quot;2020-06-18&quot;), by= &quot;days&quot;), RESULT = seq(from = 10, to = 44, by = 2), RESULT_post = c(&quot;NA&quot;,&quot;NA&quot;,12,&quot;NA&quot;,16,&quot;NA&quot;,&quot;NA&quot;,&quot;NA&quot;,24,&quot;NA&quot;,28, &quot;NA&quot;,&quot;NA&quot;, &quot;NA&quot;,36, &quot;NA&quot;,40, &quot;NA&quot; ) ) df1 # A tibble: 18 x 5 ID PERIOD DATE RESULT RESULT_pre &lt;dbl&gt; &lt;dbl&gt; &lt;date&gt; &lt;dbl&gt; &lt;chr&gt; 1 77 1 2020-06-01 10 NA 2 77 1 2020-06-02 12 NA 3 77 2 2020-06-03 14 12 4 77 2 2020-06-04 16 NA 5 77 3 2020-06-05 18 16 6 77 3 2020-06-06 20 NA 7 88 1 2020-06-07 22 NA 8 88 1 2020-06-08 24 NA 9 88 2 2020-06-09 26 24 10 88 2 2020-06-10 28 NA 11 88 3 2020-06-11 30 28 12 88 3 2020-06-12 32 NA 13 99 1 2020-06-13 34 NA 14 99 1 2020-06-14 36 NA 15 99 2 2020-06-15 38 36 16 99 2 2020-06-16 40 NA 17 99 3 2020-06-17 42 40 18 99 3 2020-06-18 44 NA </code></pre> <p>All inputs are appreciated</p> <p>Thx / Sophia</p>
3
1,745
SwiftUI how to make hstack with rounded corners and above bottom side of screen?
<p>I would like to make such buttons bar:</p> <p><a href="https://i.stack.imgur.com/9lDly.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9lDly.png" alt="enter image description here" /></a></p> <p>for this purpose I decided to use hstack (not sure whether it is a good idea). I did it in such way:</p> <pre><code>HStack{ ForEach(playerMenuControllers,id: \.self ){img in let pos = playerMenuControllers.firstIndex(of: img) let likeImg = liked ? &quot;heart.fill&quot; : img let bookMarkImg = bookmark ? &quot;bookmark.fill&quot; : img Button(action: { switch pos{ case 0: break case 1: liked.toggle() break case 2: bookmark.toggle() break case 3: showingSheet.toggle() break default: break } }) { HStack { switch pos{ case 0: Image(systemName: img).foregroundColor(Color.white) case 1: Image(systemName: likeImg).foregroundColor(Color.white) case 2: Image(systemName: bookMarkImg).foregroundColor(Color.white) case 3: Image(systemName: img).foregroundColor(Color.white) default: Image(systemName: img).foregroundColor(Color.white) } } }.sheet(isPresented: $showingSheet) { SheetView(model: episode) } .padding(EdgeInsets(top: 17, leading: 33, bottom: 17, trailing: 33)) } } .cornerRadius(15) .background(Color(red: 54 / 255, green: 54 / 255, blue: 54 / 255)) .padding(EdgeInsets(top: 17, leading: 33, bottom: 17, trailing: 33)) </code></pre> <p>and I have such result:</p> <p><a href="https://i.stack.imgur.com/cbBFJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cbBFJ.png" alt="enter image description here" /></a></p> <p>what I did wrong, because I tried to apply all params from the desired design?</p>
3
1,866
how to fill the container with background image in css?
<p>so as you can see I have used a background image for my Container but it isn't filling up the container fully, I have tried the object-fit property but it isn't working, the image is still sticking on the left side of the container, what should I do.</p> <p>here is the screenshot for the image (1st problem): <a href="https://imgur.com/puw3bDN" rel="nofollow noreferrer">https://imgur.com/puw3bDN</a></p> <p>now about the second problem, the image inside (.feature2::before) is exceeding the container, I have tried using width but it is not working.</p> <p>here is the link to screenshot: <a href="https://imgur.com/YPTelhD" rel="nofollow noreferrer">https://imgur.com/YPTelhD</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>@import url("https://fonts.googleapis.com/css2?family=Bai+Jamjuree:wght@400;600&amp;display=swap"); * { margin: 0; padding: 0; list-style-type: none; text-align: center; } body { height: 100vh; font-family: "Bai Jamjuree", sans-serif; display: flex; font-size: 18px; } .primary { color: #4a4f53; } .neutral { color: #b3b7b8; } .container { background: url(./media/bg-header-mobile.png) no-repeat top; object-fit: cover; width: 23.438rem; height: 325.313rem; border: 1px red solid; margin: 0 auto; padding: 9.375rem 2rem; } .main_logo { opacity: 85%; width: 8.5rem; margin-top: 1.59rem; } .main_heading { font-size: 1.9rem; line-height: 1.35; margin-top: 3.5rem; width: 100%; margin-bottom: 1.8rem; } .main_content { margin-bottom: 3.5rem; } .button { display: flex; flex-direction: column; flex-wrap: wrap; justify-content: center; text-align: center; } .ios { background: #26bba5; color: white; font-size: 700; padding: 15px 10px; border-radius: 50px; border-bottom: 3px #219f8a solid; box-shadow: 0 2px 10px #26bba5; margin-bottom: 1.5rem; } .mac { background: #6174ff; color: white; font-size: 700; padding: 15px 10px; border-radius: 50px; border-bottom: 3px #4f62da solid; box-shadow: 0 2px 5px #6174ff; } .feature1 { margin-top: 12rem; } .feature1_dis { margin-top: 1.8rem; } .feature2::before { content: url(./media/image-computer.png); border: 1px red solid; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta name="viewport" content="width=default-width, initial-scale=1"&gt; &lt;meta charset="UTF-8"&gt; &lt;meta lang="en"&gt; &lt;link href="style.css" rel="stylesheet"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;header&gt; &lt;img src="media/logo.svg" class="main_logo"/&gt; &lt;h1 class="main_heading primary"&gt; A history of everything you copy &lt;/h1&gt; &lt;article class="main_content neutral"&gt;Clipbord allows you to track and organize everything you copy instantly access your clipboard on all your devices.&lt;/article&gt; &lt;div class="button"&gt; &lt;botton class="ios"&gt; Download for iOS &lt;/botton&gt; &lt;botton class="mac"&gt; Download for Mac &lt;/botton&gt; &lt;/div&gt; &lt;/header&gt; &lt;main&gt; &lt;div&gt;&lt;/div&gt; &lt;section class="features"&gt; &lt;h1 class="feature1 primary"&gt;Keep track of your snippets&lt;/h1&gt; &lt;article class="feature1_dis neutral"&gt;Clipboard instantly stores any items you copy in the cloud, meaning you can access your snippets immediately on all your devices. Our Mac and iOS apps will help you organize everything.&lt;/article&gt; &lt;h1 class="feature2 primary"&gt; Quick Search &lt;/h1&gt; &lt;article class="feature2_dis neutral"&gt; Easily search your snippets by content, category, web address, application, and more. &lt;/article&gt; &lt;h1 class="feature3 primary"&gt; iCloud Sync &lt;/h1&gt; &lt;article class="feature3_dis neutral"&gt; Instantly saves and syncs snippets across all your devices. &lt;/article&gt; &lt;h1 class="feature4 primary"&gt; Complete History &lt;/h1&gt; &lt;article class="feature4_dis neutral"&gt; Retrieve any snippets from the first moment you started using the app. &lt;/article&gt; &lt;h1 class="feature5 primary"&gt; Access Clipboard Anywhere &lt;/h1&gt; &lt;aritical class="feature5_dis neutral"&gt; Whether you're on the go, or at your computer, you can access all your Clipboard snippets in a few simple clicks. &lt;/aritical&gt; &lt;h1 class="feature6 primary"&gt; Supercharge your workflow &lt;/h1&gt; &lt;article class="feature6_dis neutral"&gt; We've got the tools to boost your produtivity. &lt;/article&gt; &lt;h1 class="feature7 primary"&gt; Create blacklists &lt;/h1&gt; &lt;article class="feature7_dis neutral"&gt; Ensure sensitive information never makes its way to your clipboard by excluding certain sources. &lt;/article&gt; &lt;h1 class="feature8 primary"&gt; Plain text snippets &lt;/h1&gt; &lt;article class="feature8_dis neutral"&gt; Remove unwanted formatting from copied text for a consistent look. &lt;/article&gt; &lt;h1 class="feature9 primary"&gt; Sneak preview &lt;/h1&gt; &lt;article class="feature9_dis neutral"&gt; Quick preview of all snippets on your Clipboard for easy access. &lt;/article&gt; &lt;/section&gt; &lt;div class="companies"&gt; &lt;ul class="comp"&gt; &lt;li class="com"&gt; &lt;a href="google.com"&gt; &lt;img class="white"src="./media/logo-google.png" alt="google.com"&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="com"&gt; &lt;a href="IBM.com"&gt; &lt;img class="white"src="./media/logo-ibm.png" alt="IBM.com"&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="com"&gt; &lt;a href="Microsoft.com"&gt; &lt;img class="white"src="./media/logo-microsoft.png" alt="Microsoft.com"&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="com"&gt; &lt;a href="https://www.hpe.com/us/en/home.html"&gt; &lt;img class="white"src="./media/logo-hp.png" alt="https://www.hpe.com/us/en/home.html"&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class"com"&gt; &lt;a href="https://en.wikipedia.org/wiki/Vector_graphics"&gt; &lt;img class="white" src="./media/logo-vector-graphics.png" alt="vector graphics"&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="lower_section"&gt; &lt;section class="lower_section"&gt; &lt;h1 class="lower_heading primary"&gt;Clipboard for iOS and Mac OS&lt;/h1&gt; &lt;article class="lower_content neutral"&gt; Available for free on the App Store Download for Mac or iOS, sync with iCloud and you're ready to start adding to your clipboard. &lt;/article&gt; &lt;div class="button"&gt; &lt;botton class="ios"&gt; Download for iOS &lt;/botton&gt; &lt;botton class="mac"&gt; Download for Mac &lt;/botton&gt; &lt;/div&gt; &lt;/section&gt; &lt;/div&gt; &lt;/main&gt; &lt;footer&gt; &lt;div class="foot"&gt; &lt;img src="media/logo.svg" alt="logo"&gt; &lt;nav class="navigation_bar"&gt; &lt;ul class="nav_list"&gt; &lt;li class="items"&gt;FAQs&lt;/li&gt; &lt;li class="items"&gt;Contact Us&lt;/li&gt; &lt;li class="items"&gt;Privacy Policy&lt;/li&gt; &lt;li class="items"&gt;Press Kit&lt;/li&gt; &lt;li class="items"&gt;Install Guide &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/div&gt; &lt;div class="media"&gt; &lt;ul class="media-list"&gt; &lt;li class="media_items primary"&gt; &lt;a href="facebook.com"&gt; &lt;img src="./media/icon-facebook.svg" alt="facebook_icon"&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="media_items primary"&gt; &lt;a href="twitter.com"&gt; &lt;img src="./media/icon-twitter.svg" alt="twitter-icon"&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="media_items primary"&gt; &lt;a href="instagram.com"&gt; &lt;img src="./media/icon-instagram.svg" alt="instagram-icon"&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/footer&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
3
5,741
Unbox + Realm native "List" object
<p><strong>Update</strong></p> <blockquote> <p>Finally author of the <code>Unbox</code> library answer my question. <a href="https://github.com/JohnSundell/Unbox/issues/156" rel="nofollow noreferrer">https://github.com/JohnSundell/Unbox/issues/156</a></p> </blockquote> <hr> <p>I'm trying to use <code>Unbox</code> to make <code>Realm</code> object with other related objects inside using <code>List</code>. The <code>JSON</code> response from server has this structure.</p> <pre><code>[ { "name": "bla bla", "desc": "bla bla", "sequential": true, "createdAt": "2017-01-23T09:58:05.095Z", "hmImages": [ { "urlBase": "https://blabla.com", "fullresPath": "/blaPath/iyba783fR81L8y.jpg", "id": "bla bla" }, { "urlBase": "https://blabla.com", "fullresPath": "/blaPath/iyba783fR81L8y.jpg", "id": "bla bla" } ], "tags": [], "id": "bla bla" }, { "name": "bla bla", "desc": "bla bla", "sequential": true, "createdAt": "2017-01-23T09:58:05.095Z", "hmImages": [ { "urlBase": "https://blabla.com", "fullresPath": "/blaPath/iyba783fR81L8y.jpg", "id": "bla bla" } ] "tags": [], "id": "bla bla" } ] </code></pre> <p>Note that root object is an <code>Array</code> of dictionaries. Every dictionary has an <code>Array</code> of image dictionaries.</p> <p>The class to save objects in <code>Realm</code> looks like this:</p> <pre><code>// MARK: - Realm final class Challenge: Object { dynamic var id = "" dynamic var name = "" dynamic var desc = "" dynamic var sequential = false dynamic var createdAt = Date() dynamic var btPlayground = "" // Relations let hmImages = List&lt;Image&gt;() let tags = List&lt;Tag&gt;() override static func primaryKey() -&gt; String? { return "id" } } // MARK: - Unboxable extension Challenge: Unboxable { convenience init(unboxer: Unboxer) throws { self.init() // Date formatter let dateFormatter = ISODateFormatter() id = try unboxer.unbox(key: "id") name = try unboxer.unbox(key: "name") desc = try unboxer.unbox(key: "desc") sequential = try unboxer.unbox(key: "sequential") createdAt = try unboxer.unbox(key: "createdAt", formatter: dateFormatter) btPlayground = try unboxer.unbox(key: "btPlayground") } } </code></pre> <p>The problem occurs with <code>hmImages</code> keypath. <code>Unbox</code> can't parse automatically and I need a way to do this.</p> <p>I tried <code>UnboxableByTransform</code> with something like this:</p> <pre><code>extension List&lt;T&gt;: UnboxableByTransform { public typealias UnboxRawValue = [[String:Any]] public static func transform(unboxedValue: Array&lt;[UnboxableDictionary]&gt;) -&gt; List&lt;T&gt;? { } } </code></pre> <p>but didn't work. Any idea?</p> <p>Thanks!</p>
3
1,299
pyrebase4 AttributeError: 'function' object has no attribute 'sign_in_with_email_and_password'
<p>I couldn't make a login screen with pyrebase4. I'm getting this error:</p> <blockquote> <p>AttributeError: 'function' object has no attribute 'sign_in_with_email_and_password'</p> </blockquote> <p>Creating user is also not possible and it gives the error:</p> <blockquote> <p>AttributeError: 'function' object has no attribute 'create_user_with_email_and_password'</p> </blockquote> <p>I'm using pyrebase4 since I read that the original pyrebase was discontinued. I saw more than one video of people just writing the code exactly like I did and theirs seem to just work. I don't understand why mine doesn't.</p> <ul> <li>Python version: 3.10.4</li> <li>Kivy version: 2.1.0</li> <li>KivyMD version: 0.104.2</li> <li>Pyrebase4 version: 4.5.0</li> </ul> <p>main.py</p> <pre><code>from kivymd.app import MDApp from kivy.lang import Builder from kivy.uix.screenmanager import ScreenManager, Screen import pyrebase class MainApp(MDApp): def build(self): return Builder.load_file('main.kv') firebaseConfig = { '''write your config here''' } firebase = pyrebase.initialize_app(firebaseConfig) auth = firebase.auth def login(self): email = self.root.get_screen(&quot;test1win&quot;).ids.user_mail.text password = self.root.get_screen(&quot;test1win&quot;).ids.password.text login = self.auth.sign_in_with_email_and_password(email, password) self.root.current = &quot;test2win&quot; print(&quot;Login Success&quot;) class WindowManager(ScreenManager): pass class TestWindow1(Screen): pass class TestWindow2(Screen): pass if __name__ == &quot;__main__&quot;: MainApp().run() </code></pre> <p>main.kv</p> <pre><code>#: include testwindow1.kv #: include testwindow2.kv WindowManager: TestWindow1: TestWindow2: </code></pre> <p>testwindow1.kv</p> <pre><code>&lt;TestWindow1&gt;: name: &quot;test1win&quot; Screen: BoxLayout: orientation: 'vertical' MDTextField: id: user_mail hint_text: &quot;E-Mail&quot; size_hint_x: 0.8 pos_hint: {&quot;center_x&quot;: 0.5} font_size: 24 mode: &quot;rectangle&quot; MDTextField: id: password hint_text: &quot;Password&quot; size_hint_x: 0.8 font_size: 24 pos_hint: {&quot;center_x&quot;: 0.5} mode: &quot;rectangle&quot; MDRaisedButton: text: &quot;Login&quot; pos_hint: {&quot;center_x&quot;: 0.5} on_release: app.login() Widget: </code></pre> <p>testwindow2.kv</p> <pre><code>&lt;TestWindow2&gt;: name: &quot;test2win&quot; Screen: MDLabel: text: &quot;You're logged in&quot; </code></pre>
3
1,420
Formatting authentication request object from VueJS properly
<p>I have a VueJS/Vuex frontend consuming an express/postgres api. </p> <p>In Postman, both registration and login work with a request like:</p> <pre><code>{ "user": { "email": "user@gmail", "password":...}} </code></pre> <p>From the Vue app, registration works as expected, but for login, instead of sending a request object like </p> <pre><code>{ "user": { "email": "user@gmail", "password":...}} </code></pre> <p>, which is what the api is expecting, it is sending only, </p> <pre><code>{ "email": "user@gmail", "password":...} </code></pre> <p>This results in the api throwing: </p> <blockquote> <p>TypeError: Cannot read property 'email' of undefined</p> </blockquote> <p>Here is my Login component:</p> <pre><code>&lt;template&gt; &lt;div class="ui stackable three column centered grid container"&gt; &lt;div class="column"&gt; &lt;h2 class="ui dividing header"&gt;Log In&lt;/h2&gt; &lt;Notification :message="notification.message" :type="notification.type" v-if="notification.message" /&gt; &lt;form class="ui form" @submit.prevent="login"&gt; &lt;div class="field"&gt; &lt;label&gt;Email&lt;/label&gt; &lt;input type="email" name="email" v-model="email" placeholder="Email" required&gt; &lt;/div&gt; &lt;div class="field"&gt; &lt;label&gt;Password&lt;/label&gt; &lt;input type="password" name="password" v-model="password" placeholder="Password" required&gt; &lt;/div&gt; &lt;button class="fluid ui primary button"&gt;LOG IN&lt;/button&gt; &lt;div class="ui hidden divider"&gt;&lt;/div&gt; &lt;/form&gt; &lt;div class="ui divider"&gt;&lt;/div&gt; &lt;div class="ui column grid"&gt; &lt;div class="center aligned column"&gt; &lt;p&gt; Don't have an account? &lt;router-link to="/signup"&gt;Sign Up&lt;/router-link&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; import Notification from '@/components/Notification' export default { name: 'LogIn', components: { Notification }, data () { return { email: '', password: '', notification: { message: '', type: '' } } }, // beforeRouteEnter (to, from, next) { // const token = localStorage.getItem('tweetr-token') // return token ? next('/') : next() // }, methods: { login () { this.$store .dispatch('login', { email: this.email, password: this.password }) .then(() =&gt; { console.log(this.$store.user) // redirect to user home this.$router.push('/') }) .catch(error =&gt; console.log(error)) } } } &lt;/script&gt; </code></pre> <p>And this is my store.js:</p> <pre><code>import Vue from 'vue' import Vuex from 'vuex' import axios from 'axios' // import SubscriptionsService from './services/SubscriptionsService' Vue.use(Vuex) const VUE_APP_ROOT_API = 'http://localhost:8000' export default new Vuex.Store({ state: { status: '', user: JSON.parse(localStorage.getItem('user')) }, mutations: { auth_request (state) { state.status = 'Signing in...' }, set_user (state, user) { state.user = user localStorage.setItem('user', JSON.stringify(user)) console.log(user) }, auth_success (state) { state.status = 'success' }, auth_error (state) { state.status = 'Invalid credentials' }, logout (state) { state.status = '' state.user = null localStorage.removeItem('user') } }, actions: { register ({ commit }, user) { return new Promise((resolve, reject) =&gt; { commit('auth_request') console.log(process.env.VUE_APP_ROOT_API) axios({ url: VUE_APP_ROOT_API + '/api/auth', data: user, method: 'POST' }) .then(async resp =&gt; { const user = resp.data.user commit('auth_success') commit('set_user', user) resolve(resp) }) .catch(err =&gt; { commit('auth_error', err) localStorage.removeItem('token') reject(err) }) }) }, login ({ commit }, user) { return new Promise((resolve, reject) =&gt; { commit('auth_request') console.log(user); axios({ url: VUE_APP_ROOT_API + '/api/auth/login', data: user, method: 'POST' }) .then(resp =&gt; { const user = resp.data.user // console.log(user) // console.log(resp) commit('auth_success') commit('set_user', user) resolve(resp) }) .catch(err =&gt; { commit('auth_error') commit('logout') reject(err) }) }) }, logout ({ commit }) { return new Promise((resolve) =&gt; { commit('logout') localStorage.removeItem('token') delete axios.defaults.headers.common['authorization'] resolve() }) } }, getters: { isAuthenticated: state =&gt; !!state.user, authStatus: state =&gt; state.status, user: state =&gt; state.user } }) </code></pre> <p>for comparison, here is my working SignUp component:</p> <pre><code>&lt;template&gt; &lt;div class="ui stackable three column centered grid container"&gt; &lt;div class="column"&gt; &lt;h2 class="ui dividing header"&gt;Sign Up, it's free!&lt;/h2&gt; &lt;form class="ui form" @submit.prevent="signup"&gt; &lt;div class="field"&gt; &lt;label&gt;Username&lt;/label&gt; &lt;input type="username" name="username" v-model="username" placeholder="Username"&gt; &lt;/div&gt; &lt;div class="field"&gt; &lt;label&gt;Email&lt;/label&gt; &lt;input type="email" name="email" v-model="email" placeholder="Email"&gt; &lt;/div&gt; &lt;div class="field" &gt; &lt;label&gt;Password&lt;/label&gt; &lt;input type="password" name="password" v-model="password" placeholder="Password"&gt; &lt;/div&gt; &lt;button class="fluid ui primary button"&gt;SIGN UP&lt;/button&gt; &lt;div class="ui hidden divider"&gt;&lt;/div&gt; &lt;/form&gt; &lt;div class="ui divider"&gt;&lt;/div&gt; &lt;div class="ui column grid"&gt; &lt;div class="center aligned column"&gt; &lt;p&gt; Got an account? &lt;router-link to="/login"&gt;Log In&lt;/router-link&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; export default { name: 'SignUp', data () { return { email: '', password: '', username: '', notification: { message: '', type: '' } } }, methods: { signup: function () { let data = { user: { email: this.email, password: this.password, username: this.username } } this.$store.dispatch('register', data) .then(() =&gt; this.$router.push('/')) .catch(err =&gt; console.log(err)) }, } } &lt;/script&gt; </code></pre> <p>How do I format the request object to match what the api expects?</p>
3
3,499
Fun with US and UK dates on a new server
<p>I have just had the task of moving an old ASP website / SQL DB to a new dedicated OVH server (French - all defaults set to US-Eng).</p> <p>The DB has moved from SQL 2005 to SQL 2012 (web edition 64 bit).</p> <p>I am having the old issue of date formats showing up as US format on the website e.g <code>8/3/2016</code> instead of <code>03/08/2016</code>. This is even though in the database they are stored as ISO Date <code>2016-08-03</code> etc.</p> <p>I enter the dates on the ASP Classic, website as UK format e.g. <code>03/08/2016</code> and convert them to ISO format <code>2016-08-03</code> in the SQL that is passed to the Stored Procedure that has SET DATEFORMAT YMD at the top of it.</p> <p>If I check the tables in the DB they are all stored correctly as ISO dates.</p> <p>I have made sure all the SQL Logins to the DB have &quot;British English&quot; selected as their &quot;Default Language&quot;.</p> <p>If I view the database properties under options the Default Language is British English.</p> <p>If I view the server properties under General-&gt;Language it's English (United States) but under Advanced-&gt;Default Language it's British English.</p> <p>The dates are getting stored as ISO correctly as if I do a DATEDIFF(DAY,Stamp,GETDATE())=0 I can see all the records even though they are showing up on the website as US format 8/3/2016 (Why there are no zeros in front of US dates I don't know).</p> <p>The ASP code hasn't changed or the DB code it was just ported into this new dedicated server and now I am getting these issues. I am sure I solved something like this ages ago just by changing the default login language but that doesn't seem to work on this box.</p> <p>I am getting lots of Primary Key/Index errors due to duplicate insertions due to the dates (mixing up US/UK) from a .NET app I have that uses the Betfair API to get racing data e.g</p> <pre><code>EXEC dbo.usp_net_insert_betfair_market_selection @MarketID = 125932808, @SelectionID = 10593225, @Racedatetime = '2016-08-03 15:10:00', @MarketType = 'WIN', @HorseName = 'She Done Good'; </code></pre> <blockquote> <p>Violation of PRIMARY KEY constraint 'PK_BETFAIR_MARKET_SELECTIONS'. Cannot insert duplicate key in object 'dbo.BETFAIR_MARKET_SELECTIONS'. The duplicate key value is (719859, WIN, Mar 8 2016 3:10PM).</p> </blockquote> <p>However if I copy that EXEC statement and run it direct in a query analyser window it runs WITHOUT ANY ERROR.</p> <p>I have been searching the web and I have seen someone suggest putting this code at the top of all ASP pages that show dates to force it show in UK format &gt; <a href="https://www.webwiz.co.uk/kb/asp-tutorials/date-time-settings.htm" rel="nofollow noreferrer">https://www.webwiz.co.uk/kb/asp-tutorials/date-time-settings.htm</a></p> <pre><code>'* Set the server locale to UK Session.LCID = 2057 </code></pre> <p>This has worked on SOME pages but I have never had to do this before.</p> <p>On pages with long lists of records and dates in one column I have wrapped the date in CONVERT(varchar, GETDATE(),103) in the SQL and it returns correctly on the page.</p> <p>I am confused though as I have never had to do this on the old set up and it seems like there must be some setting that needs to change to fix all this on the new server (SQL and Web IIS 8) on same box.</p> <p>I have tried going into the .NET Globalization for the site and changing Culture and UI Culture to English (en). However that didn't fix everything.</p> <p>The &quot;Language&quot; preferences on the machine are set to English (UK) although I wouldn't have though that would have made a difference.</p> <p>If I run this code in a query analyser either RD into the box, or through my local SQL console connected to the machine over the network</p> <pre><code>select name ,alias, dateformat from syslanguages where langid = (select value from master..sysconfigures where comment = 'default language') </code></pre> <p>In a query window (Remote Desktop into server) I get back</p> <pre><code>Name Alias dateformat British British English dmy </code></pre> <h2 id="question">Question</h2> <p>So it seems like something to do with the connection between the ASP website or .NET app and the server/database. Something I have missed or need to change as this all worked fine on the old WebServer -&gt; Database Server setup we had.</p> <p>Is there something I have overlooked to ensure dates are shown as UK on the website without editing every ASP page and SQL that contains dates as I never had to do that for the old setup.</p>
3
1,325
mongodb GeoJSON coordinates must be an array
<p>There's a requirement to search some locations in a given region. And here is an example of my test data in mongo:</p> <pre><code>{ &quot;_id&quot; : &quot;insititution_NPqTrcysjKV&quot;, &quot;phone&quot; : &quot;18080808088&quot;, &quot;name&quot; : &quot;Insititution 1&quot;, &quot;address&quot; : &quot;xxxxxxxxxxxxx&quot;, &quot;city&quot; : &quot;New York&quot;, &quot;location&quot; : { &quot;type&quot; : &quot;Point&quot;, &quot;coordinates&quot; : [ 121.62764, 29.89805 ] }, &quot;includeLessions&quot; : [ &quot;English&quot; ] } </code></pre> <p>I've got a list of such entries in my mongodb. and here goes my query in Robo3T:</p> <pre><code>db.Insititution.find( { location: { $geoIntersects: { $geometry: { type: &quot;Polygon&quot; , coordinates: [ [ [ 121.33, 29.899 ], [ 121.33, 29.770 ], [ 121.67, 29.770 ], [ 121.67, 29.899 ], [ 121.33, 29.899 ] ] ] } } } } ) </code></pre> <p>It's works in robo3t, but in my project, I did like this:</p> <pre><code> var where = { location: { $geoIntersects: { $geometry: { type: &quot;Polygon&quot;, coordinates: [ [longitudeMin, latitudeMin], [longitudeMin, latitudeMax], [longitudeMax, latitudeMax], [longitudeMax, latitudeMin], [longitudeMin, latitudeMin] ] } } } } return promiseUtils.mongoNativeFindPromise(this.modelName, where); // function in promiseUtils: exports.mongoNativeFindPromise = async function (modelName, where, options) { const db = await MongoClient.connect(uri); try { let collection = db.db(mongoDBSettings.database); var cusor = await collection.collection(modelName).find(where, options); return await cusor.toArray(); } catch (err) { throw err; } finally { db.close(); } }; </code></pre> <p>and this is exactly what the 'where' variable goes like when run the code: <a href="https://i.stack.imgur.com/cxdnh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cxdnh.png" alt="enter image description here" /></a> but mongo return an error: GeoJSON coordinates must be an array Can anybody help?</p>
3
1,047
Android Studio loses files after git branch change
<p>As the title says, Android studio loses/removes project directories on branch change. This happens for the same branch every time. It's a flutter project, repository is hosted on github. I tried creating a new branch from this one and the same thing happens. When checking out other branches, the project directories are all there. <a href="https://i.stack.imgur.com/DrwWz.png" rel="nofollow noreferrer">Android studio</a></p> <h1>Update:</h1> <p>flutter doctor:</p> <pre><code>[✓] Flutter (Channel stable, 2.5.1, on macOS 11.6 20G165 darwin-x64, locale en-HR) [✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0) [✓] Xcode - develop for iOS and macOS [✓] Chrome - develop for the web [✓] Android Studio (version 4.1) [✓] VS Code (version 1.56.2) [✓] VS Code (version 1.55.2) [✓] Connected device (1 available) </code></pre> <p>.gitignore:</p> <pre><code># Created by https://www.gitignore.io/api/dart,flutter,visualstudiocode # Edit at https://www.gitignore.io/?templates=dart,flutter,visualstudiocode ### Dart ### # See https://www.dartlang.org/guides/libraries/private-files # Files and directories created by pub .dart_tool/ .packages build/ # If you're building an application, you may want to check-in your pubspec.lock pubspec.lock # Directory created by dartdoc # If you don't generate documentation locally you can remove this line. doc/api/ # Avoid committing generated Javascript files: *.dart.js *.info.json # Produced by the --dump-info flag. *.js # When generated by dart2js. Don't specify *.js if your # project includes source files written in JavaScript. *.js_ *.js.deps *.js.map ### Flutter ### # Flutter/Dart/Pub related **/doc/api/ .flutter-plugins .flutter-plugins-dependencies .pub-cache/ .pub/ # IntelliJ related *.iml *.ipr *.iws .idea/ # Android related **/android/**/gradle-wrapper.jar **/android/.gradle **/android/captures/ **/android/gradlew **/android/gradlew.bat **/android/local.properties **/android/**/GeneratedPluginRegistrant.java **/android/key.properties # iOS/XCode related **/ios/**/*.mode1v3 **/ios/**/*.mode2v3 **/ios/**/*.moved-aside **/ios/**/*.pbxuser **/ios/**/*.perspectivev3 **/ios/**/*sync/ **/ios/**/.sconsign.dblite **/ios/**/.tags* **/ios/**/.vagrant/ **/ios/**/DerivedData/ **/ios/**/Icon? **/ios/**/Pods/ **/ios/**/.symlinks/ **/ios/**/profile **/ios/**/xcuserdata **/ios/.generated/ **/ios/Flutter/App.framework **/ios/Flutter/Flutter.framework **/ios/Flutter/Generated.xcconfig **/ios/Flutter/app.flx **/ios/Flutter/app.zip **/ios/Flutter/flutter_assets/ **/ios/ServiceDefinitions.json **/ios/Runner/GeneratedPluginRegistrant.* **ios/Flutter/flutter_export_environment.sh **ios/Flutter/.last_build_id **ios/Flutter/Flutter.podspec # Exceptions to above rules. !**/ios/**/default.mode1v3 !**/ios/**/default.mode2v3 !**/ios/**/default.pbxuser !**/ios/**/default.perspectivev3 !/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages ### VisualStudioCode ### .vscode/* !.vscode/tasks.json !.vscode/extensions.json # Miscellaneous *.class *.log *.pyc *.swp .DS_Store .atom/ .buildlog/ .svn/ ### VisualStudioCode Patch ### # Ignore all local history of files .history # End of https://www.gitignore.io/api/dart,flutter,visualstudiocode *.env </code></pre>
3
1,224
How to display current date in php?
<p>I am using the wordpress plugin &quot;<a href="https://de.wordpress.org/plugins/woocommerce-gift-coupon/" rel="nofollow noreferrer">WooCommerce Gift Coupon</a>&quot; which generates a PDF sent as attachment to the customer via mail. I want to display the current date in that PDF and already found the php file to edit (mail-template.php).</p> <p>I tried to place the following code at several places within the body tag with no success:</p> <pre><code>&lt;?php $currentDateTime = date('Y-m-d H:i:s'); echo $currentDateTime; ?&gt; </code></pre> <p>I also tried it without opening and closing php tags. I either get an error or it displays the code as it is in the PDF document.</p> <p>Here is the full code of mail-template.php:</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-html lang-html prettyprint-override"><code>&lt;?php /** * WooCommerce Gift Coupon Mail Template * * Sets up the email template * * @author WooCommerce Gift Coupon * @package WooCommerce Gift Coupon/Mail Template */ if ( ! defined( 'ABSPATH' ) ) { exit; } /** * Generate HTML PDF. * * @param array $data Coupon data. * @param bool $preview Check if is preview. * @return string */ function woocommerce_gift_coupon_generate_pdf_mail( $data, $preview = false ) { $woocommerce_gift_coupon_hide_amount = get_option( 'woocommerce_gift_coupon_hide_amount' ); $woocommerce_gift_coupon_show_logo = get_option( 'woocommerce_gift_coupon_show_logo' ); $woocommerce_gift_coupon_logo = get_option( 'woocommerce_gift_coupon_logo' ); $woocommerce_gift_coupon_info_paragraph_type = get_option( 'woocommerce_gift_coupon_info_paragraph_type' ); $woocommerce_gift_coupon_info_paragraph = get_option( 'woocommerce_gift_coupon_info_paragraph' ); $woocommerce_gift_coupon_info_footer = get_option( 'woocommerce_gift_coupon_info_footer' ); $woocommerce_gift_coupon_title_type = get_option( 'woocommerce_gift_coupon_title_type' ); $woocommerce_gift_coupon_title_h = get_option( 'woocommerce_gift_coupon_title_h' ); $woocommerce_gift_coupon_subject = get_option( 'woocommerce_gift_coupon_subject' ); $woocommerce_gift_coupon_bg_color_header = get_option( 'woocommerce_gift_coupon_bg_color_header' ); $woocommerce_gift_coupon_bg_color_footer = get_option( 'woocommerce_gift_coupon_bg_color_footer' ); $woocommerce_gift_coupon_bg_color_title = get_option( 'woocommerce_gift_coupon_bg_color_title' ); $title_coupon = $woocommerce_gift_coupon_title_h; $description_coupon = wpautop( $woocommerce_gift_coupon_info_paragraph ); // Convert logo to base64. if ( !empty( $woocommerce_gift_coupon_logo ) ) { $woocommerce_gift_coupon_logo_type = pathinfo( $woocommerce_gift_coupon_logo, PATHINFO_EXTENSION ); $woocommerce_gift_coupon_logo_data = file_get_contents( $woocommerce_gift_coupon_logo ); if ( !empty( $woocommerce_gift_coupon_logo_type ) &amp;&amp; !empty( $woocommerce_gift_coupon_logo_data ) ) { $woocommerce_gift_coupon_logo_base64 = 'data:image/' . $woocommerce_gift_coupon_logo_type . ';base64,' . base64_encode( $woocommerce_gift_coupon_logo_data ); } } if ( empty( $preview ) ) { // Get title or description coupon. if ( $woocommerce_gift_coupon_title_type &gt; 0 || $woocommerce_gift_coupon_info_paragraph_type &gt; 0 ) { $data_coupon = get_post( $data['coupon_id'] ); if ( ! empty( $data_coupon ) ) { // Get custom title or product coupon title. if ( $woocommerce_gift_coupon_title_type &gt; 0 ) { $title_coupon = $data_coupon-&gt;post_title; } // Get custom description or product coupon description. if ( $woocommerce_gift_coupon_info_paragraph_type &gt; 0 ) { $description_coupon = empty( $data_coupon-&gt;post_excerpt ) ? wp_trim_words( $data_coupon-&gt;post_content, 55, '...' ) : $data_coupon-&gt;post_excerpt; } } } } else { if ( empty( $title_coupon ) ) { $title_coupon = 'Lorem ipsum dolor sit amet'; } if ( empty( $description_coupon ) ) { $description_coupon = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'; } } $email = '&lt;!DOCTYPE html&gt; &lt;html ' . get_language_attributes() . '&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=' . get_bloginfo( 'charset' ) . '" /&gt; &lt;title&gt;' . get_bloginfo( 'name', 'display' ) . '&lt;/title&gt;'; $email .= woocommerce_gift_coupon_generate_email_styles(); $email .= '&lt;/head&gt; &lt;body bgcolor="#f5f5f5" leftmargin="0" marginwidth="0" topmargin="0" marginheight="0" offset="0"&gt; &lt;div class="page-break-inside: avoid"&gt; &lt;table border="0" cellpadding="0" cellspacing="0" height="100%" width="100%" id="bodyTable" bgcolor="#f5f5f5"&gt; &lt;tr&gt; &lt;td align="center" valign="top"&gt; &lt;table bgcolor="#f5f5f5" border="0" cellpadding="0" cellspacing="0" width="595"&gt; &lt;tr&gt; &lt;td align="center" valign="top"&gt; &lt;table border="0" cellpadding="0" cellspacing="0" width="100%" bgcolor="#fff"&gt; &lt;tr&gt; &lt;td align="center" valign="top"&gt; &lt;table border="0" cellpadding="0" cellspacing="0" width="595"&gt; &lt;tr&gt; &lt;td align="center" valign="top" width="595"&gt; &lt;table border="0" cellpadding="20" cellspacing="0" width="100%"&gt; &lt;tr&gt; &lt;td align="center" valign="top" bgcolor="' . $woocommerce_gift_coupon_bg_color_header . '"&gt;'; if ( $woocommerce_gift_coupon_show_logo &gt; 0 &amp;&amp; !empty( $woocommerce_gift_coupon_logo_base64 ) ) { $email .= '&lt;img src="' . $woocommerce_gift_coupon_logo_base64 . '" width="190" /&gt;'; } $email .= ' &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td align="center" valign="top" bgcolor="' . $woocommerce_gift_coupon_bg_color_title . '"&gt; &lt;h1&gt;' . $title_coupon . '&lt;/h1&gt;'; if ( $woocommerce_gift_coupon_hide_amount &lt; 1 ) { $email .= '&lt;h2&gt;' . $data['price'] . '&lt;/h2&gt;'; } $email .= '&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td align="center" valign="top" bgcolor="#ccc"&gt; &lt;h3&gt;' . esc_html__( 'Code', WOOCOMMERCE_GIFT_COUPON_TEXT_DOMAIN ) . ': ' . $data['code'] . '&lt;/h3&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td align="left" valign="middle"&gt; ' . $description_coupon . ' &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/td&gt; &lt;/tr&gt; &lt;table bgcolor="' . $woocommerce_gift_coupon_bg_color_footer . '" border="0" cellpadding="0" cellspacing="0" width="595"&gt; &lt;tr&gt; &lt;td align="center" valign="top"&gt; &lt;table border="0" cellpadding="0" cellspacing="0" width="100%"&gt; &lt;tr&gt; &lt;td align="center" valign="top"&gt; &lt;table border="0" cellpadding="0" cellspacing="0" width="595"&gt; &lt;tr&gt; &lt;td align="center" valign="top" width="595"&gt; &lt;table border="0" cellpadding="20" cellspacing="0" width="100%"&gt; &lt;tr&gt; &lt;td align="center" valign="top"&gt; ' . $woocommerce_gift_coupon_info_footer . ' &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;'; return $email; } /** * Add inline styles to PDF template. */ function woocommerce_gift_coupon_generate_email_styles() { $styles = ' &lt;style type="text/css"&gt; html { background-color:#fff; margin:0; padding:0; } body{ height:100%!important; margin:0; padding:0; width:100%!important; font-family:DejaVu Sans, Helvetica; } table{ border-collapse:collapse; } table[id=bodyTable] { table-layout: fixed; max-width:100%!important; width: 100%!important; min-width: 100%!important; margin:40px 0;color:#7A7A7A; font-weight:normal; } table img, table a img{ border:0; outline:none; text-decoration:none; height:auto; line-height:100%; } table a{ text-decoration:none!important; border-bottom:1px solid #ff5a34; } table a:hover{ text-decoration:none!important; border-bottom:1px solid #1A242E; } table h1, table h2, table h3{ color:#fff; font-weight:bold; line-height:100%; text-align:center; letter-spacing:normal; font-style: normal; margin:0!important; padding:0!important; } table h1 { text-transform:uppercase; display: block; font-family:DejaVu Sans, Helvetica; font-size: 56px; line-height: 1.385em; font-weight: normal; } table h2 { text-transform:uppercase; font-size: 86px; display: block; } table h3 { color:#252525; line-height:100%; font-size:24px; } &lt;/style&gt;'; return $styles; }</code></pre> </div> </div> </p> <p>How can I display the current date for example below the coupon code or in the top left/right corner? <a href="https://i.stack.imgur.com/eCMpO.png" rel="nofollow noreferrer">Here is a picture of the generated PDF Coupon as Example</a></p> <p>Many thanks in advance for your support!</p>
3
8,991
How to display a dynamic map using Tabs and SliverGrid
<p>I have a Model called service provider that contains a the following data:</p> <pre><code>class ServiceProvider { final String logoUrl; final int lowerPrice; final String name; final int numberOfOrders; final int onTime; final int ordersPercentage; final int upperPrice; final double rating; final Map&lt;dynamic,dynamic&gt; albums; }; } </code></pre> <p>I am able to parse all the data correctly without any problems however I hit a brick wall when I tried to display the albums map basically its a map of strings with lists as values looking like this :</p> <pre><code> albums: { &quot;Nature&quot; :[ &quot;imageURLHere&quot;, &quot;imageURLHere&quot;, &quot;imageURLHere&quot; ], &quot;Wedding&quot; : [ &quot;imageURLHere&quot; ], &quot;Portraits&quot; : [ &quot;imageURLHere&quot;, &quot;imageURLHere&quot; ], } </code></pre> <p>My idea was to use a Tabs to represent each Key (Nature,wedding,portrait) and use a SliverGrid to display the images.</p> <p>I used a Custom Tab Builder to be able to build the TabBar and TabViews Dynamically, however I cannot think of a way to make the SliverGrid Inside to display each image list.</p> <p>basically I can only show one of the lists 3 times.</p> <p>keeping in mind that the number of albums and number of images is variable.</p> <p>This is the custom tab Builder that I am using</p> <pre><code> final int itemCount; final IndexedWidgetBuilder tabBuilder; final IndexedWidgetBuilder pageBuilder; final Widget? stub; final ValueChanged&lt;int&gt;? onPositionChange; final ValueChanged&lt;double&gt;? onScroll; final int? initPosition; CustomTabView({ required this.itemCount, required this.tabBuilder, required this.pageBuilder, this.stub, this.onPositionChange, this.onScroll, this.initPosition, }); @override _CustomTabsState createState() =&gt; _CustomTabsState(); } class _CustomTabsState extends State&lt;CustomTabView&gt; with TickerProviderStateMixin { TabController? controller; int? _currentCount; int? _currentPosition; @override void initState() { _currentPosition = widget.initPosition ?? 0; controller = TabController( length: widget.itemCount, vsync: this, initialIndex: _currentPosition!, ); controller!.addListener(onPositionChange); controller!.animation!.addListener(onScroll); _currentCount = widget.itemCount; super.initState(); } @override void didUpdateWidget(CustomTabView oldWidget) { if (_currentCount != widget.itemCount) { controller!.animation!.removeListener(onScroll); controller!.removeListener(onPositionChange); controller!.dispose(); if (widget.initPosition != null) { _currentPosition = widget.initPosition; } if (_currentPosition! &gt; widget.itemCount - 1) { _currentPosition = widget.itemCount - 1; _currentPosition = _currentPosition! &lt; 0 ? 0 : _currentPosition; if (widget.onPositionChange is ValueChanged&lt;int&gt;) { WidgetsBinding.instance!.addPostFrameCallback((_){ if(mounted) { widget.onPositionChange!(_currentPosition!); } }); } } _currentCount = widget.itemCount; setState(() { controller = TabController( length: widget.itemCount, vsync: this, initialIndex: _currentPosition!, ); controller!.addListener(onPositionChange); controller!.animation!.addListener(onScroll); }); } else if (widget.initPosition != null) { controller!.animateTo(widget.initPosition!); } super.didUpdateWidget(oldWidget); } @override void dispose() { controller!.animation!.removeListener(onScroll); controller!.removeListener(onPositionChange); controller!.dispose(); super.dispose(); } @override Widget build(BuildContext context) { if (widget.itemCount &lt; 1) return widget.stub ?? Container(); return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: &lt;Widget&gt;[ Container( alignment: Alignment.center, child: TabBar( isScrollable: true, controller: controller, labelColor: Theme.of(context).primaryColor, unselectedLabelColor: Theme.of(context).hintColor, indicator: BoxDecoration( border: Border( bottom: BorderSide( color: Theme.of(context).primaryColor, width: 2, ), ), ), tabs: List.generate( widget.itemCount, (index) =&gt; widget.tabBuilder(context, index), ), ), ), Expanded( child: TabBarView( controller: controller, children: List.generate( widget.itemCount, (index) =&gt; widget.pageBuilder(context, index), ), ), ), ], ); } onPositionChange() { if (!controller!.indexIsChanging) { _currentPosition = controller!.index; if (widget.onPositionChange is ValueChanged&lt;int&gt;) { widget.onPositionChange!(_currentPosition!); } } } onScroll() { if (widget.onScroll is ValueChanged&lt;double&gt;) { widget.onScroll!(controller!.animation!.value); } } } </code></pre> <p>and this is where I use it and build my SliverGrid inside it</p> <pre><code>class IndividualServiceProviderScreen extends StatelessWidget { final ServiceProvider serviceProvider; const IndividualServiceProviderScreen({ required this.serviceProvider, }); @override Widget build(BuildContext context) { List data = serviceProvider.albums.keys.toList(); int currentPosition = 1; return DefaultTabController( length: serviceProvider.albums.keys.length, child: Scaffold( appBar: AppBar( title: Text(serviceProvider.name), ), body: NestedScrollView( physics: BouncingScrollPhysics( parent: AlwaysScrollableScrollPhysics()), headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return &lt;Widget&gt;[ SliverToBoxAdapter( child: ServiceProviderDetailsCard( serviceProvider: serviceProvider, ), ), ]; }, body: CustomTabView( initPosition: currentPosition, itemCount: data.length, tabBuilder: (context, index) =&gt; Tab(text: data[index]), pageBuilder: (context, index) =&gt; CustomScrollView( physics: BouncingScrollPhysics( parent: AlwaysScrollableScrollPhysics()), slivers: [ SliverGrid( gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent( maxCrossAxisExtent: 200, mainAxisSpacing: 10.0, crossAxisSpacing: 10.0, childAspectRatio: 1.0, ), delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { // I want to be able to use the CustomTabBuilder index inside //here but i can't pass the index inside because //it gets overridden by the index of the sliver builder if (index &lt; serviceProvider.albums[data[0]].length) { return Image( image: NetworkImage( serviceProvider.albums[data[0]][index])); } }, childCount: serviceProvider.albums[data[0]].length, ), ) ], ), onPositionChange: (index) { print('current position: $index'); currentPosition = index; }, ), ), bottomNavigationBar: Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.only( topRight: Radius.circular(10), topLeft: Radius.circular(10)), boxShadow: [ BoxShadow( color: Colors.black38, spreadRadius: 0, blurRadius: 10), ], ), child: ClipRRect( borderRadius: BorderRadius.only( topLeft: Radius.circular(10.0), topRight: Radius.circular(10.0), ), child: Padding( padding: const EdgeInsets.fromLTRB(50, 8, 50, 8), child: ElevatedButton( style: ElevatedButton.styleFrom(minimumSize: Size(20, 50)), onPressed: () =&gt; {print(&quot;Booking&quot;)}, child: Text( &quot;Book now&quot;, style: TextStyle(fontSize: 24), )), ), ), ) ) ); } } </code></pre> <p>I tried using the onPositionChange function to pass the current index of the TabView inside the SliverGrid's delegate, however that still doesn't work because the images are loaded after the change happens and that is not the correct behavior</p> <p><a href="https://i.stack.imgur.com/d0PaV.png" rel="nofollow noreferrer">This is what I managed to build so far </a></p> <p>But as mentioned above whenever I change tabs same images are displayed, and when I use currentIndex the images do change but to the previous index not the actually pressed tab.</p>
3
4,803
Input should be equal to a list, but isn't
<p>A friend gave me the idea to write a program that asks you English words and you have to translate them in German and reverse. </p> <p>So the program asks a word and checks the input if it matches the actual translation.</p> <p>So the user gives an input of which Unit he/she wants to study. This input is stored in a variable. Now I have a list of the words of Unit 1. Then the program randomly chooses a word in the List. This word is then printed and the user enters his answer. Then using .index I find the position of the word asked and search for the same position in a second list. </p> <p>My problem is that the Unit input is seen as a string instead of being one of the lists I made. So then the user just gets asked for letter from this input. </p> <p>I want to somehow have this input equal the name of a list I have and work.(The Lists are actually larger, I cut them so it is a little easier to read)</p> <p>The code is here:</p> <pre><code>import random U1_E = ["consider (sb) to be …","describe (sb) as ...","proud to + infinitive" ] U1_D = ["erachten, wähnen","erachten, wähnen","beschreiben" ] U5_E = ["confortable","crowded","delicious","efficient","fashionable", ] U5_D = ["bequem","überfüllt","köstlich","effizient","modisch" ] Num = ["first","second","third","forth","fifth","sixth","7th","8th","9th", ] Unit_Eng = ["U1_E","U2_E","U3_E","U4_E","U5_E","U6_E","U7_E","U8_E" ] good_points = 0 bad_points = 0 Name_of_Agent = input("Can you please give me your name?") Select_Unit = input(Name_of_Agent + ",which Unit would you like to train? [Ux_E/Ux_D]") Num_of_Words = int(input("How many words would you like?")) if (Select_Unit in Unit_Eng): for i in range(0,Num_of_Words): Word_E = random.choice(Select_Unit) Select_Unit_oposite = Select_Unit[:3] + "D" Word_D = Select_Unit_oposite[Select_Unit.index(Word_E)] if (input("The "+Num[i]+" Word is:"+Word_E+":") == Word_D): print("Well done, you got it right!") good_points = good_points + 1 else: print("The word you gave is wrong, the right answer is:", Word_D) bad_points = bad_points + 1 print("Your total score is:",good_points- bad_points) input("Press Enter to close the program") </code></pre>
3
1,338
Hash password not saved in the password column
<p>I am trying to store hash password in my <code>users</code> table while registration. Please see my code:</p> <p><strong>users_controller.rb</strong></p> <pre><code>def login @title = 'Login' #render layout: 'login' end def create_login user = User.authenticate(params[:user][:username], params[:user][:password]) if user log_in user redirect_to '/admin' else flash[:danger] = 'Invalid email/password combination' # Not quite right! redirect_to :back end end def register @user = User.new @title = 'Register' end def create_register params[:user][:uniq_id] = generate_uniq @user = User.new(create_user_params) #raise @user.inspect respond_to do |format| if @user.save format.html { redirect_to :success, success: 'Registration was successfully created.' } format.json { redirect_to :register, status: :created, location: @users } else format.html { render :register } format.json { render json: @users.errors, status: :unprocessable_entity } end end end private def create_user_params params.require(:user).permit(:uniq_id, :name, :username, :email, :password, :password_confirmation, :password_salt, :dob, :address) end </code></pre> <p><strong>register.html.erb</strong></p> <pre><code>&lt;%= form_tag("/register", method: "post") do %&gt; &lt;%#= form_tag(@user) do |f| %&gt; &lt;% if @user.errors.any? %&gt; &lt;div id="error_explanation"&gt; &lt;h2&gt;&lt;%= pluralize(@user.errors.count, "error") %&gt; prohibited this user from being saved:&lt;/h2&gt; &lt;ul&gt; &lt;% @user.errors.full_messages.each do |message| %&gt; &lt;li&gt;&lt;%= message %&gt;&lt;/li&gt; &lt;% end %&gt; &lt;/ul&gt; &lt;/div&gt; &lt;% end %&gt; &lt;%= text_field :user, :name, placeholder:'NAME', required: true %&gt; &lt;div style="position: relative;"&gt; &lt;span id="chk-username" style="position: absolute;font-size: 12px;right: 2%; bottom: 5%; z-index: 9; display: block;"&gt;&lt;/span&gt; &lt;%= text_field :user, :username, placeholder:'USERNAME', 'data-validate':"/users/check_username", required: true %&gt; &lt;/div&gt; &lt;div style="position: relative;"&gt; &lt;span id="chk-email" style="position: absolute;font-size: 12px;right: 2%; bottom: 5%; z-index: 9; display: block;"&gt;&lt;/span&gt; &lt;%= text_field :user, :email, placeholder:'EMAIL', 'data-validate':"/users/check_email", required: true %&gt; &lt;/div&gt; &lt;%= password_field :user, :password, placeholder:'PASSWORD', required: true %&gt; &lt;%= password_field :user, :password_confirmation, placeholder:'CONFIRM PASSWORD', required: true %&gt; &lt;div class="submit"&gt; &lt;input type="submit" value="REGISTER" &gt; &lt;input type="button" onclick="location.href = '&lt;%= request.base_url %&gt;/login'" value="LOGIN" &gt; &lt;/div&gt; &lt;p&gt;&lt;a href="#"&gt;Forgot Password ?&lt;/a&gt;&lt;/p&gt; &lt;% end %&gt; </code></pre> <p><strong>user.rb</strong></p> <pre><code>class User &lt; ActiveRecord::Base #has_secure_password attr_accessor :password before_save :encrypt_password validates :name, presence: true validates :name, length: { minumum:2, maximum: 30 } validates :password, :presence =&gt;true, :length =&gt; { :minimum =&gt; 6, :maximum =&gt; 40 }, :confirmation =&gt;true validates :username, :presence =&gt; true, :uniqueness =&gt; { :case_sensitive =&gt; false } email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, :presence =&gt; true, :format =&gt; { :with =&gt; email_regex }, :uniqueness =&gt; { :case_sensitive =&gt; false } def self.authenticate(input_username, input_password) user = find_by_username(input_username) if user &amp;&amp; user.password == BCrypt::Engine.hash_secret(input_password, user.password_salt) user else nil end end def encrypt_password if password.present? self.password_salt = BCrypt::Engine.generate_salt self.password = BCrypt::Engine.hash_secret(password, password_salt) end end end </code></pre> <p><strong>routes.rb</strong></p> <pre><code>get 'register' =&gt; 'users#register' post 'register' =&gt; 'users#create_register' </code></pre> <p>Here is my database table.</p> <p><strong>users.sql (customize table)</strong></p> <pre><code>+----+----------+------------+-----------+----------------+ | id | name | username | password | password_salt | +----+----------+------------+-----------+----------------+ | 1 | chinmay | chinu | NULL |$2a$10$15fWDt.. | | 2 | sanjib | sanjib | NULL |$2a$10$85DyMr.. | +----+----------+------------+-----------+----------------+ </code></pre> <p>I get <code>NULL</code> value in my <code>password</code> column. Please help me and let me know where the error is in my code.</p>
3
2,193
Drawing a line after an arbitrary number of SVG tspan elements
<p>I'd like to use SVG to create an XSLT template to generate PDFs of orders placed in a system. The idea is that I have N order positions (say between 3 and 10) which I want displayed row by row and with a horizontal line after the bottom-most row and the usual total row.</p> <p>Here's is an illustration: <a href="https://i.stack.imgur.com/R4MMn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R4MMn.png" alt="How to position the line (and last order row) relative to the last position row?"></a></p> <p>My problem is that I cannot find out how to position the horizontal line and the final total row relative the last order position row. Here's what I have so far:</p> <p><a href="http://jsfiddle.net/hg3hzd4j/" rel="nofollow noreferrer">http://jsfiddle.net/hg3hzd4j/</a></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="no"?&gt; &lt;svg width="300" height="250" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"&gt; &lt;g transform="translate(10, 15)"&gt; &lt;rect x="0" y="0" height="100%" width="100%" style="stroke:#000; fill: #FFFF00" fill-opacity="0.2" stroke-opacity="0.2"&gt;&lt;/rect&gt; &lt;g transform="translate(10, 0)"&gt; &lt;line id="guide1" x1="160" y1="0" x2="160" y2="100%" style="stroke:rgb(255,0,0);stroke-width:1" /&gt; &lt;line id="guide2" x1="220" y1="0" x2="220" y2="100%" style="stroke:rgb(255,0,0);stroke-width:1" /&gt; &lt;g&gt; &lt;text x="0" y="20"&gt; &lt;tspan&gt;Mono layer&lt;/tspan&gt; &lt;tspan x="100"&gt;$50&lt;/tspan&gt; &lt;tspan x="160" style="text-anchor:end"&gt;4&lt;/tspan&gt; &lt;tspan x="220" style="text-anchor:end"&gt;$200&lt;/tspan&gt; &lt;tspan x="0" dy="20"&gt;Single layer&lt;/tspan&gt; &lt;tspan x="100"&gt;$25&lt;/tspan&gt; &lt;tspan x="160" style="text-anchor:end"&gt;3&lt;/tspan&gt; &lt;tspan x="220" style="text-anchor:end"&gt;$75&lt;/tspan&gt; &lt;tspan x="0" dy="20"&gt;Double layer&lt;/tspan&gt; &lt;tspan x="100"&gt;$45&lt;/tspan&gt; &lt;tspan x="160" style="text-anchor:end"&gt;3&lt;/tspan&gt; &lt;tspan x="220" style="text-anchor:end"&gt;$135&lt;/tspan&gt; &lt;tspan x="0" dy="20"&gt;Triple layer&lt;/tspan&gt; &lt;tspan x="100"&gt;$65&lt;/tspan&gt; &lt;tspan x="160" style="text-anchor:end"&gt;1&lt;/tspan&gt; &lt;tspan x="220" style="text-anchor:end"&gt;$65&lt;/tspan&gt; &lt;!-- I'd like a line here --&gt; &lt;!-- And the grand total row --&gt; &lt;tspan x="0" dy="30"&gt;Total&lt;/tspan&gt; &lt;tspan x="100"&gt;&lt;/tspan&gt; &lt;tspan x="160" style="text-anchor:end"&gt;11&lt;/tspan&gt; &lt;tspan x="220" style="text-anchor:end"&gt;$475&lt;/tspan&gt; &lt;/text&gt; &lt;line x1="0" y1="150" x2="100%" y2="150" style="stroke:rgb(0,0,0);stroke-width:2" /&gt; &lt;/g&gt; &lt;/g&gt; &lt;/g&gt; &lt;/svg&gt; </code></pre> <p>I'm by no means an expert so any suggestion is greatly appreciated. I thought I could define each position row with something similar to a DIV and that everything would shift down automatically. But obviously not.</p>
3
1,511
Constant label updation from different class in javafx-fxml
<p>I am unable to change the text of my label from other class. I need to constantly update date and time on the main screen, while I may be able to perform other functions too, simultaneously. I have used a <em>TimeSetting</em> class, which extends Thread and in it's run() method, I've called the updation command in an infinite loop, using setText() and then slept the method for a second. But on running this, nothing happens and on closing the output window, I get an <strong>error</strong> saying <strong><em>NullPointerExcpetion</em></strong></p> <p>Here's the code for the two classes : FXMLDocumentController.java</p> <pre><code>package crt; import java.io.IOException; import java.net.URL; import java.util.Date; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; public class FXMLDocumentController extends Thread implements Initializable { @FXML protected Label check; @FXML **protected Label date;** @FXML protected Label time; @FXML protected Label RRRR; @FXML protected Label DDDD; @FXML protected Label SSSS; @FXML protected Label temp; @FXML protected Label maxtemp; @FXML protected Label mintemp; @FXML private void handleButtonAction(ActionEvent event) throws IOException { //dc.setDate(date.textProperty().bind(valueproperty)); FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("menu.fxml")); Parent root1 = (Parent) fxmlLoader.load(); Stage stage = new Stage(); stage.initModality(Modality.APPLICATION_MODAL); stage.initStyle(StageStyle.UNDECORATED); stage.setTitle("MENU"); stage.setScene(new Scene(root1)); stage.show(); } @Override public void initialize(URL url, ResourceBundle rb) { } </code></pre> <p>FXMLDocument.fxml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;?import javafx.scene.control.Button?&gt; &lt;?import javafx.scene.control.Label?&gt; &lt;?import javafx.scene.control.ProgressBar?&gt; &lt;?import javafx.scene.layout.AnchorPane?&gt; &lt;?import javafx.scene.text.Text?&gt; &lt;AnchorPane id="AnchorPane" prefHeight="367.0" prefWidth="510.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="crt.FXMLDocumentController"&gt; &lt;children&gt; &lt;Button fx:id="button" layoutX="387.0" layoutY="302.0" minHeight="25.0" minWidth="80.0" onAction="#handleButtonAction" onTouchPressed="#handleButtonAction" text="Menu" /&gt; &lt;Label fx:id="date" layoutX="56.0" layoutY="64.0" minHeight="25.0" minWidth="80.0" /&gt; &lt;Label fx:id="time" layoutX="361.0" layoutY="64.0" minHeight="25.0" minWidth="80.0" text="S" /&gt; &lt;Label fx:id="RRRR" layoutX="76.0" layoutY="100.0" minHeight="25.0" minWidth="70.0" /&gt; &lt;Label fx:id="DDDD" layoutX="195.0" layoutY="100.0" minHeight="25.0" minWidth="70.0" /&gt; &lt;Label fx:id="SSSS" layoutX="314.0" layoutY="100.0" minHeight="25.0" minWidth="70.0" /&gt; &lt;Text layoutX="136.0" layoutY="163.0" strokeType="OUTSIDE" strokeWidth="0.0" text="TEMP :-" /&gt; &lt;Label fx:id="temp" layoutX="275.0" layoutY="156.0" minHeight="25.0" minWidth="70.0" text="A" /&gt; &lt;Text layoutX="136.0" layoutY="203.0" strokeType="OUTSIDE" strokeWidth="0.0" text="MAX TEMP :-" /&gt; &lt;Label fx:id="maxtemp" layoutX="275.0" layoutY="188.0" minHeight="25.0" minWidth="70.0" text="B" /&gt; &lt;Text layoutX="136.0" layoutY="243.0" strokeType="OUTSIDE" strokeWidth="0.0" text="MIN TEMP :-" /&gt; &lt;Label fx:id="maxtemp" layoutX="275.0" layoutY="225.0" minHeight="25.0" minWidth="70.0" text="C" /&gt; &lt;ProgressBar layoutX="401.0" layoutY="21.0" prefHeight="18.0" prefWidth="70.0" progress="0.0" /&gt; &lt;Button fx:id="startbutton" layoutX="14.0" layoutY="18.0" mnemonicParsing="false" onAction="#startstart" text="START" /&gt; &lt;Label fx:id="check" layoutX="42.0" layoutY="306.0" /&gt; &lt;/children&gt; &lt;/AnchorPane&gt; </code></pre> <p>TimeSetting.java</p> <pre><code>package crt; import java.util.Date; public class TimeSetting extends Thread { @Override public void run() { FXMLDocumentController fdc = new FXMLDocumentController(); // fdc.load(); int i=0; while(true) { Date d = new Date(); fdc.date.setText("fd" + i); i++; try { Thread.sleep(1000); } catch(InterruptedException e) { } } } } </code></pre> <p>CRT.java </p> <pre><code>package crt; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class CRT extends Application { @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); } public static void main(String[] args) throws InterruptedException { launch(args); TimeSetting ts = new TimeSetting(); ts.start(); } } </code></pre>
3
2,155
Web browser navigation Not occurring
<p>I am trying to navigate to different url links stored in TrimedPages but each time I try to navigate it to the TrimedPages[0] index it does not get navigated to new url instead it just navigate on old url :/</p> <pre><code>private void webBrowser1_DocumentCompleted_1(object sender, WebBrowserDocumentCompletedEventArgs e) { do { string url = webBrowser1.Url.ToString(); HtmlDocument doc = webBrowser1.Document; HtmlElementCollection collection = webBrowser1.Document.GetElementsByTagName("h2"); HtmlElementCollection collection2 = webBrowser1.Document.GetElementsByTagName("li"); HtmlElementCollection col = doc.GetElementsByTagName("p"); HtmlElementCollection collect = webBrowser1.Document.GetElementsByTagName("div"); if (IsRanBefore == false) { foreach (HtmlElement item in collection2) { att = item.GetAttribute("className"); if (att == "nav-current") { MainPageLink = item.InnerHtml; string[] Trim = MainPageLink.Split(new[] { '-', '\"' }, StringSplitOptions.RemoveEmptyEntries); MainPageLink = Trim[2] + "/"; } } foreach (HtmlElement item in collect) { string cls = item.GetAttribute("className"); if (cls == "nav") { Pages.Add(item.InnerHtml); break; } } foreach (string item in Pages) { string[] Trim = item.Split(TrimedWords, StringSplitOptions.RemoveEmptyEntries); for (int i = 8; i &lt; Trim.Length; i += 8) { TrimedPages.Add("http://www.bbc.co.uk" + MainPageLink + Trim[i]); } } IsRanBefore = true; } foreach (HtmlElement item in collection) { string cls = item.GetAttribute("className"); if (cls == "link title") { string inner = item.InnerText; links.Add(item.InnerHtml); } } System.IO.File.WriteAllLines("NewLinksss.txt", links.ToArray()); foreach (string item in links) { string[] Trim = item.Split(TrimedWords, StringSplitOptions.RemoveEmptyEntries); Trim[1] = "http://www.bbc.co.uk" + Trim[1]; if (!trimedlinks.Contains(Trim[1])) { trimedlinks.Add(Trim[1]); } } links = new List&lt;string&gt;(); MessageBox.Show("Crawling Done of web page" + TrimedPages[0]); if (TrimedPages.Count &gt; 0) { MessageBox.Show("Page removed " + TrimedPages[0]); TrimedPages.RemoveAt(0); System.IO.File.WriteAllLines("NewLinks.txt", trimedlinks.ToArray()); uri = TrimedPages[0]; webBrowser1.Navigate(uri); Uri myUri = new Uri(uri); webBrowser1.Url = myUri; MessageBox.Show(webBrowser1.Url.ToString()); MessageBox.Show(uri); } } while (TrimedPages.Count&gt;0); } </code></pre>
3
1,653
I get an Error when setting PCROP STM32H7 (STM32H743)
<h2>Goal</h2> <p>I'm trying to set a PCROP area on my STM32H743VI microcontroller, but I'm getting the error code <em>HAL_FLASH_ERROR_OB_CHANGE</em> when executing <em>HAL_FLASH_OB_Launch()</em> and my PCROP area is not set.</p> <p>The relevant part of the code I'm using should be the following sections</p> <h2>My code</h2> <pre><code> #include &quot;stm32h7xx_hal.h&quot; FLASH_OBProgramInitTypeDef OBInit; HAL_FLASHEx_OBGetConfig(&amp;OBInit); HAL_FLASH_Unlock(); HAL_FLASH_OB_Unlock(); // program OB OBInit.OptionType = OPTIONBYTE_PCROP; OBInit.PCROPStartAddr = 0x8030000; OBInit.PCROPEndAddr = 0x8031000; OBInit.PCROPConfig = OB_PCROP_RDP_ERASE; OBInit.Banks = FLASH_BANK_1; // (1, 2 oder BOTH) HAL_FLASHEx_OBProgram(&amp;OBInit); /* write Option Bytes */ if (HAL_FLASH_OB_Launch() != HAL_OK) { // Error handling while (1) { } } HAL_FLASH_OB_Lock(); HAL_FLASH_Lock(); </code></pre> <p>The code is mostly inspired by the youtube video &quot;Security Part3 - STM32 Security features - 07 - PCROP lab&quot; (by STMicroelectronics) and the working code I have to change RDP level.</p> <h2>Setup</h2> <p>My secret function is in the expected address range, I did that by adding the memory area in the Flash.Id File</p> <pre><code>MEMORY { [...] PCROP (x) : ORIGIN = 0x08030000, LENGTH = 16K } </code></pre> <p>and putting the function file into the section accordingly</p> <pre><code>SECTIONS { [...] .PCROPed : { . = ALIGN(4); *led_blinking.o (.text .text*) . = ALIGN(4); } &gt; PCROP [...] } </code></pre> <p>I set the flag <em>-mslow-flash-data</em> for the file I'm keeping my secret function in. I did this without really understanding why, following the tutorial in the video (see above).</p> <h2>What I tried</h2> <p>I debugged my program with my J-Trace Debugger and it seems like I'm doing the <em>Option byte modification sequence</em> described in the STM32H743/753 reference manual (p. 159) succesfully.</p> <p>Securing an entire Flashpage (start 0x080020000, end 0x0803FFFF) didn't work either, even though I did not expect it to make a difference.</p> <p>I also tried the other option for PCROPConfig, namely the OB_PCROP_RDP_NOT_ERASE option.</p> <p><em>HAL_FLASHEx_OBProgram(&amp;OBInit)</em> works as intended and the ObInit Configuration is set correctly into the _FLASH-&gt;<em>PRAR_PRG1</em> register. For my code the content of the register is 0x80880080</p> <p>I did disconnect and reconnect the microcontroller from power and debugger in case I did not POR correctly.</p> <p>I checked the errata sheet, but there is no errata which would be applicable to my problem.</p> <h2>EDIT</h2> <p>I changed the area which is protected by PCROP in the <em>My code</em> section. I did this, since my code is generally functional and I found out it's not a good idea to protect an area in the first flash page!</p>
3
1,176
D3 selection.html() , copy tooltip
<p>I have an svg element containing a circle with tooltip applied.</p> <p>I am using D3 <code>selection.html()</code> to clone this element and its contents into a new div. This works but the tooltip isn't copied across. How can I add the tooltip functionality to the new div?</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-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;script src="https://d3js.org/d3.v5.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- Create a div containing the action button --&gt; &lt;div class="container" id = "div1"&gt; &lt;button type="button" onclick=clone() &gt;Clone&lt;/button&gt; &lt;/div&gt; &lt;!--Create a div that will hold the initial circle --&gt; &lt;div class="container" id = "div2"&gt; &lt;/div&gt; &lt;!--Create a div that will hold the cloned circle --&gt; &lt;div class="container" id = "div3"&gt; &lt;/div&gt; &lt;/body&gt; &lt;script&gt; //Create an empty div that will hold the tooltip var div = d3.select("body").append("div") .attr("class", "tooltip") .style("opacity", 0); //Create some data var mydata= [{"xval":50,"yval":50,"mytooltip":"first"} ,{"xval":100,"yval":100,"mytooltip":"second"} ] //Append the SVG element var svg = d3.select("#div2") .append("svg") .attr("width",500) .attr("height", 500); //Draw a circle for each row of data svg.selectAll("circle") .data(mydata).enter() .append("circle") .attr("cx", function(d){return d.xval}) .attr("cy", function(d){return d.yval}) .attr("r", 10) .on("mouseover", function(d) { div.transition() .duration(200) .style("opacity", .9); div.html( d.mytooltip) }) .on("mouseout", function(d) { div.transition() .duration(500) .style("opacity", 0); }); //Copy the SVG element this works but the tooltup functionality is not copied function clone() { var content = d3.select("#div2").html(); var mymod = d3.select("#div3") .html(content); } &lt;/script&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p><strong>The full problem - in case I'm going about this the wrong way</strong> <br></p> <p>I have a series of svg elements, one per div containing graphs whose datapoints can be filtered using user input and which feature tooltips. </p> <p>I want the user to be able to enlarge an individual graph into a modal. I can do this by calling the function that draws the graph again when the modal loads, however this causes problems as I then need to re-apply the filtering.</p> <p>Consequently I'm using selection.html to clone the individual graphs into the tooltip (thus inheriting the filtering). This works with the exception that the tooltip functionality isn't replicated. How can I correct this.</p>
3
1,252
Java LWJGL/Slick Util Java Null Pointer Exception Error (Texture Loading)
<p>I have been having some issues with loading Textures in LWJGL/Slick Util. I am receiving this error in the <code>texture.bind()</code> method. I would also like advice as to how to improve my code if improvement is needed. Here it is: </p> <p>The Sprite Class:</p> <pre><code>package geniushour.engine.animation; import static org.lwjgl.opengl.GL11.*; import java.io.IOException; import org.newdawn.slick.opengl.Texture; public class Sprite { private float sx; private float sy; private Texture texture; public Sprite(float sx, float sy, Texture texture) throws IOException{ this.texture = texture; this.sx = sx; this.sy = sy; } public void render(){ texture.bind(); glBegin(GL_QUADS); glTexCoord2f(0,0); glVertex2f(0,0); glTexCoord2f(1,0); glVertex2f(0,sy); glTexCoord2f(1,1); glVertex2f(sx,sy); glTexCoord2f(0,1); glVertex2f(sx,0); glEnd(); } public float getSX(){ return sx; } public float getSY(){ return sy; } public Texture getTexture(){ return texture; } public void setSX(float sx){ this.sx = sx; } public void setSY(float sy){ this.sy = sy; } /*public void setSpriteTexture(String key) throws IOException{ this.texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("img/"+key+".png")); }*/ } </code></pre> <p>The GameObject Class:</p> <pre><code>package geniushour.gameobject; import static org.lwjgl.opengl.GL11.glPopMatrix; import static org.lwjgl.opengl.GL11.glPushMatrix; import static org.lwjgl.opengl.GL11.glTranslatef; import java.io.IOException; import org.newdawn.slick.opengl.Texture; import geniushour.engine.animation.Sprite; public abstract class GameObject { protected float x; protected float y; protected float sx; protected float sy; protected Sprite spr; protected int type; protected static final int PLAYER_ID = 0; protected static final int ENEMY_ID = 1; protected static final int ITEM_ID = 2; protected static final int ENTITY_SIZE = 64; protected static final int ITEM_SIZE = 16; protected boolean[] flags = new boolean[1]; public void update(){} public void render(){ glPushMatrix(); glTranslatef(x,y,0); spr.render(); glPopMatrix(); } public float getX(){ return x; } public float getY(){ return y; } public float getSX(){ return spr.getSX(); } public float getSY(){ return spr.getSY(); } public int getType(){ return type; } public boolean getRemove(){ return flags[0]; } public void remove(){ flags[0] = true; } /*protected void setTexture(String key) throws IOException{ spr.setSpriteTexture(key); }*/ public Texture getTexture(){ return spr.getTexture(); } protected void init(float x, float y, float sx, float sy,Texture texture,int type) throws IOException{ this.x = x; this.y = y; this.type = type; this.spr = new Sprite(sx,sy,texture); } } </code></pre> <p>The Player Class:</p> <pre><code>package geniushour.gameobject.entity; import java.io.IOException; import org.lwjgl.input.Keyboard; import org.newdawn.slick.opengl.Texture; import geniushour.game.Inventory; import geniushour.game.Stats; import geniushour.gameobject.GameObject; import geniushour.gameobject.item.Item; public class Player extends GameObject { private Stats stats; private Inventory inv; private int stamina; private int maxStamina = 150; public Player(float x, float y, Texture texture) throws IOException{ init(x,y,ENTITY_SIZE,ENTITY_SIZE,texture,PLAYER_ID); stats = new Stats(0,true); inv = new Inventory(9); stamina = maxStamina; } public void update(){ if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) &amp;&amp; stamina &gt; 0){ stamina--; } else if(!Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)){ stamina++; if(stamina &gt; maxStamina){ stamina = maxStamina; } } } public void getInput(){ if(Keyboard.isKeyDown(Keyboard.KEY_W)){ if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) &amp;&amp; stamina &gt; 0){ move(0,1.5); } else{ move(0,1); } } if(Keyboard.isKeyDown(Keyboard.KEY_S)){ if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) &amp;&amp; stamina &gt; 0){ move(0,-1.5); } else{ move(0,-1); } } if(Keyboard.isKeyDown(Keyboard.KEY_A)){ if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) &amp;&amp; stamina != 0){ move(-1.5,0); } else{ move(-1,0); } } if(Keyboard.isKeyDown(Keyboard.KEY_D)){ if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) &amp;&amp; stamina != 0){ move(1.5,0); } else{ move(1,0); } } } public Texture getTexture(){ return getTexture(); } private void move(double magX, double magY){ x += getSpeed() * magX; y += getSpeed() * magY; } private int getSpeed(){ return stats.getPlayerSpeed(); } @SuppressWarnings("unused") private int getLevel(){ return stats.getLevel(); } @SuppressWarnings("unused") private int getXP(){ return stats.getXP(); } public int getMaxHP(){ return stats.getMaxHP(); } public int getCurrentHealth(){ return stats.getCurrentHealth(); } public int getStrength(){ return stats.getStrength(); } public int getMagic(){ return stats.getMagic(); } public void addXP(int amt){ stats.addXP(amt); } public void addHP(int amt){ stats.addHP(amt); } public void addItem(Item item){ inv.add(item); } } </code></pre> <p>The Game Class:</p> <pre><code>package geniushour.game; import java.io.IOException; import java.util.ArrayList; import org.newdawn.slick.opengl.Texture; import geniushour.gameobject.*; import geniushour.gameobject.entity.*; import geniushour.gameobject.item.*; public class Game { private ArrayList&lt;GameObject&gt; obj; private ArrayList&lt;GameObject&gt; remove; private Player p; private Texture pTexture; private ItemEssence essence; private Texture eTexture; private EnemyBlob blob; private Texture bTexture; public Game() throws IOException{ obj = new ArrayList&lt;GameObject&gt;(); remove = new ArrayList&lt;GameObject&gt;(); setTexture(pTexture,"raptor"); setTexture(eTexture,"essence"); setTexture(bTexture,"blob"); p = new Player(250,250,pTexture); essence = new ItemEssence(400, 400, eTexture, p); blob = new EnemyBlob(300,500,bTexture, 1); obj.add(essence); obj.add(p); obj.add(blob); } public void getInput(){ p.getInput(); } public void update(){ for(GameObject go : obj){ if(!go.getRemove()){ go.update(); } else{ remove.add(go); } } for(GameObject go : remove){ obj.remove(go); } } public void render(){ for(GameObject go : obj){ go.render(); } } public ArrayList&lt;GameObject&gt; sphereCollide(float x, float y, float radius){ ArrayList&lt;GameObject&gt; res = new ArrayList&lt;GameObject&gt;(); for(GameObject go : obj){ if(Util.dist(go.getX(),x,go.getY(),y) &lt; radius){ res.add(go); } } return res; } private void setTexture(Texture texture, String key){ } } </code></pre> <p>The error occurs in the Sprite class, the first block of code.</p>
3
3,853
how to identify the element that was clicked?
<p>please help to fix the <a href="http://jsfiddle.net/hfoeja7f/" rel="nofollow">script</a>. </p> <p>after the user clicks on an item .menu_button, there is a call function initForm(). This function should print one </p> <pre><code>console.log(N) </code></pre> <p>but displays 3:</p> <pre><code>console.log(1) console.log(2) console.log(3) </code></pre> <p>I do not understand</p> <p>js:</p> <pre><code>$(document).ready(function() { // --- PLUGIN kalininModals INITIALIZATION --- $('.menu_button').kalininModals(); ); (function($){ // --- options --- $.fn.kalininModals = function(options) { var options = $.extend({},options); return this.each(function(e) { // --- properties --- var self = $(this), selfModals = $('#modalOuter'), selfModalsWindow = $('#modalWindow'), head, info, actionsArr; // --- methods --- function initForm(formNum){ //console.log('___' + self.text()); if(formNum == 1){ console.log(1); head = 'Обратный звонок'; } else if(formNum == 2){ console.log(2); head = 'Обратный звонок'; } else if(formNum == 3){ console.log(3); head = 'Обратный звонок'; }; } function makeBody(){ console.log('make'); $('#head .h2').text(head); $('#info').html(info); } // --- handlers --- function onClickControls(e){ self = $(e.currentTarget); initForm(self.attr('data-form-num')); makeBody(); } // --- events --- $('#menuButton1, #menuButton2, #menuButton3').on('click', onClickControls); }); }; })($); </code></pre>
3
1,193
Swift - Consecutive fetch request to Core Data are unsuccessful
<p>I'm trying to make 3 consecutive fetch requests to core data based on the result from the previous fetch such as follow:</p> <pre><code>func myFunction(info: Info ? , completionHandler : (selectedTop: MyObject ? , selectedMiddle : MyObject ? , selectedBottom : MyObject ? , error : NSError ? ) - &gt; Void) { selectTop(info) { selectedTop, error in if let top = selectedTop { self.selectMiddle(top) { selectedMiddle, error in if let middle = selectedMiddle { self.selectBottom(middle) { selectedBottom, error in if let bottom = selectedBottom { completionHandler(selectedTop: top, selectedMiddle: middle, selectedBottom: bottom, error: nil) } //close if bottom } // close selectBottom } // close if middle } // close selectMiddle } // close if top } // close selectTop } // close myFunction </code></pre> <p><strong>Notes</strong>: </p> <ul> <li>Each selectXXX function is a simple fetch request with some predicates</li> <li>I removed part of the code to handle errors to simplify this snippet.</li> </ul> <p><strong>Goal</strong>: Populate 3 UIImageView images (from the 3 objects) all "connected" to one another: top, middle, bottom. <em>Note that I cannot use a core data relationship (one-to-one or one-to-many) since a middle can be associated to many tops or bottoms for instance.</em></p> <p><strong>Issue</strong>: My top object get properly selected from Core Data but the middle does not. I of course verified and debugged multiple times what I have available in my core data to make sure at least one object matches all required conditions (aka fetch request predicates) but still my printing debugging shows me that no matching object is available.</p> <p><strong>Question/Doubt</strong>: I'm wondering if making consecutive fetch requests as such messes up with the actual data being available for the subsequent fetches. Since I'm fetching Top objects first, I'm thinking that somehow only those are available when I start fetching for Middle objects (which would explain why nothing is found)</p> <p>I tried hard looking for similar questions or issues but didn't come to anything close. Would anyone had experience with similar approach?</p> <p>Thanks in advance for the help.</p> <p>EDIT: as requested, here is the additional code from the functions involved in my fetches.</p> <pre><code>func selectTop(info: Info?, completionHandler:(result: MyObject?, error: NSError?)-&gt; Void){ let predicateCat = NSPredicate(format: "category = %@", "Top") let predicateStyle = NSPredicate(format: "style IN %@", ["Style1, Style2", "Style3"]) let compoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicateCat, predicateStyle]) fetchDataAndSelectClothe(compoundPredicate){ success, selectedObject, error in if success { completionHandler(result: selectedObject, error: nil) } else { if let topError = error { completionHandler(result: nil, error: topError) } } } </code></pre> <p>}</p> <pre><code>func selectMiddle(selectedTop: MyObject!, completionHandler:(result: MyObject?, error: NSError?)-&gt; Void){ let styleToUse = [selectedTop.style] let predicateCat = NSPredicate(format: "category = %@", "Middle") let predicateStyle = NSPredicate(format: "style IN %@", styleToUse) // other predicates are built here but removed for the sake of this example // ie: switch statement to select matching color based on selectedTop.color let compoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicateCat, predicateStyle]) fetchDataAndSelectClothe(compoundPredicate){ success, selectedObject, error in if success { completionHandler(result: selectedObject, error: nil) } else { if let topError = error { completionHandler(result: nil, error: topError) } } } func fetchDataAndSelectObject(compoundPredicate: NSCompoundPredicate, completionHandler:(success: Bool, selectedObject: MyObject?, error: NSError?) -&gt; Void){ let fetchRequest = NSFetchRequest(entityName: "MyObject") fetchRequest.predicate = compoundPredicate fetchRequest.sortDescriptors = [] let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.sharedContext, sectionNameKeyPath: nil, cacheName: nil) do { try fetchedResultsController.performFetch() } catch let error as NSError { print("Error: \(error.localizedDescription)") abort() } // if we didn't get any data if fetchedResultsController.fetchedObjects?.count == 0 { completionHandler(success: false, selectedClothe: nil, error: NSError(domain: "FetchedResultsController", code: 0, userInfo: [NSLocalizedDescriptionKey: "There was no matching fetched Objects"])) } // if we did get data else { let numberOfItems = fetchedResultsController.fetchedObjects?.count let randomIndex = Int.random(0..&lt;numberOfItems!) let selectedObject = fetchedResultsController.fetchedObjects![randomIndex] as! MyObject completionHandler(success: true, selectedObject: selectedObject, error: nil) } } </code></pre>
3
1,907
Trie permutations not found
<p>I'm running into a problem while using a Trie in Java for an anagram solver. The following code is for Android and does not give me any permutation results for the letters that are given and passed in. However, if I implement the same code in a Java desktop application, it returns the correct results for me. I'm pretty sure it's something simple that's going wrong, I just can't seem to find it. </p> <p>Code for Desktop version:</p> <pre><code>static String myWord; static String myLetters = ""; static char[] myChars; static TrieNode myNode = new TrieNode(); static TrieNode currentNode; static ArrayList&lt;String&gt; availableWords = new ArrayList&lt;String&gt;(); public static void main(String[] args) { Scanner s = new Scanner(System.in); myLetters = s.next(); readWords(); getPermutations(); } public static void getPermutations(){ currentNode = myNode; for(int x = 0; x &lt; myLetters.length(); x++){ if(currentNode.children[myLetters.charAt(x) - 'a'] != null){ availableWords.addAll(currentNode.getWords()); currentNode = currentNode.children[myLetters.charAt(x) - 'a']; System.out.println("x: " + x + " " + currentNode.getWords() + "" + myLetters.charAt(x)); } } System.out.println(availableWords); } Desktop Output: aelpp //(user input from scanner) x: 0 []a x: 1 [ae]e x: 2 [ale, lea]l x: 3 [leap, pale, peal, plea]p x: 4 [appel, apple, pepla]p [ae, ale, lea, leap, pale, peal, plea] </code></pre> <p>Android code:</p> <pre><code>static String myWord; static char[] myChars; static TrieNode myNode = new TrieNode(); static TrieNode currentNode; static ArrayList&lt;String&gt; availableWords = new ArrayList&lt;String&gt;(); public static void getPermutations(String passedInLetters){ currentNode = myNode; Log.i("TRIE:" , passedInLetters); for(int x = 0; x &lt; passedInLetters.length(); x++){ if(currentNode.children[passedInLetters.charAt(x) - 'a'] != null){ availableWords.addAll(currentNode.getWords()); Log.i("TRIE:" , "x: " + x + " " + currentNode.getWords()); currentNode = currentNode.children[passedInLetters.charAt(x) - 'a']; } } Log.i("TRIE:", availableWords.toString()); } </code></pre> <p>Android Log Output:</p> <pre><code>03-15 22:45:11.670: I/TRIE:(4286): aelpp 03-15 22:45:11.670: I/TRIE:(4286): x: 0 [] 03-15 22:45:11.670: I/TRIE:(4286): x: 1 [] 03-15 22:45:11.670: I/TRIE:(4286): x: 2 [] 03-15 22:45:11.670: I/TRIE:(4286): x: 3 [] 03-15 22:45:11.670: I/TRIE:(4286): x: 4 [] 03-15 22:45:11.670: I/TRIE:(4286): [] </code></pre> <p>If needed, here are the full classes:</p> <p>Desktop: <a href="http://pastie.org/3604515" rel="nofollow noreferrer">http://pastie.org/3604515</a> Android: <a href="http://pastie.org/3604513" rel="nofollow noreferrer">http://pastie.org/3604513</a></p> <p>I have been studying this post among some of my other sources: <a href="https://stackoverflow.com/questions/9138239/java-string-permutations-and-combinations">java string permutations and combinations lookup</a></p> <p>Thanks!</p> <p>EDIT: </p> <p>These lines needed switched inside the if statement:</p> <pre><code>currentNode = currentNode.children[passedInLetters.charAt(x) - 'a']; availableWords.addAll(currentNode.getWords()); </code></pre>
3
1,460
Excel VBA non contiguous range more than 255 characters error
<p>I have code which worked fine. But suddenly when I changed range of cells for copying to another sheet I'm getting the error message &quot;Excel VBA Runtime error '1004' - Method 'Range' of object '_Worksheet' failed&quot;. I guess it's related to character limitation. So I tried to split the range to several zones and use &quot;Union&quot; function which then messed order of copied cells. I would really appreciate any help or suggestion.</p> <pre><code>Option Explicit </code></pre> <p>Public Sub SaveExpenses() Dim UniqueID(1 To 2) As Variant, arr() As Variant Dim Response As VbMsgBoxResult Dim txtPrompt As String, FirstAddress As String Dim RecordRow As Long, i As Long Dim DataRange As Range, FoundCell As Range, Cell As Range, Zone1 As Range, Zone2 As Range, Zone3 As Range, Zone4 As Range Dim wsDataStorage As Worksheet, wsExpenses As Worksheet</p> <pre><code>With ThisWorkbook Set wsDataStorage = .Worksheets(&quot;Data Storage&quot;) Set wsExpenses = .Worksheets(&quot;Expenses&quot;) End With Set Zone1 = wsExpenses.Range(&quot;B3,D3,B8:F8,H8:J8,B9:F9,H9:J9,B10:F10,H10:J10,B11:F11,H11:J11,B12:F12,H12:J12,B13:F13,H13:J13&quot;) Set Zone2 = wsExpenses.Range(&quot;B17,C17,E17,H17:J17,B18,C18,E18,H18:J18,B19,C19,E19,H19:J19&quot;) Set Zone3 = wsExpenses.Range(&quot;B20,C20,E20,H20:J20,B21,C21,E21,H21:J21,B22,C22,E22,H22:J22&quot;) Set Zone4 = wsExpenses.Range(&quot;B23,C23,E23,H23:J23,B24,C24,E24,H24:J24,B25,C25,E25,H25:J25,I14,C27,C34&quot;) Set DataRange = Union(Zone1, Zone2, Zone3, Zone4) </code></pre> <p>' Set DataRange = wsExpenses.Range(&quot;B3,D3,&quot; &amp; _ &quot;B8:F8,H8:J8,B9:F9,H9:J9,B10:F10,H10:J10,B11:F11,H11:J11,B12:F12,H12:J12,B13:F13,H13:J13,&quot; &amp; _ &quot;B17,C17,E17,H17:J17,B18,C18,E18,H18:J18,B19,C19,E19,H19:J19,&quot; &amp; _ &quot;B20,C20,E20,H20:J20,B21,C21,E21,H21:J21,B22,C22,E22,H22:J22,&quot; &amp; _ &quot;B23,C23,E23,H23:J23,B24,C24,E24,H24:J24,B25,C25,E25,H25:J25,&quot; &amp; _ &quot;I14,C27,C34&quot;)</p> <pre><code> 'check ID values entered For i = 1 To 2 UniqueID(i) = DataRange.Areas(i) If Len(UniqueID(i)) = 0 Then Exit Sub Next 'new record RecordRow = wsDataStorage.Cells(wsDataStorage.Rows.Count, &quot;B&quot;).End(xlUp).Row + 1 txtPrompt = &quot;Saved&quot; 'check record exists Set FoundCell = wsDataStorage.Columns(2).Find(UniqueID(1), LookIn:=xlValues, LookAt:=xlWhole) If Not FoundCell Is Nothing Then FirstAddress = FoundCell.Address Do If UCase(FoundCell.Offset(, 1).Value) = UCase(UniqueID(2)) Then 'inform user Response = MsgBox(UniqueID(1) &amp; &quot; &quot; &amp; UniqueID(2) &amp; Chr(10) &amp; _ &quot;Record Already Exists&quot; &amp; Chr(10) &amp; _ &quot;Do You Want To OverWrite?&quot;, 36, &quot;Record Exists&quot;) If Response = vbNo Then Exit Sub 'overwrite record RecordRow = FoundCell.Row txtPrompt = &quot;Updated&quot; Exit Do End If Set FoundCell = wsDataStorage.Columns(2).FindNext(FoundCell) If FoundCell Is Nothing Then Exit Do Loop Until FoundCell.Address = FirstAddress End If 'size array ReDim arr(1 To DataRange.Cells.Count) i = 0 For Each Cell In DataRange.Cells i = i + 1 'non-contiguous form cell values to array arr(i) = Cell.Value Next Cell 'post arr to range wsDataStorage.Range(&quot;B&quot; &amp; RecordRow).Resize(, UBound(arr)).Value = arr 'inform user MsgBox &quot;Form no. &quot; &amp; UniqueID(1) &amp; &quot; &quot; &amp; UniqueID(2) &amp; &quot; Successfully &quot; &amp; txtPrompt, 64, &quot;Record &quot; &amp; txtPrompt End Sub </code></pre>
3
1,898
Why does my regex fail when trying to indicate beginning of string in replace()?
<p>Moving from Perl to Node I'm confused why given the passed object <code>data</code> of:</p> <pre class="lang-js prettyprint-override"><code>{ xAxis: 'string', yAxis: 'string', zAxis: 'string', data: '\n' + 'p.foo {\n' + '\tcolor:#000000;\n' + '\tfont-family:&quot;Open Sans&quot;;\n' + '\tfont-size:1em;\n' + '\tfont-style:normal;\n' + '\tfont-variant:normal;\n' + '\tfont-weight:normal;\n' + '\tline-height:1;\n' + '\tmargin-bottom:0;\n' + '\tmargin-left:0;\n' + '\tmargin-right:0;\n' + '\tmargin-top:0;\n' + '\torphans:1;\n' + '\tpage-break-after:auto;\n' + '\tpage-break-before:auto;\n' + '\ttext-align:left;\n' + '\ttext-decoration:none;\n' + '\ttext-indent:0;\n' + '\ttext-transform:none;\n' + '\twidows:1;\n' + '}\n' + 'p.bar {\n' + '\tcolor:#000000;\n' + '\tfont-family:&quot;Open Sans&quot;;\n' + '\tfont-size:1em;\n' + '\tfont-style:normal;\n' + '\tfont-variant:normal;\n' + '\tfont-weight:normal;\n' + '\tline-height:1;\n' + '\tmargin-bottom:0;\n' + '\tmargin-left:0;\n' + '\tmargin-right:0;\n' + '\tmargin-top:0;\n' + '\torphans:1;\n' + '\tpage-break-after:auto;\n' + '\tpage-break-before:auto;\n' + '\ttext-align:left;\n' + '\ttext-decoration:none;\n' + '\ttext-indent:0;\n' + '\ttext-transform:none;\n' + '\twidows:1;\n' + '}\n' } </code></pre> <p>if trying to replace any instance of a <code>p</code> or <code>span</code> from a beginning of line (<code>^</code>):</p> <pre class="lang-js prettyprint-override"><code>obj.data = obj.data.replace(/^(p|span)(?=\.)/gi, '') </code></pre> <p>the replace will not work and will only work as:</p> <pre class="lang-js prettyprint-override"><code>obj.data = obj.data.replace(/(p|span)(?=\.)/gi, '') </code></pre> <p>example:</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>const test = { xAxis: 'string', yAxis: 'string', zAxis: 'string', data: '\n' + 'p.foo {\n' + '\tcolor:#000000;\n' + '\tfont-family:"Open Sans";\n' + '\tfont-size:1em;\n' + '\tfont-style:normal;\n' + '\tfont-variant:normal;\n' + '\tfont-weight:normal;\n' + '\tline-height:1;\n' + '\tmargin-bottom:0;\n' + '\tmargin-left:0;\n' + '\tmargin-right:0;\n' + '\tmargin-top:0;\n' + '\torphans:1;\n' + '\tpage-break-after:auto;\n' + '\tpage-break-before:auto;\n' + '\ttext-align:left;\n' + '\ttext-decoration:none;\n' + '\ttext-indent:0;\n' + '\ttext-transform:none;\n' + '\twidows:1;\n' + '}\n' + 'p.bar {\n' + '\tcolor:#000000;\n' + '\tfont-family:"Open Sans";\n' + '\tfont-size:1em;\n' + '\tfont-style:normal;\n' + '\tfont-variant:normal;\n' + '\tfont-weight:normal;\n' + '\tline-height:1;\n' + '\tmargin-bottom:0;\n' + '\tmargin-left:0;\n' + '\tmargin-right:0;\n' + '\tmargin-top:0;\n' + '\torphans:1;\n' + '\tpage-break-after:auto;\n' + '\tpage-break-before:auto;\n' + '\ttext-align:left;\n' + '\ttext-decoration:none;\n' + '\ttext-indent:0;\n' + '\ttext-transform:none;\n' + '\twidows:1;\n' + '}\n' } console.log(test.data.replace(/^(p|span)(?=\.)/gi, '')) // doesn't work console.log(test.data.replace(/(p|span)(?=\.)/gi, '')) // works</code></pre> </div> </div> </p> <p>testing with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp" rel="nofollow noreferrer">RegExp</a> it works only on the first found:</p> <pre class="lang-js prettyprint-override"><code>obj.data = obj.data.replace(new RegExp(/^(p|span)(?=\.)/, 'ig'), '') </code></pre> <p>and seems to be due to the <code>m</code> flag needed, so this works:</p> <pre class="lang-js prettyprint-override"><code>obj.data = obj.data.replace(new RegExp(/^(p|span)(?=\.)/, 'igm'), '') </code></pre> <p>When reading the type of <code>obj.data</code>:</p> <pre class="lang-js prettyprint-override"><code>console.log(typeof obj.data) // returns string </code></pre> <p>it shows <code>string</code>. Upon research I'm not seeing a reason why but I've read:</p> <ul> <li><a href="https://stackoverflow.com/questions/49800718/javascript-replace-with-regex-not-working-correctly">Javascript replace with regex not working correctly</a></li> <li><a href="https://stackoverflow.com/questions/6646703/javascript-regexp-replace-not-working-but-string-replace-works">javascript regexp replace not working, but string replace works</a></li> </ul> <p>Why am I seeing mixed results from my regex in a <code>replace()</code> while trying to use <code>^</code> when passing in the object's data and why does it only work with RegExp?</p> <hr /> <h2>Edit:</h2> <p>I think my issue is from a misunderstanding of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#advanced_searching_with_flags" rel="nofollow noreferrer">JavaScript flags</a>. I assumed that because the object's data was a string the flag <code>g</code> <strong>Global Search</strong> flag would work but it seems that I need <code>m</code> <strong>Multi-line Search</strong> flag.</p>
3
2,482
Java Pong game bounce ball from paddle
<p>I'm trying to make a Pong game in Java and I have a little problem with bouncing the ball from the paddle.</p> <p>I have two paddles: left paddle1, right paddle2.</p> <p>My idea is the following: <code>ball_Y</code> should be between the height of the paddle and <code>ball_X</code> touching point should be <code>paddle width (PP1_width or PP2_width) +/- ball_radius</code></p> <p>Paddle2 is working OK, but the ball passes through paddle1 and I cannot see my mistake. </p> <p>Here is the video of how it looks like;</p> <p><a href="https://streamable.com/bzrud" rel="nofollow noreferrer">https://streamable.com/bzrud</a></p> <p>Here is the paddle bouncing part:</p> <pre><code>if(ball_Y &gt; P1_Y &amp;&amp; ball_Y &lt; P1_Hit_Y){ if(ball_X &lt; P1_Hit_X){ ball_Velocity_X *= -1; ball_X = P1_Hit_X; } } if (ball_Y &gt; P2_Y &amp;&amp; ball_Y &lt; P2_Hit_Y){ if(ball_X &gt; P2_Hit_X){ ball_Velocity_X *= -1; ball_X = P2_Hit_X; } } </code></pre> <p>Here is all the code:</p> <pre><code>import java.awt.*; import java.awt.geom.*; import javax.swing.*; import java.awt.event.*; public class PongGame extends GameEngine{ public static void main(String args[]) { // Warning - don't edit this function. // Create a new game. createGame(new PongGame()); } int game_width, game_height; double PP1_width, PP1_height, PP2_width, PP2_height; double P1_X, P1_Y, P2_X, P2_Y; double PP_Velocity; boolean PP1_UP, PP1_DOWN, PP2_UP, PP2_DOWN; double ball_X, ball_Y, ball_Radius, ball_Velocity_X, ball_Velocity_Y; double P1_Hit_X, P1_Hit_Y, P2_Hit_X, P2_Hit_Y; AudioClip wall_bounce; //TODO: Create paddles and a ball //Two paddles for two players: They will be controlled with W-S and UP-DOWN Keys public void paddle1(){ drawSolidRectangle(P1_X, P1_Y, PP1_width, PP1_height); } public void paddle2(){ drawSolidRectangle(P2_X, P2_Y, PP2_width, PP2_height); } public void ball(){ drawSolidCircle(ball_X, ball_Y, ball_Radius); } //TODO: Update Paddles //DONE: Sources from PhysicsDemo lecture /** * These methods allow us the update the window with each framerate so we will be able to move the * paddles */ public void paddle1_update(double dt){ // Paddle 1 Up with W if(PP1_UP == true){ P1_Y -= PP_Velocity * dt; // Check paddle inside wall if((P1_Y &lt; 0) ) { P1_Y = 0; } } // Paddle 1 Down with S if(PP1_DOWN == true){ P1_Y += PP_Velocity * dt; // Check paddle inside wall if(P1_Y &gt; game_height-PP1_height){ P1_Y = game_height-PP1_height; } } } public void paddle2_update(double dt){ // Paddle 2 Up with Up Key if(PP2_UP == true){ P2_Y -= PP_Velocity * dt; // Check paddle inside wall if((P2_Y &lt; 0) ) { P2_Y = 0; } } // Paddle 2 Down with Down Key if(PP2_DOWN == true){ P2_Y += PP_Velocity * dt; // Check paddle inside wall if(P2_Y &gt; game_height-PP2_height){ P2_Y = game_height-PP2_height; } } } public void ball_update(double dt){ ball_X += ball_Velocity_X * dt; ball_Y += ball_Velocity_Y * dt; // Bouncing the ball from edge of the wals if(ball_Y &lt; ball_Radius) { ball_Velocity_Y *= -1; //Play wall bounce sound playAudio(wall_bounce); }else if (ball_Y &gt; (game_height - ball_Radius)){ ball_Velocity_Y *= -1; //Play wall bounce sound playAudio(wall_bounce); } } // Background //TODO: Override init method in GameEngine public void init(){ //Initialise Window size game_width = 750; game_height = 450; //Position for Paddles PP_Velocity = 250; PP1_width = 10; PP1_height = 100; P1_X = 0; P1_Y = 100; PP2_width = 10; PP2_height = 100; P2_X = game_width - PP2_width; P2_Y = 100; //Initialise Keyboard variables PP1_UP = false; PP1_DOWN = false; PP2_UP = false; PP2_DOWN= false; //Initialise Ball ball_X = 250; ball_Y = 250; ball_Radius = 10; ball_Velocity_X = 200; ball_Velocity_Y = 200; //Paddle ball bounce point P1_Hit_X = PP1_width + ball_Radius; P1_Hit_Y = P1_Y + PP1_height; P2_Hit_X = P2_X - ball_Radius; P2_Hit_Y = P2_Y + PP2_height; /* NOTE: Sound Resources * https://freesound.org/people/NoiseCollector/sounds/4391/ * https://freesound.org/people/NoiseCollector/sounds/4386/ */ wall_bounce = loadAudio("Audio/wall_bounce.wav"); // paddle = loadAudio("Audio/paddle_bounce.wav"); //background = loadAudio("Audio/background.wav"); } // Override abstract method update(double) in GameEngine public void update(double dt){ paddle1_update(dt); paddle2_update(dt); ball_update(dt); if(ball_Y &gt; P1_Y &amp;&amp; ball_Y &lt; P1_Hit_Y){ if(ball_X &lt; P1_Hit_X){ ball_Velocity_X *= -1; ball_X = P1_Hit_X; } } if (ball_Y &gt; P2_Y &amp;&amp; ball_Y &lt; P2_Hit_Y){ if(ball_X &gt; P2_Hit_X){ ball_Velocity_X *= -1; ball_X = P2_Hit_X; } } } public void paintComponent() { // Clear the background to black setWindowSize(game_width, game_height); changeBackgroundColor(black); clearBackground(game_width, game_height); changeColor(white); drawLine(game_width/2, 0, game_width/2, game_height); paddle1(); paddle2(); ball(); // Draw in black changeColor(black); } //TODO: Key Listener for paddles () //DONE: KeyListener -&gt; Space game example // KeyPressed Event public void keyPressed(KeyEvent event) { // Left Arrow if(event.getKeyCode() == KeyEvent.VK_W) { PP1_UP = true; } // Right Arrow if(event.getKeyCode() == KeyEvent.VK_S) { PP1_DOWN = true; } // Space Button if(event.getKeyCode() == KeyEvent.VK_UP) { PP2_UP = true; } if(event.getKeyCode() == KeyEvent.VK_DOWN) { PP2_DOWN = true; } } // KeyReleased Event public void keyReleased(KeyEvent event) { // Left Arrow if(event.getKeyCode() == KeyEvent.VK_W) { PP1_UP = false; } // Right Arrow if(event.getKeyCode() == KeyEvent.VK_S) { PP1_DOWN = false; } // Space Button if(event.getKeyCode() == KeyEvent.VK_UP) { PP2_UP = false; } if(event.getKeyCode() == KeyEvent.VK_DOWN) { PP2_DOWN = false; } } } </code></pre>
3
3,802
Feeding highchart with x and y values from ajax
<p>I'm trying to feed my highchart from a database using ajax. From my ajax request, I want to return both x and y values (the x value is like that: year-week, ie 2020-16; the y value is a random number). My chart remains blank, I have a silent error that I cannot figure out. I'm pretty sure it comes from the strucure of the data returned by ajax, but I can't seem to fix it on my own.</p> <p>Here's my javascript:</p> <pre><code> var weekOptions = { chart: { renderTo: 'weekContainer', type: 'column', }, title: { text: 'Last 52 weeks', }, credits: { enabled: false, }, xAxis: { lineWidth: .5, tickWidth: 1, tickLength: 10, }, yAxis: { title: { text: 'Distance (miles)' }, labels: { formatter: function() { return this.value; }, }, allowDecimals: false, gridLineWidth: 1, }, tooltip: { crosshairs: true, split: true, useHTML: true, valueDecimals: 2, valueSuffix: ' miles', formatter: '', }, plotOptions: { spline: { marker: { symbol: "circle", radius: 3, } } }, lang: { noData: "No Data. Make sure at least one activity type is selected." }, noData: { style: { fontWeight: 'bold', fontSize: '15px', color: '#303030' } }, exporting: { buttons: { contextButton: { menuItems: ['viewFullscreen'] } }, }, series: [{}], }; //get series from ajax filtered by activity types $.ajax({ url: "weekGetSeries.php", type: "POST", data: { activityType: activityTypeSelected, dataToDisplay: dataToDisplay, }, dataType: "JSON", success: function (json) { weekOptions.series = json; var chart = new Highcharts.Chart(weekOptions); } }); </code></pre> <p>And here my ajax php file:</p> <pre><code> &lt;?php require 'dbConnection.php'; $activityType = array(1,2,3,4,5); $dataToDisplay = "distance"; $startingDate = date('Y-m-d', strtotime('-52 week', time())); $firstWeek = strtotime($startingDate); $conditionActivityType = ' WHERE startingTime &gt;= "' . $startingDate . '" AND (type=' . implode(" OR type=",$activityType) . ')'; $dataSerie = array("name" =&gt; "Weekly Stats","data" =&gt; array()); for($i = 0; $i &lt; 52; $i++){ $nextWeek = strtotime('+'.$i.' week', $firstWeek); $dataSerie["data"][date("o",$nextWeek) . "-" . date("W",$nextWeek)] = 0; } $getActivities = $conn-&gt;query("SELECT * FROM activity" . $conditionActivityType . " ORDER BY startingTime ASC"); if ($getActivities-&gt;num_rows &gt; 0) { while($row = $getActivities-&gt;fetch_assoc()) { $date = substr($row["startingTime"],0,10); $date = strtotime($date); $week = date("W",$date); $category = date("Y-",$date).$week; $distance = ($row["distance"]); $movingTime = $row["movingTime"]; $elapsedTime = $row["elapsedTime"]; $totalElevationGain = ($row["totalElevationGain"])*3.28084; switch ($dataToDisplay) { //distance case "distance": $dataSerie["data"][$category] += $distance; break; //Moving Time case "movingTime": break; //Elapsed Time case "elapsedTime": break; //elevation gain case "totalElevationGain": break; //number activities case "activities": break; } } }; $data = array(); array_push($data,$dataSerie); echo json_encode($data); ?&gt; </code></pre> <p>My ajax returns this:</p> <p>[{"name":"Weekly Stats","data":{"2019-17":13184.4,"2019-18":73560.2,"2019-19":36899.4,"2019-20":0,"2019-21":38691.3,"2019-22":165127.8,"2019-23":188163.2,"2019-24":12888.5,"2019-25":60011.3,"2019-26":32585.2,"2019-27":12952.8,"2019-28":7944.8,"2019-29":79258.3,"2019-30":60885.2,"2019-31":0,"2019-32":0,"2019-33":0,"2019-34":0,"2019-35":0,"2019-36":0,"2019-37":30974.6,"2019-38":7766.5,"2019-39":7685,"2019-40":21128.7,"2019-41":28996,"2019-42":46362.6,"2019-43":0,"2019-44":0,"2019-45":63694.8,"2019-46":81551.1,"2019-47":104595.9,"2019-48":18121.7,"2019-49":18691.6,"2019-50":37538,"2019-51":40671.8,"2019-52":22109.6,"2020-01":22079,"2020-02":22086.7,"2020-03":21933.2,"2020-04":30702.1,"2020-05":58259,"2020-06":38811.3,"2020-07":43754,"2020-08":45109.1,"2020-09":50870.1,"2020-10":62917.8,"2020-11":0,"2020-12":95912.5,"2020-13":20836.2,"2020-14":25293,"2020-15":110540.5,"2020-16":150804.9}}]</p> <p>How do I structure my data so I can feed my chart?</p>
3
3,013
How to create array of nested comments out of flat array from DB
<p>After querying the DB for comments that are nested in a closure table, like Bill Karwin suggests here <a href="https://stackoverflow.com/questions/192220/what-is-the-most-efficient-elegant-way-to-parse-a-flat-table-into-a-tree/192462#192462">What is the most efficient/elegant way to parse a flat table into a tree?</a>, I now get the following datastructure from SQL:</p> <pre><code>"comments": [ { "id": "1", "breadcrumbs": "1", "body": "Bell pepper melon mung." }, { "id": "2", "breadcrumbs": "1,2", "body": "Pea sprouts green bean." }, { "id": "3", "breadcrumbs": "1,3", "body": "Komatsuna plantain spinach sorrel." }, { "id": "4", "breadcrumbs": "1,2,4", "body": "Rock melon grape parsnip." }, { "id": "5", "breadcrumbs": "5", "body": "Ricebean spring onion grape." }, { "id": "6", "breadcrumbs": "5,6", "body": "Chestnut kohlrabi parsnip daikon." } ] </code></pre> <p>Using PHP I would like to restructure this dataset, so the comments are nested like this:</p> <pre><code>"comments": [ { "id": "1", "breadcrumbs": "1", "body": "Bell pepper melon mung." "comments": [ { "id": "2", "breadcrumbs": "1,2", "body": "Pea sprouts green bean." "comments": [ { "id": "4", "breadcrumbs": "1,2,4", "body": "Rock melon grape parsnip." } ] }, { "id": "3", "breadcrumbs": "1,3", "body": "Komatsuna plantain spinach sorrel." } ] }, { "id": "5", "breadcrumbs": "5", "body": "Ricebean spring onion grape." "comments": [ { "id": "6", "breadcrumbs": "5,6", "body": "Chestnut kohlrabi parsnip daikon." } ] } ] </code></pre> <p>I have hacked together a solution, but it seems over complex, and I have a feeling that there is some clever solution out there to do this in an elegant and efficient way, but I dont know how?</p>
3
1,814
How can I automatically switch to a Spring profile to another one during the execution of an application? (to change the DB on which a DAO work)
<p>I am working on a batch application developed using Spring. This application have to read on a database and then have to write on another database.</p> <p>So I know that I can create 2 different DAO with 2 different connections but I am trying to do it using Spring profiles.</p> <p>So I have the following situation, I have a configuration file named <code>databaseConfiguration.xml</code> that contains the information for the DB connection (I import this file into the main configuration file <strong>applicationContext.xml</strong>):</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:jdbc=&quot;http://www.springframework.org/schema/jdbc&quot; xmlns:tx=&quot;http://www.springframework.org/schema/tx&quot; xsi:schemaLocation=&quot;http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd&quot;&gt; &lt;tx:annotation-driven transaction-manager=&quot;tjtJTransactionManager&quot; /&gt; &lt;!-- DB CONNECTIONS: --&gt; &lt;bean id=&quot;tjtJTransactionManager&quot; class=&quot;org.springframework.jdbc.datasource.DataSourceTransactionManager&quot; scope=&quot;singleton&quot;&gt; &lt;property name=&quot;dataSource&quot; ref=&quot;dataSourcePUC&quot; /&gt; &lt;/bean&gt; &lt;!-- PROFILO DI PRODUZIONE --&gt; &lt;beans profile=&quot;PROD&quot;&gt; &lt;bean id=&quot;dataSourcePUC&quot; class=&quot;org.apache.commons.dbcp.BasicDataSource&quot; destroy-method=&quot;close&quot;&gt; &lt;property name=&quot;driverClassName&quot; value=&quot;net.sourceforge.jtds.jdbc.Driver&quot; /&gt; &lt;property name=&quot;url&quot; value=&quot;jdbc:jtds:sqlserver://XXX.myCompany.YYYY.it:1433/DB_1&quot; /&gt; &lt;property name=&quot;username&quot; value=&quot;username&quot; /&gt; &lt;property name=&quot;password&quot; value=&quot;pswd&quot; /&gt; &lt;/bean&gt; &lt;/beans&gt; &lt;!-- PROFILO DI COLLAUDO --&gt; &lt;beans profile=&quot;COLL&quot;&gt; &lt;bean id=&quot;dataSourcePUC&quot; class=&quot;org.apache.commons.dbcp.BasicDataSource&quot; destroy-method=&quot;close&quot;&gt; &lt;property name=&quot;driverClassName&quot; value=&quot;net.sourceforge.jtds.jdbc.Driver&quot; /&gt; &lt;property name=&quot;url&quot; value=&quot;jdbc:jtds:sqlserver://XXXX.MYCOMPANY.YYYY.it:1433/DB_2&quot; /&gt; &lt;property name=&quot;username&quot; value=&quot;username&quot; /&gt; &lt;property name=&quot;password&quot; value=&quot;pswd&quot; /&gt; &lt;/bean&gt; &lt;/beans&gt; &lt;/beans&gt; </code></pre> <p>As you can see in the previous snippet I am defining 2 different profiles that defines 2 different version of the datasource bean with <code>id=&quot;dataSourcePUC&quot;</code> that create the connection to my 2 different database.</p> <p>So, into my <code>main()</code> method I do something like this:</p> <pre><code>GenericXmlApplicationContext context = new GenericXmlApplicationContext(); ConfigurableEnvironment conf = (ConfigurableEnvironment) context.getEnvironment(); conf.setActiveProfiles(&quot;PROD&quot;); context.load(&quot;applicationContext.xml&quot;); context.refresh(); pucManager = (PucManager) context.getBean(&quot;pucManager&quot;); // my DAO // QUERY PERFORMED ON THE DB_1: List&lt;TassoRendimentoInterno&gt; tassoRendimentoInternoList = pucManager.getTassoRendimentoInterno(); // THIS SECOND QUERY HAVE TO BE PERFORMED ON THE DB_2 List&lt;TassoInternoRendimentoFondo&gt; tassoInternoRendimentoFondoList = pucManager.getTassoRendimentoInternoFondo(); </code></pre> <p>In this code snippet first I set the active profile on <strong>PROD</strong> so it is used the <strong>DB_1</strong>, in this way:</p> <pre><code>ConfigurableEnvironment conf = (ConfigurableEnvironment) context.getEnvironment(); conf.setActiveProfiles(&quot;PROD&quot;); </code></pre> <p>It work fine and the query are performed on this DB.</p> <p>The problem is that I want to perform the second query on the <strong>DB_2</strong>, so before this line:</p> <pre><code>List&lt;TassoInternoRendimentoFondo&gt; tassoInternoRendimentoFondoList = pucManager.getTassoRendimentoInternoFondo(); </code></pre> <p>I have to set the other profile <strong>COLL</strong>.</p> <p>To do this operation I also have to stop and refresh the context?</p> <p>How can exactly do it? What is the best solution?</p>
3
1,993
Uncaught type error : Cannot read value 'name' of undefined
<p>Actually I am having a global JSON, when I am trying to parse its value in loop, it is showing me error "uncaught type error : Cannot read value 'name' of undefined". I have tried a lot but I am still not able to figure out any solution for it.</p> <pre><code> $(document).ready(function(){ var productJSON = [ {id:"1001",name:"Hopper1",image:"images/290161k.jpg"}, {id:"1002",name:"Hopper2",image:"images/290161k.jpg"}, {id:"1003",name:"Hopper3",image:"images/290161k.jpg"}, {id:"1004",name:"Hopper4",image:"images/290161k.jpg"}, {id:"1005",name:"Hopper5",image:"images/290161k.jpg"}, {id:"1006",name:"Hopper6",image:"images/290161k.jpg"}, {id:"1007",name:"Hopper7",image:"images/290161k.jpg"}, {id:"1008",name:"Hopper8",image:"images/290161k.jpg"} ]; var a=0; for(var i=0;i&lt;productJSON.length;i++){ var pagedisplay = ''; for(var j=0;j&lt;2;j++){ var generatedProductDisplay = ''; generatedProductDisplay = '&lt;div id="'+productJSON[a].id+'" class="productDiv"&gt;&lt;a class="productLink" href="#"&gt;&lt;center&gt;&lt;div class="productImage"&gt;&lt;img src="'+productJSON[a].image+'" width="100%" height="200px" alt="'+productJSON[a].name+'"&gt;&lt;/div&gt;&lt;div&gt;&lt;p class="productName"&gt;'+productJSON[a].name+'&lt;/p&gt;&lt;/div&gt;&lt;/center&gt;&lt;/a&gt;&lt;/div&gt;'; pagedisplay = pagedisplay+generatedProductDisplay; a++; } pagedisplay = pagedisplay+'&lt;br/&gt;'; $(".productDisplay").append(pagedisplay); } $(".productDiv").live("click",function(){ alert("Hello"); }); }); </code></pre> <p>This is the HTML code</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;Welcome to Nitin Agro Industries, Chhatarpur&lt;/title&gt; &lt;link href="styles/main.css" type="text/css" rel="stylesheet" /&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="productsDisplay.js" type="text/javascript"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;center&gt; &lt;div class="page-wrap"&gt; &lt;div class="centerContent"&gt; &lt;h1&gt;Explore our Product Catalog&lt;/h1&gt; &lt;div class="centerText"&gt; &lt;center&gt; &lt;div class="hideShowDiv"&gt; skdddddddddddd &lt;/div&gt; &lt;div class="productDisplay"&gt;&lt;/div&gt; &lt;/center&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/center&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
3
1,417
How to call me function in laravel based jwt , Its giving 401 error when hit from my react application?
<p>Below is my auth controller and api routes file login function is working well no issue in that but getting issue on me() function or /me post route please help me to solve it out.</p> <p><strong>AuthController</strong></p> <pre><code>&lt;?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Auth; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use JWTAuth; use JWTFactory; class AuthController extends Controller { /** * Create a new AuthController instance. * * @return void */ public function __construct() { $this-&gt;middleware('auth:api', ['except' =&gt; ['login']]); } /** * Get a JWT via given credentials. * * @return \Illuminate\Http\JsonResponse */ public function index() { return response()-&gt;json(['message' =&gt; 'Ok Bro !'], 200); } public function login(Request $request) { $password= bcrypt($request-&gt;password); $credentials1=[ 'email'=&gt;$request-&gt;email, 'password'=&gt;$password ]; $credentials = request(['email', 'password',]); if (! $token = JWTAuth::attempt($credentials)) { return response()-&gt;json(['error' =&gt; 'Invalid Userid Or Password'], 200); } return $this-&gt;respondWithToken($token); //return $credentials1; // print_r($credentials); //$2y$10$yxnc9WKUM3fw4BlDOjJWM.8SYuLnWdEoRgrM4Nc\/iQspi2cAE8E5K //$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi } /** * Get the authenticated User. * * @return \Illuminate\Http\JsonResponse */ public function me() { // $user = JWTAuth::toUser($token); ///return response()-&gt;json(compact('token', 'user')); return response()-&gt;json(auth()-&gt;user()); } /** * Log the user out (Invalidate the token). * * @return \Illuminate\Http\JsonResponse */ public function logout() { auth()-&gt;logout(); return response()-&gt;json(['message' =&gt; 'Successfully logged out']); } /** * Refresh a token. * * @return \Illuminate\Http\JsonResponse */ public function refresh() { return $this-&gt;respondWithToken(auth()-&gt;refresh()); } /** * Get the token array structure. * * @param string $token * * @return \Illuminate\Http\JsonResponse */ protected function respondWithToken($token) { return response()-&gt;json([ 'access_token' =&gt; $token, 'token_type' =&gt; 'bearer', 'expires_in' =&gt; auth()-&gt;factory()-&gt;getTTL() * 60, 'user'=&gt;auth()-&gt;user() ]); } } </code></pre> <p>Below is api routes file login function is working well no issue in that but getting issue on me() function or /me post route please help me to solve it out.</p> <p><strong>Api Route</strong></p> <pre><code>&lt;?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use App\Http\Controllers\AuthController; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the &quot;api&quot; middleware group. Enjoy building your API! | */ Route::middleware('auth:sanctum')-&gt;get('/user', function (Request $request) { return $request-&gt;user(); }); Route::post('login', 'AuthController@login'); Route::group(['middleware'=&gt;'api'],function(){ Route::post('logout', 'AuthController@logout'); Route::post('refresh', 'AuthController@refresh'); Route::post('me', 'AuthController@me'); }); </code></pre> <p><strong>Result on Post Request in console</strong> Issue i am getting on page from post request in react</p> <p><a href="https://i.stack.imgur.com/obH2d.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/obH2d.jpg" alt="enter image description here" /></a></p>
3
1,738
Large space above navigationTitle (Swift / SwiftUI)
<p>My view has this massive space above the title text and I was am not sure how to get rid of it as everything I've tried seems to do nothing. How can I remove this space? Initially, I intended to just hide the navigation bar, however, I want to the back button for demonstrative purposes.</p> <p>Apologies for all the commented-out code.</p> <p>How the view looks (the blue is just for visualization purposes):</p> <p><a href="https://i.stack.imgur.com/04oRl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/04oRl.png" alt="enter image description here" /></a></p> <p>Code for the above View:</p> <pre><code>struct LoggedinView: View { @Binding var userName:String @Binding var userModelData : UserModelData var userInformation : UserModel? var body: some View{ NavigationView{ VStack{ if let items = userInformation{ /*Text(&quot;\(items.username)'s \(items.type)&quot;) .font(.title) .fontWeight(.bold/)*/ List(items.items, id: \.self){ item in Text(item) } .navigationTitle(&quot;\(items.username)'s \(items.type)&quot;) //.navigationBarHidden(true) } } //.navigationTitle(&quot;Hi&quot;) //.navigationBarHidden(true) //.navigationBarTitleDisplayMode(.inline) }.onAppear { UINavigationBar.appearance().backgroundColor = .blue } //.navigationBarHidden(true) //.navigationTitle(&quot;&quot;) } } </code></pre> <p>Code that displays the view shown:</p> <pre><code>struct ContentView: View { @State public var userName: String = &quot;&quot; @State public var userPassword: String = &quot;&quot; @State private var errorMsg: String = &quot;&quot; @State private var showPassword: Bool = false @State private var authenticationPassed:Bool = false @State var userModelData = UserModelData() var userInformation : UserModel? { userModelData.userInformation.first { $0.username == userName } } @State var errorMsgColor = Color(red:220.0/255.0, green:0.0, blue:0.0) var body: some View { NavigationView{ VStack{ Group{ //titles Text(&quot;Welcome Back!&quot;) .fontWeight(.bold) .font(.largeTitle) UserImage() Spacer() .frame(height: 25) } Group{ //inputs TextField(&quot;Username&quot;, text: $userName ) .padding() .overlay(RoundedRectangle(cornerRadius: 30.0) .stroke(Color.black, lineWidth: 3)) .disableAutocorrection(true) .autocapitalization(.none) Spacer() .frame(height: 20) if showPassword{ TextField(&quot;Password&quot;, text: $userPassword) .padding() .overlay(RoundedRectangle(cornerRadius: 30.0) .stroke(Color.black, lineWidth: 3)) .disableAutocorrection(true) .autocapitalization(.none) }else{ SecureField(&quot;Password&quot;, text: $userPassword) .padding() .overlay(RoundedRectangle(cornerRadius: 30.0) .stroke(Color.black, lineWidth: 3)) .disableAutocorrection(true) .autocapitalization(.none) } ShowPasswordButton(showPassword: $showPassword) } Group{ //error msg + button Button(action:{ if self.userName == userInformation?.username &amp;&amp; self.userPassword == userInformation?.password { self.authenticationPassed = true }else{ self.authenticationPassed = false } if !authenticationPassed { errorMsg = &quot;Incorrect username or password, please try again&quot; errorMsgColor = Color(red:220.0/255.0, green:0.0, blue:0.0) }else{ errorMsg = &quot;Success&quot; errorMsgColor = Color(red:0.0, green:200.0/255.0, blue:0.0) } }){ CustomButtonStyle(buttonText: &quot;Login&quot;) } Spacer() .frame(height: 25) Text(errorMsg) .foregroundColor(errorMsgColor) NavigationLink(destination: LoggedinView(userName: $userName, userModelData: $userModelData, userInformation: userInformation), isActive: $authenticationPassed){ EmptyView() } //.navigationTitle(&quot;&quot;) .navigationBarHidden(true) } } .padding() //.navigationTitle(&quot;&quot;) .navigationBarHidden(true) } } } </code></pre>
3
3,212
Getting ValueError while fitting ANN
<p>I am trying to fit ANN on Kaggle's Titanic dataset but getting ValueError. When I used RandomForest, there was no problem and when I am trying to use Artificial Neural Network, the code is throwing below error. Can you point out why I am getting the below error. I have pasted the code below</p> <pre><code> import numpy as np import pandas as pd train_data = pd.read_csv("/kaggle/input/titanic/train.csv") test_data = pd.read_csv("/kaggle/input/titanic/test.csv") y = train_data["Survived"] y = np.array(y.values.tolist()) features = ["Pclass", "Sex", "SibSp", "Parch", "Age", "Fare"] X = pd.get_dummies(train_data[features]) X_test = pd.get_dummies(test_data[features]) from sklearn.impute import SimpleImputer my_imputer = SimpleImputer() X = my_imputer.fit_transform(X) my_imputer = SimpleImputer() X_test = my_imputer.fit_transform(X_test) from sklearn.preprocessing import StandardScaler sc= StandardScaler() X=sc.fit_transform(X) X_test=sc.transform(X_test) import keras from keras.models import Sequential from keras.layers import Dense classifier = Sequential() classifier.add(Dense(units=4, kernel_initializer='uniform', activation= 'relu', input_dim=6)) classifier.add(Dense(units=4, kernel_initializer='uniform', activation='relu')) classifier.add(Dense(units=1, kernel_initializer='uniform', activation='sigmoid')) classifier.compile(optimizer = 'adam', loss='binary_crossentropy', metrics=['accuracy']) #Fitting the ANN to the Training set classifier.fit(X, y, batch_size=10, epochs=100) </code></pre> <p>Error as below</p> <pre><code> --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-30-f7e7c8ad52f1&gt; in &lt;module&gt; ----&gt; 1 classifier.fit(X, y, batch_size=10, epochs=100) /opt/conda/lib/python3.7/site-packages/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs) 1152 sample_weight=sample_weight, 1153 class_weight=class_weight, -&gt; 1154 batch_size=batch_size) 1155 1156 # Prepare validation data. /opt/conda/lib/python3.7/site-packages/keras/engine/training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size) 577 feed_input_shapes, 578 check_batch_axis=False, # Don't enforce the batch size. --&gt; 579 exception_prefix='input') 580 581 if y is not None: /opt/conda/lib/python3.7/site-packages/keras/engine/training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix) 143 ': expected ' + names[i] + ' to have shape ' + 144 str(shape) + ' but got array with shape ' + --&gt; 145 str(data_shape)) 146 return data 147 ValueError: Error when checking input: expected dense_11_input to have shape (6,) but got array with shape (7,) </code></pre> <p>I tried converting y variable to array but it still giving the same error. </p>
3
1,485
Swing error ClassCastException
<p>This is the Code I typed</p> <pre><code>// loading all distict age on to list bix from student table private void b1ActionPerformed(java.awt.event.ActionEvent evt) { DefaultTableModel tb = (DefaultTableModel)tb1.getModel(); tb.setRowCount(0); String sql = "select * from student"; try { Class.forName("java.sql.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/info","root",""); Statement s = con.createStatement(); ResultSet rs = s.executeQuery(sql); while(rs.next()) { int s_rno = rs.getInt(1); String s_name = rs.getString(2); int s_age = rs.getInt(3); double s_marks = rs.getDouble(4); tb.addRow(new Object[]{s_rno, s_name, s_age, s_marks}); tb1.setModel(tb); } rs.close(); s.close(); con.close(); } catch(Exception e) { JOptionPane.showMessageDialog(this, e.getMessage()); } } </code></pre> <p>And when I run the program, the GUI appears, but on pressing the button, nothing happens, and there is the following error on my output window</p> <blockquote> <p>Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: JDBC2$2 cannot be cast to javax.swing.DefaultListModel at JDBC2.b1ActionPerformed(JDBC2.java:74) at JDBC2.access$000(JDBC2.java:9) at JDBC2$1.actionPerformed(JDBC2.java:36) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022) at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252) at java.awt.Component.processMouseEvent(Component.java:6535) at javax.swing.JComponent.processMouseEvent(JComponent.java:3324) at java.awt.Component.processEvent(Component.java:6300) at java.awt.Container.processEvent(Container.java:2236) at java.awt.Component.dispatchEventImpl(Component.java:4891) at java.awt.Container.dispatchEventImpl(Container.java:2294) at java.awt.Component.dispatchEvent(Component.java:4713) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466) at java.awt.Container.dispatchEventImpl(Container.java:2280) at java.awt.Window.dispatchEventImpl(Window.java:2750) at java.awt.Component.dispatchEvent(Component.java:4713) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758) at java.awt.EventQueue.access$500(EventQueue.java:97) at java.awt.EventQueue$3.run(EventQueue.java:709) at java.awt.EventQueue$3.run(EventQueue.java:703) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86) at java.awt.EventQueue$4.run(EventQueue.java:731) at java.awt.EventQueue$4.run(EventQueue.java:729) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:728) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93) at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)</p> </blockquote> <p>I need more help , how i can comprehend the error.</p>
3
1,533
Replace dt element with jQuery (phpBB)
<p>I tried searching, but all the examples and answers I found I couldn't get to work.</p> <p>phpBB has the following lines of code:</p> <pre><code> &lt;!-- IF topicrow.S_FIRST_ROW or not topicrow.S_TOPIC_TYPE_SWITCH --&gt; &lt;div class="forumbg&lt;!-- IF topicrow.S_TOPIC_TYPE_SWITCH and (topicrow.S_POST_ANNOUNCE or topicrow.S_POST_GLOBAL) --&gt; announcement&lt;!-- ENDIF --&gt;"&gt; &lt;div class="inner"&gt; &lt;ul class="topiclist"&gt; &lt;li class="header"&gt; &lt;dl class="row-item"&gt; &lt;dt&lt;!-- IF S_DISPLAY_ACTIVE --&gt; id="active_topics"&lt;!-- ENDIF --&gt;&gt;&lt;div class="list-inner"&gt;&lt;!-- IF S_DISPLAY_ACTIVE --&gt;{L_ACTIVE_TOPICS}&lt;!-- ELSEIF topicrow.S_TOPIC_TYPE_SWITCH and (topicrow.S_POST_ANNOUNCE or topicrow.S_POST_GLOBAL) --&gt;{L_ANNOUNCEMENTS}&lt;!-- ELSE --&gt;{L_TOPICS}&lt;!-- ENDIF --&gt;&lt;/div&gt;&lt;/dt&gt; &lt;dd class="posts"&gt;{L_REPLIES}&lt;/dd&gt; &lt;dd class="views"&gt;{L_VIEWS}&lt;/dd&gt; &lt;dd class="lastpost"&gt;&lt;span&gt;{L_LAST_POST}&lt;/span&gt;&lt;/dd&gt; &lt;/dl&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>I'm trying to relace this part (the entire line)</p> <pre><code>&lt;dt&lt;!-- IF S_DISPLAY_ACTIVE --&gt; id="active_topics"&lt;!-- ENDIF --&gt;&gt; &lt;div class="list-inner"&gt; &lt;!-- IF S_DISPLAY_ACTIVE --&gt;{L_ACTIVE_TOPICS} &lt;!-- ELSEIF topicrow.S_TOPIC_TYPE_SWITCH and (topicrow.S_POST_ANNOUNCE or topicrow.S_POST_GLOBAL) --&gt;{L_ANNOUNCEMENTS} &lt;!-- ELSE --&gt;{L_TOPICS}&lt;!-- ENDIF --&gt; &lt;/div&gt; &lt;/dt&gt; </code></pre> <p>For reference, I need to change it to</p> <pre><code>&lt;dt&lt;!-- IF S_DISPLAY_ACTIVE --&gt; id="active_topics"&lt;!-- ENDIF --&gt;&gt; &lt;div class="list-inner"&gt; &lt;!-- IF S_DISPLAY_ACTIVE --&gt;{L_ACTIVE_TOPICS} &lt;!-- ELSEIF topicrow.S_TOPIC_TYPE eq 3 --&gt;{L_GLOBAL_ANNOUNCEMENTS} &lt;!-- ELSEIF (topicrow.S_POST_ANNOUNCE or topicrow.S_POST_GLOBAL) eq 2 --&gt;{L_ANNOUNCEMENTS} &lt;!-- ELSEIF topicrow.S_TOPIC_TYPE eq 1 --&gt;{L_STICKY} &lt;!-- ELSE --&gt;{L_TOPICS}&lt;!-- ENDIF --&gt; &lt;/div&gt; &lt;/dt&gt; </code></pre> <p>Can someone provide the entire jquery code I need to make this work please? Thank you.</p>
3
1,206
How to add relationships in Django fixtures by explicitly adding object's fields?
<p>I'm working with Django Framework. I have two models: Component and ComponentProperty.</p> <pre><code>class Component(models.Model): name = models.CharField(unique=True, max_length=255) component_properties = models.ManyToManyField(ComponentProperty) class ComponentProperty(models.Model): label = models.CharField(unique=True, max_length=255) component_type = models.CharField(max_length=255) </code></pre> <p>And serializers:</p> <pre><code>class ComponentSerializer(serializers.ModelSerializer): class Meta: model = Component fields = ('name', 'component_properties') depth = 1 class ComponentPropertySerializer(serializers.ModelSerializer): class Meta: model = ComponentProperty fields = ('label', 'component_type') </code></pre> <p>I'm trying to load data with fixtures. I wrote and fixture file that look like this: </p> <pre><code>[ { "pk":1, "model":"api.componentproperty", "fields":{ "label":"label", "component_type":"text" } }, { "pk":2, "model":"api.componentproperty", "fields":{ "label":"description", "component_type":"text", } }, { "pk":1, "model":"api.component", "fields":{ "name":"text", "component_properties":[ 1, 2 ] } } ] </code></pre> <p>That's work fine! But I have 20 fixtures to load. I want to have fixture (component.json for example) look like this bellow:</p> <pre><code>[ { "pk":null, "model":"api.component", "fields":{ "name":"text", "component_properties":[ { "pk":null, "model":"api.componentproperty", "fields":{ "label":"label", "component_type":"text" } }, { "pk":null, "model":"api.componentproperty", "fields":{ "label":"description", "component_type":"text", } } ] } } ] </code></pre> <p>The icing on the cake must be fixtures specifying a primary key like <a href="https://stackoverflow.com/questions/1499898/django-create-fixtures-without-specifying-a-primary-key">here</a>. Please, can anyone help me to write these fixtures without pk and the relationships described above?</p>
3
1,130
C- Server/clients, Wait for an other client and then exit
<p>I have a server and a client, when I open the server I must open 2 Terminals, one for products selection and one for pay these products. I made this code for the client but I can't find out this: When I open the first client by typing <code>./client localhost</code> I want to select a product from the vending machine, once the product is selected I transfer the product using sockets to the server. Then when I open the second client <code>./client localhost</code> the server transfer the price to this second client and then I wrote a code for insert moneys. Once the product has been paid the second client leaves. Well I want that the first client wait the second, and only when the second leaves the first client leaves too. Should I use waitpid?</p> <p>Thank you for your time, this is the code: </p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; #include &lt;errno.h&gt; #include &lt;string.h&gt; #include &lt;netdb.h&gt; #include &lt;sys/types.h&gt; #include &lt;netinet/in.h&gt; #include &lt;sys/socket.h&gt; #include "funzioni.h" #define PORT 3490 #define MAXDATASIZE 100 int main(int argc, char *argv[]) { int sockfd;// numbytes; //char buf[MAXDATASIZE]; struct hostent *he; struct sockaddr_in their_addr; // informazioni sull’indirizzo di chi si connette if (argc != 2) { fprintf(stderr,"usage: client hostname\n"); exit(1); } if ((he=gethostbyname(argv[1])) == NULL) { // ottiene le informazioni sull’host herror("gethostbyname"); exit(1); } if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } their_addr.sin_family = AF_INET; // host byte order their_addr.sin_port = htons(PORT); // short, network byte order their_addr.sin_addr = *((struct in_addr *)he-&gt;h_addr); memset(their_addr.sin_zero, '\0', sizeof their_addr.sin_zero); if (connect(sockfd, (struct sockaddr *)&amp;their_addr,sizeof their_addr) == -1) { perror("connect"); exit(1); } //When the server is running, if I open a client I want to select products, when I open an other client I want to pay. // Read the number of client, the first connected receives f=1 and // the second f=2, I managed this in the server code int received_int=0 ; int return_status = read(sockfd, &amp;received_int, sizeof(received_int)); if (return_status &gt; 0) { fprintf(stdout, "Client # = %d\n", ntohl(received_int)); } else { perror("read"); exit(1); } //Open Client1 - Select product int f = ntohl(received_int); if(f==1){ //CODE FOR THE FIRST CLIENT //Select product } //Open client2 - Pay if(f==2){ // CODE FOR THE SECOND CLIENT //pay, insert money, confirm, take the product } exit(EXIT_SUCCESS); } </code></pre>
3
1,029
how do I pass the values after each iteration of the loop to a separate variable, or to an array for subsequent use/ use in the loop?
<pre><code>public static void Run() { public static string desktop = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop); //List&lt;string&gt; found = new List&lt;string&gt;(); //MemoryStream memoryone = default; using (var result = new MemoryStream()) { using (var archive = new ZipArchive(result, ZipArchiveMode.Create, true)) { foreach (string p in found) // List&lt;string&gt; found { var pr = archive.CreateEntry(&quot;Found_&quot; + p + &quot;.txt&quot;); using (var entryStream = pr.Open()) { memoryone.CopyTo(entryStream); // MemoryStream memoryone } } } File.WriteAllBytes(@&quot;found.zip&quot;, result.ToArray()); } foreach (string path in Paths.sWPaths) { List&lt;string&gt; my = new List&lt;string&gt; { &quot;qw&quot;, &quot;er&quot;, &quot;ty&quot;, &quot;ui&quot;, &quot;op&quot;, &quot;as&quot;, &quot;df&quot;, &quot;gh&quot;, }; List&lt;string&gt; found = Directory.EnumerateDirectories(desktop + &quot;//&quot;) .Select(d =&gt; new DirectoryInfo(path).Name).Where(n =&gt; my.Contains(n)).ToList(); List&lt;file&gt; Informone = Data.Get(desktop + path); MemoryStream memoryone = new MemoryStream(cUtils.WriteOne(Informone).ToArray()); } } </code></pre> <p>how do I pass the VALUES after each ITERATION of the loop to a separate variable, or to an array for later use in the loop? (I warn you right away, I don't need to output the final value of the loop, but the values of each iteration)</p> <p>I need to pass the values of &quot;List &lt; string &gt; found&quot; after each iteration to an array or to a variable</p> <pre><code>foreach (string path in Paths.sWPaths) { List&lt;string&gt; my = new List&lt;string&gt; { &quot;qw&quot;, &quot;er&quot;, &quot;ty&quot;, &quot;ui&quot;, &quot;op&quot;, &quot;as&quot;, &quot;df&quot;, &quot;gh&quot;, }; List&lt;string&gt; found = Directory.EnumerateDirectories(desktop + &quot;//&quot;) Select(d =&gt; new DirectoryInfo(path).Name).Where(n =&gt; my.Contains(n)).ToList(); } </code></pre> <p>for use in another cycle</p> <pre><code>foreach (string p in found) // List&lt;string&gt; found { var pr = archive.CreateEntry(&quot;Found_&quot; + p + &quot;.txt&quot;); } </code></pre> <p>I need to pass the values of &quot;MemoryStream memoryone&quot; after each iteration to an array or to a variable</p> <pre><code>foreach (string path in Paths.sWPaths) { List&lt;file&gt; Informone = Data.Get(desktop + path); MemoryStream memoryone = new MemoryStream(cUtils.WriteOne(Informone).ToArray()); //MemoryStream memoryone } </code></pre> <p>for use here</p> <pre><code>using (var entryStream = pr.Open()) { memoryone.CopyTo(entryStream); // MemoryStream memoryone } </code></pre>
3
1,454
Calculating the angle between two vectors using a needle-like triangle
<p>I implemented a function (<code>angle_between</code>) to calculate the angle between two vectors. It makes use of needle-like triangles and is based on <a href="https://people.eecs.berkeley.edu/%7Ewkahan/Triangle.pdf" rel="nofollow noreferrer">Miscalculating Area and Angles of a Needle-like Triangle</a> and <a href="https://scicomp.stackexchange.com/questions/27689/numerically-stable-way-of-computing-angles-between-vectors">this related question</a>.</p> <p>The function appears to work fine most of the time, except for one weird case where I don't understand what is happening:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np vectorA = np.array([0.008741225033460295, 1.1102230246251565e-16], dtype=np.float64) vectorB = np.array([1, 0], dtype=np.float64) angle_between(vectorA, vectorB) # is np.nan </code></pre> <p>Digging into my function, the <code>np.nan</code> is produced by taking the square root of a negative number, and the negative number seems to be the result of the increased accuracy of the method:</p> <pre class="lang-py prettyprint-override"><code>foo = 1.0 # np.linalg.norm(vectorA) bar = 0.008741225033460295 # np.linalg.norm(vectorB) baz = 0.9912587749665397 # np.linalg.norm(vectorA- vectorB) # algebraically equivalent ... numerically not so much order1 = baz - (foo - bar) order2 = bar - (foo - baz) assert order1 == 0 assert order2 == -1.3877787807814457e-17 </code></pre> <p>According to Kahan's paper, this means that the triplet (foo, bar, baz) actually doesn't represent the side lengths of a triangle. However, this should - in fact - be the case given how I constructed the triangle (see the comments in the code).</p> <p>From here, I feel a bit lost as to where to look for the source of the error. Could somebody explain to me what is happening?</p> <hr /> <p>For completeness, here is the full code of my function:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np from numpy.typing import ArrayLike def angle_between( vec_a: ArrayLike, vec_b: ArrayLike, *, axis: int = -1, eps=1e-10 ) -&gt; np.ndarray: &quot;&quot;&quot;Computes the angle from a to b Notes ----- Implementation is based on this post: https://scicomp.stackexchange.com/a/27694 &quot;&quot;&quot; vec_a = np.asarray(vec_a)[None, :] vec_b = np.asarray(vec_b)[None, :] if axis &gt;= 0: axis += 1 len_c = np.linalg.norm(vec_a - vec_b, axis=axis) len_a = np.linalg.norm(vec_a, axis=axis) len_b = np.linalg.norm(vec_b, axis=axis) mask = len_a &gt;= len_b tmp = np.where(mask, len_a, len_b) np.putmask(len_b, ~mask, len_a) len_a = tmp mask = len_c &gt; len_b mu = np.where(mask, len_b - (len_a - len_c), len_c - (len_a - len_b)) numerator = ((len_a - len_b) + len_c) * mu denominator = (len_a + (len_b + len_c)) * ((len_a - len_c) + len_b) mask = denominator &gt; eps angle = np.divide(numerator, denominator, where=mask) np.sqrt(angle, out=angle) np.arctan(angle, out=angle) angle *= 2 np.putmask(angle, ~mask, np.pi) return angle[0] </code></pre> <p><strong>Edit:</strong> The problem is definitely related to <code>float64</code> and disappears when performing the computation with larger floats:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np vectorA = np.array([0.008741225033460295, 1.1102230246251565e-16], dtype=np.float128) vectorB = np.array([1, 0], dtype=np.float128) assert angle_between(vectorA, vectorB) == 0 </code></pre>
3
1,372
PointCloud2 Storage Format
<p>I am trying to implement in FPGA a ROS publisher node of PointCloud2 messages. As a first step, i have already implemented a publisher node on the FPGA that is publishing strings. Now, i am trying to do the same but for the PointCloud2 message format.</p> <p>It is very simple to understand how a string is stored, basically each character is converted to its ASCII value and stored (as it can be seen <a href="http://wiki.ros.org/ROS/Connection%20Header" rel="nofollow noreferrer">here</a>). On the other hand, a PointCloud2 is a complex data type that is not so easy to understand.</p> <p>I have made some progress on understanding how the metadata of a PointCloud2 is stored, however, it is being very difficult to understand the storage of the data part of the PointCloud2 data type. To simplify, I have also tried a PointCloud2 with only one point but i couldn't decode it either. I know that the X, Y and Z are sequentially ordered with 4 bytes each (the datatype is a Float32). Therefore, i can isolate the 4 bytes corresponding to one of the coordinates. I have tried to assign to the X coordinate the values from 0 to 17 (in decimal). This are the values stored when using these values (they are all in decimal):</p> <p>1 = [0, 0, 128, 63] -&gt; little-endian so, the most significant byte is 63 followed by, 128, 0, 0</p> <p>2 = [0, 0, 0, 64]</p> <p>3 = [0, 0, 64, 64]</p> <p>4 = [0, 0, 128, 64]</p> <p>5 = [0, 0, 160, 64]</p> <p>6 = [0, 0, 192, 64]</p> <p>7 = [0, 0, 224, 64]</p> <p>8 = [0, 0, 0, 65]</p> <p>9 = [0, 0, 16, 65]</p> <p>10 = [0, 0, 32, 65]</p> <p>11 = [0, 0, 48, 65]</p> <p>12 = [0, 0, 64, 65]</p> <p>13 = [0, 0, 80, 65]</p> <p>14 = [0, 0, 96, 65]</p> <p>15 = [0, 0, 112, 65]</p> <p>16 = [0, 0, 128, 65]</p> <p>17 = [0, 0, 136, 65]</p> <p>So, my question is, how are the values stored? Supposedly the data part is stored in binary blobs according to <a href="http://docs.ros.org/en/api/sensor_msgs/html/msg/PointCloud2.html" rel="nofollow noreferrer">here</a>. However, i don't understand what does this mean and how it works. Also, i have not found any concrete example on how to convert a decimal value to this representation.</p> <p>For a PointCloud2 with X, Y and Z my current understanding is the following (<a href="https://imgbb.com/72XdjCc" rel="nofollow noreferrer">here</a> is the corresponding data):</p> <p>header:</p> <ul> <li>seq (4 bytes)</li> <li>stamp (8 bytes)</li> <li>frame_id (1 byte per character)</li> </ul> <p>height: 4 bytes</p> <p>width: 4 bytes</p> <p>fields:</p> <ul> <li>number of fields (4 bytes)</li> </ul> <p>field 1</p> <ul> <li>dimension (4 bytes)</li> <li>name (1 byte)</li> <li>offset (4 bytes)</li> <li>datatype (1 byte)</li> <li>count (4 bytes)</li> </ul> <p>field 2</p> <ul> <li>dimension (4 bytes)</li> <li>name (1 byte)</li> <li>offset (4 bytes)</li> <li>datatype (1 byte)</li> <li>count (4 bytes)</li> </ul> <p>field 3</p> <ul> <li>dimension (4 bytes)</li> <li>name (1 byte)</li> <li>offset (4 bytes)</li> <li>datatype (1 byte)</li> <li>count (4 bytes)</li> </ul> <p>is_bigendian: 1 byte</p> <p>point_step: 4 bytes</p> <p>row_step: 4 bytes</p> <p>size: 4 bytes</p> <p>data: size bytes</p> <p>is_dense: 1 byte</p>
3
1,218
unable to return json from django view to axios
<p>I want to make a Visual search interface with keywords and category to search sth. Obviously, It needs front-end and back-end data interaction. So after weighing some tools, I have choosed <strong>Vue</strong> and <strong>axios</strong> to implement data interaction in the <strong>front-end</strong>, and <strong>django view</strong> in the <strong>front-end</strong>.</p> <p>In my index.html page, I defined my axios like this. </p> <pre><code>var param = new URLSearchParams(); param.append('searchKey',this.searchKey); param.append('category',this.selected); axios.post("{% url 'main:getCommodityInfo'%}", param, {headers:{'X-CSRFToken': this.getCookie('csrftoken')}},) .then(response=&gt;{ console.log(response); }) .catch(error=&gt;{ console.log(error); alert("connection has error") }) </code></pre> <p><strong>searchKey</strong> and <strong>category</strong> could be acquired by Vue object. Then I post the data to my back-end django view.</p> <pre><code>def getCommodityInfo(request): if request.method=="POST": # To get the POST paramaters searchKey = request.POST.get('searchKey') category = request.POST.get('category') # unique ID for each record for DB uniqueId = str(uuid4()) print("Enter the view! ",searchKey,category) # set setting settings = { 'unique_id': uniqueId, 'USER_AGENT': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' } # task Id to indentify each spider task task = scrapyd.schedule('JDSpider', 'getCommodityInfo', settings=settings, searchKey=searchKey, category=category) print("It seems everything is running well? ") print(task,uniqueId) print("-"*100) return JsonResponse({'taskId': task, 'uniqueId': uniqueId, 'status': 'started'},safe=False) </code></pre> <p>Well, the view could acutally get the POST paramaters. <strong><em>But When I am trying to return the status json from view to the axios function, error occurs.</em></strong> </p> <pre><code>[20/Mar/2019 21:03:08] "GET /main/ HTTP/1.1" 200 7216 [20/Mar/2019 21:03:08] "GET /static/main/axios.min.js HTTP/1.1" 304 0 [20/Mar/2019 21:03:08] "GET /static/main/axios.min.map HTTP/1.1" 304 0 Enter the view! switch Electronics [20/Mar/2019 21:03:30] "GET /main/?searchKey=switch&amp;category=Electronics HTTP/1.1" 200 7216 It seems everything is running well? 8fdcee984b1011e9b7e5ace010528bab e07cd1ee-efe8-4c23-8457-51732aa57435 ---------------------------------------------------------------------------------------------------- [20/Mar/2019 21:03:33] "POST /main/getCommodityInfo/ HTTP/1.1" 200 119 Traceback (most recent call last): File "D:\Anacaonda\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "D:\Anacaonda\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "D:\Anacaonda\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "D:\Anacaonda\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "D:\Anacaonda\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "D:\Anacaonda\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "D:\Anacaonda\lib\socketserver.py", line 775, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] The software in your host has aborted an established connection. [20/Mar/2019 21:03:33] "POST /main/getCommodityInfo/ HTTP/1.1" 500 59 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 11890) Traceback (most recent call last): File "D:\Anacaonda\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "D:\Anacaonda\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "D:\Anacaonda\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "D:\Anacaonda\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "D:\Anacaonda\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "D:\Anacaonda\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "D:\Anacaonda\lib\socketserver.py", line 775, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] The software in your host has aborted an established connection. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\Anacaonda\lib\wsgiref\handlers.py", line 141, in run self.handle_error() File "D:\Anacaonda\lib\site-packages\django\core\servers\basehttp.py", line 86, in handle_error super().handle_error() File "D:\Anacaonda\lib\wsgiref\handlers.py", line 368, in handle_error self.finish_response() File "D:\Anacaonda\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "D:\Anacaonda\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "D:\Anacaonda\lib\wsgiref\handlers.py", line 331, in send_headers if not self.origin_server or self.client_is_modern(): File "D:\Anacaonda\lib\wsgiref\handlers.py", line 344, in client_is_modern return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9' TypeError: 'NoneType' object is not subscriptable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\Anacaonda\lib\socketserver.py", line 639, in process_request_thread self.finish_request(request, client_address) File "D:\Anacaonda\lib\socketserver.py", line 361, in finish_request self.RequestHandlerClass(request, client_address, self) File "D:\Anacaonda\lib\socketserver.py", line 696, in __init__ self.handle() File "D:\Anacaonda\lib\site-packages\django\core\servers\basehttp.py", line 154, in handle handler.run(self.server.get_app()) File "D:\Anacaonda\lib\wsgiref\handlers.py", line 144, in run self.close() File "D:\Anacaonda\lib\wsgiref\simple_server.py", line 35, in close self.status.split(' ',1)[0], self.bytes_sent AttributeError: 'NoneType' object has no attribute 'split' </code></pre> <p>I have tried to debug the process, but the code logic is too complicated to understand. <strong><em>I could only find the errors happens when executing</em></strong> </p> <pre><code>return JsonResponse({'taskId': task, 'uniqueId': uniqueId, 'status': 'started'},safe=False) </code></pre> <p>I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.Thanks in advance.</p> <hr> <p>I' ve looked around and apparently I've got the choice below.</p> <pre><code>&lt;form action="{%url 'main:getCommodityInfo'%}" method="POST"&gt; </code></pre> <p>Using the form could get the json from the django View after my test. But I don't want to use it in my project instead of axios.</p>
3
2,702
Mockito not working when method start Observable
<p>im trying to test a presenter, but the test only pass when things are outside of Observable, my presenter:</p> <pre><code>class CompManCodePresenter @Inject constructor(val apiBag: ServiceModule.ApiBag, disposable: CompositeDisposable, scheduler: SchedulerProvider) : BasePresenter&lt;CompManCodeView&gt;(disposable, scheduler) { fun validateCompmanCode(code: String) { view?.showProgress() if (code.isEmpty()) { view?.emptyCode() view?.hideProgress() } else { val request = mutableMapOf&lt;String, Any?&gt;() request.put("code", code) disposable.add( apiBag.apiMainFast.check_code(JWT.jwt_encrypted(request)) .subscribeOn(scheduler.io()) .observeOn(scheduler.ui()) .subscribe( { result -&gt; view?.hideProgress() }, { error -&gt; view?.hideProgress() view?.onError() }) ) } } </code></pre> <p>rest api part:</p> <pre><code>@POST("v2/check-code") fun check_code(@Body body: JwtDataRequest): Observable&lt;SyncCompManAndDeviceResponse&gt; </code></pre> <p>test that works ok:</p> <pre><code>@Test fun test_code_empty() { val mockedResponse: Throwable = mock() val params = HashMap&lt;String, Any&gt;() val mockedRequest = JWT.jwt_encrypted(params) doReturn(Observable.just(mockedResponse)).`when`(api).check_code(mockedRequest) presenter.validateCompmanCode("") testScheduler.triggerActions() verify(view).showProgress() verify(view).emptyCode() verify(view).hideProgress() } </code></pre> <p><strong>test that is not working (it only run the .showProgress outside</strong> </p> <pre><code> @Test fun test_no_connection() { val mockedResponse: Throwable = mock() val params = HashMap&lt;String, Any&gt;() val mockedRequest = JWT.jwt_encrypted(params) doReturn(Observable.just(mockedResponse)).`when`(api).check_code(mockedRequest) presenter.validateCompmanCode("A") testScheduler.triggerActions() verify(view).showProgress() verify(view).hideProgress() verify(view).onError() } </code></pre> <p>my test class setup:</p> <pre><code> private val view: CompManCodeView = mock() private lateinit var presenter: CompManCodePresenter private lateinit var testScheduler: TestScheduler val api:RestAPI = Mockito.mock(RestAPI::class.java, Mockito.RETURNS_DEEP_STUBS) val apiBag:ServiceModule.ApiBag = Mockito.spy(ServiceModule.ApiBag(api,api,api,api)) @Before fun setUp() { MockitoAnnotations.initMocks(this); val compositeDisposable = CompositeDisposable() testScheduler = TestScheduler() val testSchedulerProvider = TestSchedulerProvider(testScheduler) presenter = CompManCodePresenter(apiBag, disposable = compositeDisposable, scheduler = testSchedulerProvider) presenter.attachView(view) } </code></pre> <p>no error show, the only thing that the test result show is this:</p> <pre><code>Wanted but not invoked: view.hideProgress(); However, there were exactly 2 interactions with this mock: view.setPresenter( CompManCodePresenter@72ee5d84 ); -&gt; BasePresenter.attachView(BasePresenter.kt:13) view.showProgress(); -&gt; at CompManCodePresenter.validateCompmanCode(CompManCodePresenter.kt:21) </code></pre> <p>im following this: <a href="https://github.com/burakeregar/KotlinRxMvpArchitecture" rel="nofollow noreferrer">https://github.com/burakeregar/KotlinRxMvpArchitecture</a></p>
3
1,657
Creating new fields in serializer that access another model's attributes
<p>My API call to <code>api/business-review/3abe3a1e-199c-4a4b-9d3b-e7cb522d6bed/</code> currently returns the following:</p> <pre><code>[ { "id": "3abe3a1e-199c-4a4b-9d3b-e7cb522d6bed", "date_time": "2016-05-31T19:18:24Z", "review": "Another quality job, Anna has a no fuss approach to his job and clearly takes pride in what he does. Will continue to use again and again.", "rating": "4.0", "person": "c1cc5684-1be1-4120-9d81-05aec29f352a", "employee": "ecdc1f99-138c-4f9f-9e1f-b959d59209aa", "service": "1dfa408f-d5bc-4eb2-96ae-e07e7999a01a", } ] </code></pre> <p>Now I want to create three new fields: </p> <ul> <li><p><code>person_name</code> - which grabs the first_name and last_name of the reviewer</p></li> <li><p><code>employee_name</code> - which grabs the first_name and last_name of the employee</p></li> <li><p><code>service_name</code> - which grabs the title of the service</p></li> </ul> <p>I've tried the following so far but it doesn't create any new variables:</p> <p><strong>serializers.py</strong></p> <pre><code>class ReviewSerializer(serializers.ModelSerializer): """ Class to serialize Review objects """ person_name = serializers.CharField(source='person.reviewer.first_name', read_only=True) employee_name = serializers.CharField(source='person.employer.first_name', read_only=True) service_name = serializers.CharField(source='service.title', read_only=True) class Meta: model = Review fields = '__all__' read_only_fields = 'id' </code></pre> <p><strong>models.py</strong></p> <pre><code>class Review(models.Model): """ Review model """ id = models.UUIDField(primary_key=True, default=uuid4, editable=False) date_time = models.DateTimeField(blank=True, null=True, default=None) person = models.ForeignKey(Person, null=True, default=None, related_name='reviewer') employee = models.ForeignKey(Person, null=True, default=None, related_name='employee') review = models.TextField(null=True, default=None) service = models.ForeignKey(Service, null=True, default=None) rating = models.DecimalField(max_digits=4, decimal_places=1) class Person(models.Model): """ Person entity """ id = models.UUIDField(primary_key=True, default=uuid4, editable=False) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) class Service(models.Model): """ Service model """ id = models.UUIDField(primary_key=True, default=uuid4, editable=False) title = models.CharField(max_length=255) </code></pre>
3
1,065
Handling only images with thumbnail creator Azure Function
<p>I created a simple Azure Function that creates thumbnails for images uploaded to a container on Azure which gets triggered by a <code>BlobTrigger</code>.</p> <p>It's working fine but because my container has both image files as well as other types e.g. PDF, Excel, Word, etc., the function gets triggered by all these files.</p> <p>I thought I could address this by making sure that we only process image files using the code below. It kind of works because it only processes image files but it still seems to create placeholder blobs for other file types in the target container.</p> <p>For example, if it detects a file named <code>myfile.pdf</code> in the source container, it still creates a <code>myfile.pdf</code> in the target container but it's 0 Bytes.</p> <p>How do I make sure that a non-image files completely get skipped and not even create placeholders in my target container?</p> <pre><code>[FunctionName(&quot;ImageResizer&quot;)] public async Task Run([BlobTrigger(&quot;my-source-container/{name}&quot;, Connection = &quot;myconnection&quot;)] Stream input, string name, [Blob(&quot;my-thumbnails-container/{name}&quot;, FileAccess.Write, Connection = &quot;myconnection&quot;)] Stream outputBlob, ILogger log) { try { var fileExtension = FileUtils.GetFileExtension(name); if (!string.IsNullOrEmpty(fileExtension)) { if (fileExtension.ToLower() == &quot;png&quot; || fileExtension.ToLower() == &quot;jpg&quot; || fileExtension.ToLower() == &quot;jpeg&quot;) { using (var image = Image.Load(input)) { image.Mutate(x =&gt; x.Resize(new ResizeOptions { Size = new Size(150, 150), Mode = ResizeMode.Crop })); using (var ms = new MemoryStream()) { if(fileExtension.ToLower() == &quot;png&quot;) await image.SaveAsPngAsync(outputBlob); else if(fileExtension.ToLower() == &quot;jpg&quot; || fileExtension.ToLower() == &quot;jpeg&quot;) await image.SaveAsJpegAsync(outputBlob); } } log.LogInformation($&quot;C# Blob trigger function Processed blob\n Name:{name} \n Size: {input.Length} Bytes&quot;); } } } catch (Exception ex) { log.LogInformation(ex.Message, null); } } </code></pre>
3
1,098
recvfrom() hangs when I try to get time from NTP server
<p>I'm currently figuring out why my recvfrom() doesn't return anything. I've suspected whether socket or NTP Ip address is wrong, but both seems right so far.</p> <p>The following is the code:</p> <pre><code> int sntp_client(ST_VOID) { struct sockaddr_in saddr, myaddr; struct timeval tv, tp; int sntp_fd=-1; int len; unsigned int pkt_len; fd_set readfds; ST_CHAR hostname[16]; sprintf(&amp;hostname[0], &quot;%d.%d.%d.%d&quot;, SNTP_IP.m_dsIPAddr.m_u8IP[0], SNTP_IP.m_dsIPAddr.m_u8IP[1] , SNTP_IP.m_dsIPAddr.m_u8IP[2], SNTP_IP.m_dsIPAddr.m_u8IP[3]); // sntp ip 가 0.0.0.0 즉, 설정되지 않으면 시각동기를 하지 않는다. if(!strcmp(hostname, &quot;0.0.0.0&quot;)) { printf(&quot;host ip error - 0.0.0.0\n&quot;); return -1; } // sntp 서버 ip 가져오기 if((len = strlen(hostname)) &lt;= 0) { printf(&quot;sntp : get host name error\n&quot;); return -1; } // socket 생성 bzero((char *)&amp;saddr, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_port = htons(SNTP_SPORT); saddr.sin_addr.s_addr = inet_addr(hostname); if((sntp_fd = socket(AF_INET, SOCK_DGRAM, 0)) &lt; 0) { printf(&quot;sntp make socket error\n&quot;); return(sntp_fd); } bzero((char *)&amp;myaddr, sizeof(myaddr)); myaddr.sin_family = AF_INET; myaddr.sin_port = htons(3030); myaddr.sin_addr.s_addr = INADDR_ANY; if(bind(sntp_fd, (struct sockaddr *)&amp;myaddr, sizeof(myaddr)) &lt; 0) { printf(&quot;sntp bind socket error\n&quot;); close(sntp_fd); return -1; } /* Fill in the request packet */ bzero((char *)&amp;pkt, sizeof pkt); // 서우현 박사에 의하면 client에서 txtime을 0으로 셋팅하면 sntp 규격에 어긋나므로 // IED의 현재 시간을 넣는다. gettimeofday(&amp;tp, NULL); pkt.txtime[0] = tp.tv_sec + JAN_1970; pkt.txtime[1] = tp.tv_usec * 4295; pkt.livnmode = 0x1b; /* version 1, mode 3 (client) */ // send request packet to server if((len=sendto(sntp_fd, (char *)&amp;pkt, sizeof(pkt), 0, (struct sockaddr *)&amp;saddr, sizeof(saddr))) != sizeof(pkt)) { printf(&quot;sntp service sendto() error\n&quot;); close(sntp_fd); return -1; } //read reply packet from server pkt_len = sizeof(pkt); // montavistadpsms FD_ZERO가 꼭 있어야 한다. FD_ZERO(&amp;readfds); FD_SET(sntp_fd, &amp;readfds); // FD_SET 메크로 사용 tv.tv_sec = 1; tv.tv_usec = 0; // select는 이벤트가 발생하기 전까지 block(대기) if(select(sntp_fd+1, &amp;readfds, NULL, NULL, &amp;tv)) { if((len = recvfrom(sntp_fd, (char *)&amp;pkt, sizeof(pkt), 0, (struct sockaddr *)&amp;saddr, &amp;pkt_len)) != sizeof(pkt)) { printf(&quot;sntp service recvfrom error\n&quot;); close(sntp_fd); return -1; } } else { //perror(&quot;ntp : select timeout\n&quot;); close(sntp_fd); return -1; } // diebu add - 2019.12.31. // livnmode는 leap indicator(2bit) + version number(3bit) + mode (3bit) 이다. // 여기서 leap indicator가 synchronize에 관련된다. // 정상 : 0x8A, ClockFailure : 0x4A, ClockNotSynchronize : 0x2A if((pkt.livnmode &amp; 0xC0) == 0x00) { SntpTimeQuality = SNTP_TIME_GOOD; } else { // diebu modified - 2020.05.15. : SNTP_CLOCK_NOT_SYNCHRONIZED -&gt; SNTP_CLOCK_FAILURE // 시각동기는 됬지만, synch가 맞지 않음 - clock not synchronized // GPS등과 연결이 안된 시간을 의미.. SntpTimeQuality = SNTP_CLOCK_FAILURE; } // STB는 UTC 시간 그대로 받는다. tv.tv_sec = ntohl(pkt.txtime[0]) - JAN_1970; tv.tv_usec = ntohl(pkt.txtime[1]/4295); // --&gt; usec을 만들기 위해 settimeofday(&amp;tv, NULL); if(sntp_fd &gt; 0) close(sntp_fd); return SD_TRUE; } </code></pre> <p>As you can see in the code, I'm skipping the part by calling select() function. However, I'd like to get the NTP time to synchronize.</p> <p>I'm using the following pkt struct</p> <pre><code>struct { unsigned char livnmode, stratum, poll, prec; unsigned long delay, disp, refid; unsigned long reftime[2], origtime[2], rcvtime[2], txtime[2]; }pkt; </code></pre> <p>And I'm using '203.248.240.140' as the NTP server.</p> <p>It'd be great if any network guru can help me out!!</p>
3
2,641
Select duplicate persons with duplicate memberships
<p><a href="http://sqlfiddle.com/#!18/93065/2" rel="nofollow noreferrer">SQL Fiddle</a> with schema and my intial attempt.</p> <pre><code>CREATE TABLE person ([firstname] varchar(10), [surname] varchar(10), [dob] date, [personid] int); INSERT INTO person ([firstname], [surname], [dob] ,[personid]) VALUES ('Alice', 'AA', '1/1/1990', 1), ('Alice', 'AA', '1/1/1990', 2), ('Bob' , 'BB', '1/1/1990', 3), ('Carol', 'CC', '1/1/1990', 4), ('Alice', 'AA', '1/1/1990', 5), ('Kate' , 'KK', '1/1/1990', 6), ('Kate' , 'KK', '1/1/1990', 7) ; CREATE TABLE person_membership ([personid] int, [personstatus] varchar(1), [memberid] int); INSERT INTO person_membership ([personid], [personstatus], [memberid]) VALUES (1, 'A', 10), (2, 'A', 20), (3, 'A', 30), (3, 'A', 40), (4, 'A', 50), (4, 'A', 60), (5, 'T', 70), (6, 'A', 80), (7, 'A', 90); CREATE TABLE membership ([membershipid] int, [memstatus] varchar(1)); INSERT INTO membership ([membershipid], [memstatus]) VALUES (10, 'A'), (20, 'A'), (30, 'A'), (40, 'A'), (50, 'T'), (60, 'A'), (70, 'A'), (80, 'A'), (90, 'T'); </code></pre> <p>There are three tables (as per the fiddle above). <code>Person</code> table contains duplicates, same people entered more than once, for the purpose of this exercise we assume that a combination of the first name, surname and DoB is enough to uniquely identify a person.</p> <p>I am trying to build a query which will show duplicates of people (first name+surname+Dob) with two or more active entries in the <code>Person</code> table (<code>person_membership.person_status=A</code>) AND two or more active memberships (<code>membership.mestatus=A</code>).</p> <p>Using the example from SQL Fiddle, the result of the query should be just Alice (two active person IDs, two active membership IDs). <a href="https://i.stack.imgur.com/e7jxo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e7jxo.png" alt="enter image description here"></a></p> <p>I think I'm making progress with the following effort but it looks rather cumbersome and I need to remove Katie from the final result - she doesn't have a duplicate membership.</p> <pre><code>SELECT q.firstname, q.surname, q.dob, p1.personid, m.membershipid FROM (SELECT p.firstname,p.surname,p.dob, count(*) as cnt FROM person p GROUP BY p.firstname,p.surname,p.dob HAVING COUNT(1) &gt; 1) as q INNER JOIN person p1 ON q.firstname=p1.firstname AND q.surname=p1.surname AND q.dob=p1.dob INNER JOIN person_membership pm ON p1.personid=pm.personid INNER JOIN membership m ON pm.memberid = m.membershipid WHERE pm.personstatus = 'A' AND m.memstatus = 'A' </code></pre>
3
1,100
Why do I get a BufferOverflowException when running a TensorFlowLite Model?
<p>I want to run a custom tflite model on Android using TensorFlowLite (and using Kotlin). Despite using the TFLite support library to create a supposedly correctly shaped input and output buffer I get the following error message everytime I'm calling my <code>run()</code> method.</p> <p>Here is my class:</p> <pre><code>class Inference(context: Context) { private val tag = &quot;Inference&quot; private var interpreter: Interpreter private var inputBuffer: TensorBuffer private var outputBuffer: TensorBuffer init { val mappedByteBuffer= FileUtil.loadMappedFile(context, &quot;CNN_ReLU.tflite&quot;) interpreter = Interpreter(mappedByteBuffer as ByteBuffer) interpreter.allocateTensors() val inputShape = interpreter.getInputTensor(0).shape() val outputShape = interpreter.getOutputTensor(0).shape() inputBuffer = TensorBuffer.createFixedSize(inputShape, DataType.FLOAT32) outputBuffer = TensorBuffer.createFixedSize(outputShape, DataType.FLOAT32) } fun run() { interpreter.run(inputBuffer.buffer, outputBuffer.buffer) // XXX: generates error message } } </code></pre> <p>And this is the error Message:</p> <pre><code>W/System.err: java.nio.BufferOverflowException W/System.err: at java.nio.ByteBuffer.put(ByteBuffer.java:615) W/System.err: at org.tensorflow.lite.Tensor.copyTo(Tensor.java:264) W/System.err: at org.tensorflow.lite.Tensor.copyTo(Tensor.java:254) W/System.err: at org.tensorflow.lite.NativeInterpreterWrapper.run(NativeInterpreterWrapper.java:170) W/System.err: at org.tensorflow.lite.Interpreter.runForMultipleInputsOutputs(Interpreter.java:347) W/System.err: at org.tensorflow.lite.Interpreter.run(Interpreter.java:306) </code></pre> <p>I have only initialized the input and output buffers and did not write any data to it yet.</p> <p>I'm using these gradle dependencies:</p> <pre><code>implementation 'org.tensorflow:tensorflow-lite:0.0.0-nightly' implementation 'org.tensorflow:tensorflow-lite-gpu:0.0.0-nightly' implementation 'org.tensorflow:tensorflow-lite-support:0.0.0-nightly' </code></pre> <p>The .tflite model was built with these TensorFlow versions:</p> <pre><code>tensorflow 2.3.0 tensorflow-cpu 2.2.0 tensorflow-datasets 3.1.0 tensorflow-estimator 2.3.0 tensorflow-gan 2.0.0 tensorflow-hub 0.7.0 tensorflow-metadata 0.22.0 tensorflow-probability 0.7.0 tensorflowjs 1.7.4.post1 </code></pre> <p>Any thoughts or hints are highly appreciated, thank you.</p>
3
1,103
Cant figure out joins
<p>So I am making a Businesses web app with the <code>filters</code> feature. There are two filters that I have problem with: <strong>Order By</strong> and <strong>Attributes</strong>(Has following attributes) features. Which looks like this:</p> <p>Order By</p> <ul> <li>Highest Rated (<em>radio button</em>)</li> <li>Most reviews (<em>radio button</em>)</li> </ul> <p>Attributes</p> <ul> <li>Accepts Credit Cards (<em>checkbox</em>)</li> <li>Accepts Events (<em>checkbox</em>)</li> <li>Alcohol (<em>checkbox</em>)</li> <li>Delivery (<em>checkbox</em>)</li> <li>Smoking (<em>checkbox</em>)</li> </ul> <p>So when <strong>Order By</strong> option is clicked this function is executed. Where <code>$term</code> is value of <code>order_by</code> <code>get request</code> parameter.</p> <p><strong>BusinessFilter.php</strong></p> <pre><code>public function orderby($term) { if ($term == 'reviews_count') { return $this-&gt;builder -&gt;leftJoin('reviews', 'businesses.id', '=', 'reviews.business_id') -&gt;groupBy('businesses.id') -&gt;selectRaw('businesses.*, COUNT(reviews.id) as reviews_count') -&gt;orderByDesc('reviews_count'); } else if ($term == 'rating') { return $this-&gt;builder -&gt;leftJoin('reviews', 'businesses.id', '=', 'reviews.business_id') -&gt;groupBy('businesses.id') -&gt;selectRaw('businesses.*, AVG(reviews.rating) AS average') -&gt;orderByDesc('average'); } else { return $this-&gt;builder; } } </code></pre> <p>It works ok and the result is correct.</p> <p>Now when <strong>Attribute</strong> have some <code>check boxes</code> this function is executed where <code>$term</code> is an array with set of ids.</p> <p><strong>BusinessFilter.php</strong></p> <pre><code> public function attributes($term) { $attributes= json_decode($term); if (count($attributes) == 0) { return $this-&gt;builder; } return $this-&gt;builder -&gt;select('businesses.*') -&gt;join('business_attribute_value', 'businesses.id', '=', 'business_attribute_value.business_id') -&gt;join('values', 'business_attribute_value.attribute_value_id', '=', 'values.id') -&gt;whereIn('values.id', $attributes) -&gt;groupBy('businesses.id') -&gt;havingRaw('COUNT(*) = ?', [count($attributes)]); } </code></pre> <p>the result is correct here too.</p> <p>Now the problem is when both filters have values it executes both queries together and It doesn't return the correct result. I assume it has something to do with joins. Am I doing something wrong? Please help. And if you need more info or code please let me know. Thank you, you are the best guys!</p> <p>This is how I execute filters</p> <pre><code>public function getSearch(BusinessFilter $filters) { $businesses = Business::filter($filters)-&gt;paginate(30); return $businesses; } </code></pre> <p>This is <code>QueryFilter</code> class. Basically what it does is that it goes through each request parameter and executes its function that was mentioned above.</p> <pre><code>class QueryFilters{ protected $request; protected $builder; public function __construct( Request $request ) { $this-&gt;request = $request; } public function apply(Builder $builder) { $this-&gt;builder = $builder; foreach( $this-&gt;filters() as $name =&gt; $value ){ if( !method_exists($this, $name ) ){ continue; } if(strlen($value)){ $this-&gt;$name($value); } else { $this-&gt;$name(); } } return $this-&gt;builder; } public function filters() { return $this-&gt;request-&gt;all(); } } </code></pre>
3
1,681
No mapping found for HTTP Spring MVC
<p>I'm doing a little demo with spring mvc and I have a problem when deploying the application. I'm using wildfly 10.0.0</p> <p>In don't understand what is happening</p> <p>in My web.xml </p> <pre><code>&lt;web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"&gt; &lt;display-name&gt;Archetype Created Web Application&lt;/display-name&gt; &lt;servlet&gt; &lt;servlet-name&gt;simu-cmac&lt;/servlet-name&gt; &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/spring/app-config.xml&lt;/param-value&gt; &lt;/init-param&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;simu-cmac&lt;/servlet-name&gt; &lt;url-pattern&gt;*.htm&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; </code></pre> <p></p> <p>in my app-config.xml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd"&gt; &lt;context:component-scan base-package="com.cmac.simu" /&gt; &lt;mvc:annotation-driven/&gt; </code></pre> <p></p> <p>And my Controller </p> <pre><code>@Controller public class SimuAPIController { protected final Log logger = LogFactory.getLog(getClass()); @RequestMapping("/home.htm") public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.info("Returning home view"); System.out.println("To home view"); return new ModelAndView("home.jsp"); } } </code></pre> <p>When the application is deployed the following error is displayed on the console</p> <pre><code>19:50:39,417 WARN [org.springframework.web.servlet.PageNotFound] (default task-3) No mapping found for HTTP request with URI [/simu-cmac/home.htm] in DispatcherServlet with name 'simu-cmac' </code></pre>
3
1,101
GEOS-Chem compilation error and then Segmentation fault
<pre><code>Bareword found where operator expected at -e line 1, near "2ubuntu1" (Missing operator before ubuntu1?) syntax error at -e line 1, near "2ubuntu1" Execution of -e aborted due to compilation errors. make[5]: Entering directory `/home/caecivil10/Desktop/GC_V11-01/Code.v11-01/HEMCO' Bareword found where operator expected at -e line 1, near "2ubuntu1" (Missing operator before ubuntu1?) syntax error at -e line 1, near "2ubuntu1" Execution of -e aborted due to compilation errors. make[6]: Entering directory `/home/caecivil10/Desktop/GC_V11-01/Code.v11-01/HEMCO/Core' ar crs libHCO.a hco_arr_mod.o hco_calc_mod.o hco_chartools_mod.ohco_clock_mod.o hco_config_mod.o hco_datacont_mod.o hco_diagn_mod.o hco_driver_mod.o hco_emislist_mod.o hco_error_mod.o hco_extlist_mod.o hco_filedata_mod.o hco_fluxarr_mod.o hco_geotools_mod.o hco_interp_mod.o hcoio_dataread_mod.o hcoio_diagn_mod.o hcoio_messy_mod.o hcoio_read_esmf_mod.o hcoio_read_std_mod.o hcoio_write_esmf_mod.o hcoio_write_std_mod.o hco_logfile_mod.o hco_readlist_mod.o hco_restart_mod.o hco_state_mod.o hco_tidx_mod.o hco_timeshift_mod.o hco_types_mod.o hco_unit_mod.o hco_vertgrid_mod.o messy_ncregrid_base.o messy_ncregrid_mpi.o mv libHCO.a ../../lib make[6]: Leaving directory `/home/caecivil10/Desktop/GC_V11-01/Code.v11-01/HEMCO/Core' make[5]: Leaving directory `/home/caecivil10/Desktop/GC_V11-01/Code.v11-01/HEMCO' </code></pre> <p>When ever I am running a code for compilation using make I am getting above error.</p> <p>I execute:<br> make help<br> make -j2 all MET=geosfp GRID=4x5 COMPILER=gfortran OMP=no </p> <p>then I am getting above error but the compilation is not terminated. it creates an executable but after running the executable it shows:</p> <pre><code>************* S T A R T I N G 4 x 5 G E O S--C H E M ************* Using GMAO GEOS-FP met fields ####################################### # OPENMP TURNED OFF FOR TESTING!!! # ####################################### ===&gt; SIMULATION START TIME: 2017/04/05 15:47 &lt;=== ============================================================================== = G E O S - C H E M U S E R I N P U T READ_INPUT_FILE: Reading input.geos =============================================================================== GEOS-CHEM I/O ERROR 2 in file unit 11 Encountered at routine:location read_input_file:1 =============================================================================== Program received signal SIGSEGV: Segmentation fault - invalid memory reference. Backtrace for this error: #0 0x7F84A95F9777 #1 0x7F84A95F9D7E #2 0x7F84A8D35CAF #3 0x9173FD in __hco_driver_mod_MOD_hco_final at hco_driver_mod.F90:308 #4 0x72C0AB in __hcoi_gc_main_mod_MOD_hcoi_gc_final at hcoi_gc_main_mod.F90:748 #5 0x4681AD in cleanup_ at cleanup.F:276 #6 0x999C80 in __error_mod_MOD_geos_chem_stop at error_mod.F:758 #7 0x5E5706 in __input_mod_MOD_read_input_file at input_mod.F:283 (discriminator 1) #8 0x5F6FF0 in geos_chem at main.F:486 Segmentation fault (core dumped) </code></pre>
3
1,188
Tried building a sample app where the fragments inside the Grid layout while drag and dropping would swap their place
<p>This is my Activity.xml file.</p> <pre><code> ' &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;GridLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:tools=&quot;http://schemas.android.com/tools&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; android:columnCount=&quot;2&quot; android:rowCount=&quot;2&quot; android:layout_margin=&quot;10sp&quot; tools:context=&quot;.MainActivity&quot; android:id=&quot;@+id/gridView&quot;&gt; &lt;fragment android:id=&quot;@+id/frag1&quot; android:layout_height=&quot;wrap_content&quot; android:layout_width=&quot;wrap_content&quot; android:name=&quot;com.example.drag.Fragment1&quot; android:layout_row=&quot;0&quot; android:layout_column=&quot;0&quot; android:layout_columnWeight=&quot;1&quot; android:layout_rowWeight=&quot;1&quot; android:layout_gravity=&quot;fill&quot; android:layout_margin=&quot;20sp&quot; android:background=&quot;@color/teal_200&quot; &gt; &lt;/fragment&gt; &lt;fragment android:id=&quot;@+id/frag2&quot; android:name=&quot;com.example.drag.Fragment2&quot; android:layout_height=&quot;wrap_content&quot; android:layout_width=&quot;wrap_content&quot; android:layout_row=&quot;0&quot; android:layout_column=&quot;1&quot; android:layout_gravity=&quot;fill&quot; android:background=&quot;@color/teal_200&quot; android:layout_columnWeight=&quot;1&quot; android:layout_rowWeight=&quot;1&quot; android:layout_margin=&quot;20sp&quot;&gt; &lt;/fragment&gt; &lt;fragment android:id=&quot;@+id/frag3&quot; android:name=&quot;com.example.drag.Fragment3&quot; android:layout_height=&quot;wrap_content&quot; android:layout_width=&quot;wrap_content&quot; android:layout_row=&quot;1&quot; android:layout_column=&quot;0&quot; android:layout_gravity=&quot;fill&quot; android:background=&quot;@color/teal_200&quot; android:layout_columnWeight=&quot;1&quot; android:layout_rowWeight=&quot;1&quot; android:layout_margin=&quot;20sp&quot;&gt; &lt;/fragment&gt; &lt;fragment android:id=&quot;@+id/frag4&quot; android:name=&quot;com.example.drag.Fragment4&quot; android:layout_height=&quot;wrap_content&quot; android:layout_width=&quot;wrap_content&quot; android:layout_row=&quot;1&quot; android:layout_column=&quot;1&quot; android:layout_gravity=&quot;fill&quot; android:background=&quot;@color/teal_200&quot; android:layout_columnWeight=&quot;1&quot; android:layout_rowWeight=&quot;1&quot; android:layout_margin=&quot;20sp&quot;&gt; &lt;/fragment&gt; &lt;/GridLayout&gt;' </code></pre> <p>This is my MainActivity.java file</p> <pre><code> `package com.example.drag; import androidx.appcompat.app.AppCompatActivity; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.fragment.app.Fragment; import android.app.Activity; import android.app.FragmentTransaction; import android.content.ClipData; import android.content.ClipDescription; import android.graphics.Color; import android.icu.text.Transliterator; import android.os.Bundle; import android.view.DragEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.GridLayout; import android.widget.GridView; import android.widget.LinearLayout; import java.util.ArrayList; public class MainActivity extends AppCompatActivity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); (findViewById(R.id.frag1)).setOnDragListener(new MyDragListener()); (findViewById(R.id.frag2)).setOnDragListener(new MyDragListener()); (findViewById(R.id.frag3)).setOnDragListener(new MyDragListener()); (findViewById(R.id.frag4)).setOnDragListener(new MyDragListener()); MyDragListener myDragListener = null; myDragListener = new MyDragListener(); (findViewById(R.id.frag1)).setOnDragListener(myDragListener); (findViewById(R.id.frag2)).setOnDragListener(myDragListener); (findViewById(R.id.frag3)).setOnDragListener(myDragListener); (findViewById(R.id.frag4)).setOnDragListener(myDragListener); (findViewById(R.id.frag1)).setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { ClipData.Item item = new ClipData.Item((CharSequence) v.getTag()); ClipData dragData = new ClipData( (CharSequence) v.getTag(), new String[]{ClipDescription.MIMETYPE_TEXT_PLAIN}, item); View.DragShadowBuilder myShadow = new MyDragShadowBuilder((findViewById(R.id.frag1))); v.startDrag(dragData, myShadow, v, 0); return true; } }); (findViewById(R.id.frag2)).setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { ClipData.Item item = new ClipData.Item((CharSequence) v.getTag()); ClipData dragData = new ClipData( (CharSequence) v.getTag(), new String[]{ClipDescription.MIMETYPE_TEXT_PLAIN}, item); View.DragShadowBuilder myShadow = new MyDragShadowBuilder((findViewById(R.id.frag2))); v.startDrag(dragData, myShadow,v, 0); return true; } }); (findViewById(R.id.frag3)).setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { ClipData.Item item = new ClipData.Item((CharSequence) v.getTag()); ClipData dragData = new ClipData( (CharSequence) v.getTag(), new String[]{ClipDescription.MIMETYPE_TEXT_PLAIN}, item); View.DragShadowBuilder myShadow = new MyDragShadowBuilder((findViewById(R.id.frag3))); v.startDrag(dragData, myShadow, v, 0); return true; } }); (findViewById(R.id.frag4)).setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { ClipData.Item item = new ClipData.Item((CharSequence) v.getTag()); ClipData dragData = new ClipData( (CharSequence) v.getTag(), new String[]{ClipDescription.MIMETYPE_TEXT_PLAIN}, item); View.DragShadowBuilder myShadow = new MyDragShadowBuilder((findViewById(R.id.frag4))); v.startDrag(dragData, myShadow, v, 0); return true; } }); } class MyDragListener implements View.OnDragListener{ @Override public boolean onDrag(View v, DragEvent event) { final int action = event.getAction(); final FragmentTransaction ft = getFragmentManager().beginTransaction(); switch (action){ case DragEvent.ACTION_DRAG_STARTED: if(event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)){ v.setBackgroundColor(Color.BLUE); return true; } return false; case DragEvent.ACTION_DRAG_ENTERED: v.setBackgroundColor(Color.GREEN); return true; case DragEvent.ACTION_DRAG_LOCATION: return true; case DragEvent.ACTION_DRAG_EXITED: v.setBackgroundColor(Color.BLUE); return true; case DragEvent.ACTION_DROP: ClipData.Item item = event.getClipData().getItemAt(0); CharSequence dragData = item.getText(); View view = (View) event.getLocalState(); ViewGroup owner = (ViewGroup) view.getParent(); owner.removeView(view); LinearLayout container1 = (LinearLayout) v; view.setVisibility(View.VISIBLE); break; case DragEvent.ACTION_DRAG_ENDED: return true; } return false; } } }` </code></pre> <p>Each fragments xml like this</p> <pre><code> `&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot; xmlns:tools=&quot;http://schemas.android.com/tools&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; android:background=&quot;@color/purple_200&quot; tools:context=&quot;.Fragment1&quot; &gt; &lt;TextView android:id=&quot;@+id/firstFragment&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_centerInParent=&quot;true&quot; android:text=&quot;Slide 1&quot; android:textSize=&quot;30dp&quot; app:layout_constraintBottom_toBottomOf=&quot;parent&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toTopOf=&quot;parent&quot;&gt; &lt;/TextView&gt; &lt;/LinearLayout&gt;` </code></pre> <p>When i tried to run it and start my dragging of fragments. the fragments start adding in the size of container rather than swapping between them. it supposedly work like when i drag one fragment and drop it to the other fragments. the fragments should swap their places.</p>
3
5,046
background-repeat: no-repeat; is not working
<p>Restricting the height of the body to 100% of the screen height you will see background-repeat: no-repeat; not working.</p> <p>How is, or would this be fixed in the code? <a href="https://jsfiddle.net/z3gq0y5x/" rel="nofollow noreferrer">https://jsfiddle.net/z3gq0y5x/</a></p> <p>Why is the background still repeating?</p> <p>How would that be fixed in the code?</p> <p>I am using <code>background-repeat: no-repeat;</code> yet that is not working in the code.</p> <pre><code>html, body { height: 100%; margin: 0; padding: 0; } body::before { content: &quot;&quot;; background-repeat: no-repeat; position: fixed; z-index: -1; left: 0; right: 0; top: 0; bottom: 0; } .bg1 { background-image: linear-gradient(45deg, #102eff, #d2379b); } .bg2 { background-image: linear-gradient(45deg, #102eff, #d2379b); } .bg3 { background-image: linear-gradient(45deg, #102eff, #d2379b); } </code></pre> <p><a href="https://i.stack.imgur.com/Te2rB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Te2rB.png" alt="enter image description here" /></a></p> <p>It can also be seen in the snippet I provided.</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>(function randomBackground() { const classNames = [ "bg1", "bg2", "bg3" ]; const random = Math.floor(Math.random() * classNames.length); document.querySelector("body").classList.add(classNames[random]); }()); const videoPlayer = (function makeVideoPlayer() { const config = {}; let player = null; const tag = document.createElement("script"); tag.src = "https://www.youtube.com/iframe_api"; const firstScriptTag = document.getElementsByTagName("script")[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); function onYouTubeIframeAPIReady() { const frameContainer = document.querySelector(".video"); videoPlayer.addPlayer(frameContainer, config.playlist); } function shufflePlaylist(player) { player.setShuffle(true); player.playVideoAt(0); player.stopVideo(); } function onPlayerReady(event) { player = event.target; player.setVolume(100); // percent shufflePlaylist(player); } function addPlayer(video, playlist) { const config = { height: 360, host: "https://www.youtube-nocookie.com", width: 640 }; config.playerVars = { autoplay: 0, cc_load_policy: 0, controls: 1, disablekb: 1, fs: 0, iv_load_policy: 3, loop: 1, playlist, rel: 0 }; config.events = { "onReady": onPlayerReady }; player = new YT.Player(video, config); } function init(videos) { config.playlist = videos.join(); window.onYouTubeIframeAPIReady = onYouTubeIframeAPIReady; } return { addPlayer, init }; }()); videoPlayer.init([ "CHahce95B1g", "CHahce95B1g", "CHahce95B1g", "CHahce95B1g" ]);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>html, body { height: 100%; margin: 0; padding: 0; } body::before { content: ""; background-repeat: no-repeat; position: fixed; z-index: -1; left: 0; right: 0; top: 0; bottom: 0; } .bg1 { background-image: linear-gradient(45deg, #102eff, #d2379b); } .bg2 { background-image: linear-gradient(45deg, #102eff, #d2379b); } .bg3 { background-image: linear-gradient(45deg, #102eff, #d2379b); } .outer { display: table; height: 100%; margin: 0 auto; width: 100%; } .tcell { display: table-cell; vertical-align: middle; padding: 8px 8px; } .video-wrapper { position: relative; margin: auto; max-width: 640px; } .ratio-keeper { position: relative; height: 0; padding-top: 56.25%; margin: auto; } .video-frame { position: absolute; top: 0; left: 0; width: 100%; height: 100%; animation: fade 10s ease-in 0s forwards; } @keyframes fade { 0% { opacity: 0; } 100% { opacity: 1; } } iframe { user-select: none; } .hide { display: none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="outer"&gt; &lt;div class="tcell"&gt; &lt;div class="video-wrapper"&gt; &lt;div class="ratio-keeper"&gt; &lt;div class="video video-frame"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><a href="https://i.stack.imgur.com/W57de.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/W57de.png" alt="enter image description here" /></a></p> <p><strong>The answer below gives me this:</strong></p> <p><a href="https://i.stack.imgur.com/J1oA8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J1oA8.png" alt="enter image description here" /></a></p> <p>2nd updated answer provided:</p> <p>The updated answer causes the video to no-longer be centered in the middle.</p> <p>The video was originally centered in the middle in the question I posted.</p> <p>The answer that was provided messed that up.</p> <p><strong>Seen Here:</strong> <a href="https://i.stack.imgur.com/03xRH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/03xRH.png" alt="enter image description here" /></a></p>
3
2,140
How to make WorkManager.cancel() immediate?
<p>I have duplicated data backednd side due to the fact that WorkManager.cancel() isn't immediate.</p> <p>I tried to maked the cancellation immediate by making it a Single. but it doesn't work.</p> <pre><code>private fun cancelSendEventsWorkManager(): Single&lt;Boolean&gt; = Single.fromCallable { WorkManager.getInstance(requireContext()).getWorkInfosByTag(SendEventstWorker.TAG).cancel(true) }.subscribeOn(Schedulers.io()) </code></pre> <p>and use it like this on a <em>click button event</em> :</p> <pre><code>Single.concat( cancelSendEventsWorkManager(), eventsViewModel.reportAllEvents(), eventsViewModel.saveReportCompleted(), .subscribeOn(Schedulers.io()) .doOnSubscribe { EventBus.post(ShowProgress(getString(R.string.common_dialog_progress_generic))) } .doOnError { EventBus.post(DismissProgress()) listener?.showUnknownErrorDialog() } .doOnComplete { onReportAllEventAndCloseSessionSuccess(userName) } .subscribe( { }, { onReportAllEventAndCloseSessionSuccess(userName) } }) </code></pre> <p><strong>SendEventstWorker</strong></p> <pre><code>class SendEventstWorker constructor(context: Context, workerParameters: WorkerParameters) : RxWorker(context, workerParameters) { private val db: RpxDatabase = RpxDatabase.getInstance(context) private val eventRepository: EventRepository init { eventRepository = db.eventRepository } override fun createWork(): Single&lt;Result&gt; { // Get the input val userId = inputData.getString(KEY_USER_ID) return eventsRepository .getAllventsByUserId(userId) .flattenAsObservable { Log.d(TAG, it.size.toString()) it } .concatMapSingle { val event = it val mapper = ObjectMapper() val typeRef: TypeReference&lt;HashMap&lt;String, Any&gt;&gt; = object : TypeReference&lt;HashMap&lt;String, Any&gt;&gt;() {} val map: Map&lt;String, Any&gt; = mapper.readValue(Event.data, typeRef) reportingApi.reportEvent(e.eventventType.getValue(), event.id, event.eventCreateDate, event.bId, event.bHash, map) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.io()) .doOnSuccess { deleteEvent(event) } .doOnError { } } .toList() //.subscribeOn(Schedulers.io()) .map { Result.retry() } .onErrorReturn { Result.retry() } } private fun deleteEvent(event: Event) { Single.fromCallable { eventRepository.deleteEvent(event) } .subscribeOn(Schedulers.io()) .subscribe() } } </code></pre> <p>Is there any way to acheive the immediate cancelation properly ?</p>
3
1,950
can't verify selected checkbox, Selenium Webdriver Java
<p>In my test I want to verify selected checkbox. Below is my code</p> <pre><code>if (CheckboxForFirstCitizenship.isSelected()) { System.out.println("Checkbox selected"); } else { System.out.println("Checkbox not selected"); } if (CheckboxForSecondCitizenship.isSelected()) { System.out.println("Checkbox selected"); } else { System.out.println("Checkbox not selected"); } </code></pre> <p>Web elements I have in PageObjects class</p> <pre><code>@FindBy(xpath = "/html[1]/body[1]/ufe-root[1]/div[1]/div[1]/div[1]/ng-component[1]/div[1]/ufe-klient[1]/app-dashboard[1]/main[1]/div[1]/div[2]/app-individual-client-edit-container[1]/app-process-container[1]/app-local-loader[1]/div[1]/div[3]/app-individual-client-edit-client-data[1]/app-form-container[1]/p-accordion[1]/div[1]/p-accordiontab[1]/div[2]/div[1]/div[2]/div[1]/app-form-data-set-container[1]/div[1]/div[1]/app-individual-client-edit-personal-data-form[1]/app-data-container[1]/div[1]/div[2]/app-container-state[1]/div[1]/form[1]/div[1]/div[8]/div[1]/div[1]/app-individual-client-edit-citizenship-form[1]/div[2]/p-checkbox[1]/div[1]/div[2]") @CacheLookup public WebElement CheckboxForFirstCitizenship; @FindBy(xpath = "/html[1]/body[1]/ufe-root[1]/div[1]/div[1]/div[1]/ng-component[1]/div[1]/ufe-klient[1]/app-dashboard[1]/main[1]/div[1]/div[2]/app-individual-client-edit-container[1]/app-process-container[1]/app-local-loader[1]/div[1]/div[3]/app-individual-client-edit-client-data[1]/app-form-container[1]/p-accordion[1]/div[1]/p-accordiontab[1]/div[2]/div[1]/div[2]/div[1]/app-form-data-set-container[1]/div[1]/div[1]/app-individual-client-edit-personal-data-form[1]/app-data-container[1]/div[1]/div[2]/app-container-state[1]/div[1]/form[1]/div[1]/div[8]/div[1]/div[2]/app-individual-client-edit-citizenship-form[1]/div[2]/p-checkbox[1]/label[1]") @CacheLookup public WebElement CheckboxForSecondCitizenship; </code></pre> <p><a href="https://i.stack.imgur.com/C4KBF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C4KBF.png" alt="enter image description here"></a></p> <p>In test result I have two printlines 'Checkbox not selected' despite of firstCheckox is selected. What I'm doing wrong? Can someone help?</p> <pre><code>&lt;p-checkbox _ngcontent-c26="" binary="true" class="control__hint ng-untouched ng-pristine ng-valid ng-star-inserted" label="Główne" id="main-citizenship-checkbox-0" style="" xpath="1"&gt; &lt;div class="ui-chkbox ui-widget"&gt; &lt;div class="ui-helper-hidden-accessible"&gt; &lt;input type="checkbox" name="undefined" value="undefined"&gt; &lt;/div&gt; &lt;div class="ui-chkbox-box ui-widget ui-corner-all ui-state-default ui-state-active"&gt;&lt;span class="ui-chkbox-icon ui-clickable pi pi-check"&gt;&lt;/span&gt;&lt;/div&gt; &lt;/div&gt; &lt;!----&gt; &lt;label class="ui-chkbox-label ui-label-active ng-star-inserted"&gt;Główne&lt;/label&gt; &lt;/p-checkbox&gt; </code></pre>
3
1,363
Swift Audio Playback speed
<p>I am developing a game where the main sprite is a spinning wheel. I would like to associate audio to the spinning wheel that changes pitch as the wheel slows down. When the wheel stops spinning I would like the sound effect to stop. Can someone point me in the right direction?</p> <p>In my game scene I have the following code:</p> <pre><code>override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) { for touch in touches { let location = touch.location(in: self) //Start spinning the wheel if atPoint(location).name == "play_button" { player?.physicsBody?.angularVelocity = 0 player?.rotatePlayer() //Click back button } else if atPoint(location).name == "back_button" { let play_scene = CharacterSelectScene(fileNamed: "CharacterSelect") play_scene?.scaleMode = .aspectFill self.view?.presentScene(play_scene!, transition: SKTransition.doorsOpenVertical(withDuration: 1)) } else if atPoint(location).name == "settings_button" { let play_scene = SettingsScene(fileNamed: "SettingsScene") play_scene?.scaleMode = .aspectFill self.view?.presentScene(play_scene!, transition: SKTransition.doorsOpenVertical(withDuration: 1)) } } } override func didSimulatePhysics() { let speed = player?.physicsBody?.angularVelocity if (speed != CGFloat(0.0)) { if (speed! &lt;= CGFloat(0.1)){ finishedRotation = true } } } override func didFinishUpdate() { if (finishedRotation == true) { let play_scene = QuestionScene(fileNamed: "QuestionScene") play_scene?.scaleMode = .aspectFill self.view?.presentScene(play_scene!, transition: SKTransition.doorsOpenVertical(withDuration: 1)) } } func didBegin(_ contact: SKPhysicsContact) { let defaults = UserDefaults.standard var firstBody = SKPhysicsBody() var secondBody = SKPhysicsBody() if (contact.bodyA.node?.name == "pin") { firstBody = contact.bodyA secondBody = contact.bodyB } else { firstBody = contact.bodyB secondBody = contact.bodyA } if (firstBody.node?.name == "pin" &amp;&amp; secondBody.node?.name == "geography") { let set_topic = secondBody.node?.name defaults.set(set_topic, forKey: "Topic") } else if (firstBody.node?.name == "pin" &amp;&amp; secondBody.node?.name == "maths") { let set_topic = secondBody.node?.name defaults.set(set_topic, forKey: "Topic") } else if (firstBody.node?.name == "pin" &amp;&amp; secondBody.node?.name == "history") { let set_topic = secondBody.node?.name defaults.set(set_topic, forKey: "Topic") } else if (firstBody.node?.name == "pin" &amp;&amp; secondBody.node?.name == "science") { let set_topic = secondBody.node?.name defaults.set(set_topic, forKey: "Topic") } } </code></pre> <p>The rotatePlayer method from the Player class is defined as below:</p> <pre><code>func rotatePlayer() { let random = GKRandomDistribution(lowestValue: 20, highestValue: 120) let r = random.nextInt() self.physicsBody?.angularVelocity = 0 self.physicsBody?.angularVelocity = CGFloat(r) self.physicsBody?.angularDamping = 1.02 } </code></pre>
3
1,314
Is there a way to avoid documentation duplication when documenting setters/getters, properties and constructors in JavaDoc?
<p>I really like well documented code. But there are lots of duplications in the documentation, since the basic information and examples should be available for the properties, the setters/getters and in constructors (also see <a href="https://stackoverflow.com/questions/1028967/simple-getter-setter-comments">Simple Getter/Setter comments</a>).</p> <p>Is there a way to avoid duplication of JavaDocs? The only idea I had is using <code>{@link #function()}</code> and link to a part in the JavaDocs that contains more information.</p> <p>Here is an imaginary example:</p> <pre><code>package com.stackoverflow.tests; /** * An Event ... */ public class Event { /** * The date the event takes place. * Needs to be in &lt;a href="https://en.wikipedia.org/wiki/ISO_8601"&gt;ISO 8601&lt;/a&gt; format. * * &lt;h2&gt;Examples:&lt;/h2&gt; * &lt;ul&gt; * &lt;li&gt;{@code 2016-03-19}&lt;/li&gt; * &lt;li&gt;{@code 2016-03-19T05:54:01+00:00}&lt;/li&gt; * &lt;li&gt;{@code 2016-W11} - i.e. week 11 of 2016&lt;/li&gt; * &lt;/ul&gt; */ private String date; /** * Creates an event initializing it with the date and location the event takes place. * @param date * Date in &lt;a href="https://en.wikipedia.org/wiki/ISO_8601"&gt;ISO 8601&lt;/a&gt; format. Examples: * &lt;ul&gt; * &lt;li&gt;{@code 2016-03-19}&lt;/li&gt; * &lt;li&gt;{@code 2016-03-19T05:54:01+00:00}&lt;/li&gt; * &lt;li&gt;{@code 2016-W11} - i.e. week 11 of 2016&lt;/li&gt; * &lt;/ul&gt; * @param location * Location ... */ public Event(final String date, final String location) { this.date = date; } /** * The date the event takes place. * @return * Date in &lt;a href="https://en.wikipedia.org/wiki/ISO_8601"&gt;ISO 8601&lt;/a&gt; format. */ public String getDate() { return date; } /** * Updates the date the event takes place using an ISO 8601 formatted String. * @param date * Date in &lt;a href="https://en.wikipedia.org/wiki/ISO_8601"&gt;ISO 8601&lt;/a&gt; format. Examples: * &lt;ul&gt; * &lt;li&gt;{@code 2016-03-19}&lt;/li&gt; * &lt;li&gt;{@code 2016-03-19T05:54:01+00:00}&lt;/li&gt; * &lt;li&gt;{@code 2016-W11} - i.e. week 11 of 2016&lt;/li&gt; * &lt;/ul&gt; */ public void setDate(String date) { this.date = date; } } </code></pre>
3
1,047
How can I display the data from a foreign table in a table cell using django-tables2 (custom table)?
<p>The value on the table cell is empty. This column contains the data from foreign table.</p> <p>Here is the snippet of my models.</p> <p>model.py</p> <pre><code>class DailyRecord(models.Model): date_organised = models.DateField('Ogransied Date', help_text=('Enter Date when the program is organised: CCYY-MM-DD')) program_name = models.TextField('program name',) venue = models.CharField('venue', max_length = 255, blank=True) organiser = models.ForeignKey(Organiser, verbose_name = 'Organiser', related_name = 'organisers') objects = models.Manager() public = DailyRecordManager() class Meta: verbose_name = 'dailyrecord' verbose_name_plural = 'dailyrecords' ordering = ['-date_organised'] def __str__(self): return self.program_name.encode('ascii', errors='replace') class Participant(models.Model): participant = models.CharField(max_length= 50) daily_record = models.ForeignKey(DailyRecord, verbose_name = 'program_name', related_name = 'participant_set') class Meta: verbose_name = 'participant' verbose_name_plural = 'participants' def __str__(self): return self.participant.encode('ascii', errors='replace') </code></pre> <p>This is class on table to display custom table. below is the snippet</p> <p>tables.py</p> <pre><code>class DailyRecordTable(tables.Table): date_organised = tables.Column('Date') program_name = tables.Column( 'Program Name') venue = tables.Column('Venue') organiser = tables.Column( 'Organiser') participant = tables.Column(accessor='participant.participant') class Meta: model = DailyRecord </code></pre> <p>This is my Generic Views for displaying table.</p> <p>views.py</p> <pre><code>class DailyActivityPageView(SingleTableView): queryset = DailyRecord.public.prefetch_related('participant_set').all() table = DailyRecordTable(queryset) template_name = 'dailyrecord/daily-activity-record.html' def get(self, request): RequestConfig(request).configure(self.table) return render(request, self.template_name, {'table': self.table, 'ziptable':self.ziptable,'data' : self.data}) </code></pre> <p>data.html</p> <pre><code>&lt;tbody&gt; {% for row in table.page.object.list|default:table.rows %} {# support pagination #} {% block table.tbody.row %} &lt;tr {{ row.attrs.as_html }}&gt; {% for column, cell in row.items %} &lt;td {{ column.attrs.td.as_html }}&gt; {{cell}} {% if column.localize == None %} {% if column.header == 'Participant' %} {{cell}} {% for item in cell.participant_set.all %} {{item.participant}} {% endfor %} {% else %} {{ cell}} {% endif %} {% else %} {% if column.localize %} {{ cell|localize }} {% else %} {{cell|unlocalize}} {% endif %} {% endif %} &lt;/td&gt; {% endfor %} &lt;/tr&gt; {% endblock table.tbody.row %} {% empty %} {% if table.empty_text %} {% block table.tbody.empty_text %} {% endblock table.tbody.empty_text %} {% endif %} {% endfor %} &lt;/tbody&gt; </code></pre> <p>Output <a href="https://i.stack.imgur.com/o7vqw.jpg" rel="nofollow noreferrer">screenshot</a> </p> <p>The participant column is empty. Why?</p>
3
1,456
Download PDF Files - Socket Error
<p>I have a little problem, I have this method to download files in two formats (. Txt and. PDF). </p> <p>For files in. Txt'm not having problems. </p> <p>But for PDF files when I cancel download or when he opens the download window and I make no action, the code is giving this exception: </p> <p>For Time waiting a user action:</p> <pre><code>java.net.SocketException: Socket closed at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:99) at java.net.SocketOutputStream.write(SocketOutputStream.java:137) at weblogic.servlet.internal.ChunkOutput.writeChunkTransfer(ChunkOutput.java:578) at weblogic.servlet.internal.ChunkOutput.writeChunks(ChunkOutput.java:548) at weblogic.servlet.internal.ChunkOutput.flush(ChunkOutput.java:436) at weblogic.servlet.internal.ChunkOutput$2.checkForFlush(ChunkOutput.java:657) at weblogic.servlet.internal.ChunkOutput.write(ChunkOutput.java:342) at weblogic.servlet.internal.ChunkOutputWrapper.write(ChunkOutputWrapper.java:148) at weblogic.servlet.internal.ServletOutputStreamImpl.write(ServletOutputStreamImpl.java:151) at java.io.OutputStream.write(OutputStream.java:59) at FIRST.handlers.FRC.downloadFile(FRC.java:752) at FIRST.handlers.FRC.handleDownloadPDFItem(FRC.java:638) at FIRST.handlers.FRC.handleRequest(FRC.java:368) at FIRST.FIRSTApplication.serviceRequest(FIRSTApplication.java:47) at FIRST.FIRSTONLINE.service(FIRSTONLINE.java:265) at javax.servlet.http.HttpServlet.service(HttpServlet.java:845) at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:242) at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:216) at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:132) at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:352) at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:236) at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3284) at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3254) at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321) at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120) at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57) at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2163) at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2091) at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2074) at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1512) at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:255) at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256) at weblogic.work.ExecuteThread.run(ExecuteThread.java:221) </code></pre> <p>And this when the user cancel the download file:</p> <pre><code>java.net.SocketException: socket write error: Connection reset by peer. at jrockit.net.SocketNativeIO.writeBytesPinned(Native Method) at jrockit.net.SocketNativeIO.socketWrite(SocketNativeIO.java:46) at java.net.SocketOutputStream.socketWrite0(SocketOutputStream.java) at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92) at java.net.SocketOutputStream.write(SocketOutputStream.java:136) at weblogic.servlet.internal.ChunkOutput.writeChunkTransfer(ChunkOutput.java:577) at weblogic.servlet.internal.ChunkOutput.writeChunks(ChunkOutput.java:548) at weblogic.servlet.internal.ChunkOutput.flush(ChunkOutput.java:436) at weblogic.servlet.internal.ChunkOutput$2.checkForFlush(ChunkOutput.java:657) at weblogic.servlet.internal.ChunkOutput.write(ChunkOutput.java:342) at weblogic.servlet.internal.ChunkOutputWrapper.write(ChunkOutputWrapper.java:148) at weblogic.servlet.internal.ServletOutputStreamImpl.write(ServletOutputStreamImpl.java:151) at java.io.OutputStream.write(OutputStream.java:58) at FIRST.handlers.FRC.downloadFile(FRC.java:752) at FIRST.handlers.FRC.handleDownloadPDFItem(FRC.java:638) at FIRST.handlers.FRC.handleRequest(FRC.java:368) at FIRST.FIRSTApplication.serviceRequest(FIRSTApplication.java:47) at FIRST.FIRSTONLINE.service(FIRSTONLINE.java:265) at javax.servlet.http.HttpServlet.service(HttpServlet.java:844) at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:242) at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:216) at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:132) at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:352) at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:235) at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3284) at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3254) at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321) at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120) at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57) at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2163) at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2089) at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2074) at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1512) at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:254) at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256) at weblogic.work.ExecuteThread.run(ExecuteThread.java:221) </code></pre> <p>This is my method: </p> <pre><code>private String downloadFile(String fileName, String name, String format) { String result = null; HttpServletResponse response = getHttpServletResponse(); if (response != null) { if (format != null &amp;&amp; format.contains(PDF_EXTENSION.getExtension())) { response.setContentType("application/pdf"); } else { response.setContentType("application/text"); } response.addHeader("Content-disposition", "attachment; filename=" + name); FileInputStream fs = null; try { OutputStream os = response.getOutputStream(); fs = new FileInputStream(fileName); byte[] b = new byte[8192]; byte[] crlf = { 0x0d, 0x0a }; int size = 0; while ((size = fs.read(b)) != -1) { if (format == null) { for (int i = 0; i &lt; size; i++) { if (b[i] == 0x0a) { os.write(crlf); } else { os.write(b, i, 1); } } } else { os.write(b); } } out.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (fs != null) { fs.close(); } if(isPDFFile(fileName)) { deletePDFFileTemporary(fileName); } } catch (Exception e1) { e1.printStackTrace(); } } result = "application/text"; } return result; } </code></pre> <p>Have appreciate the help. thank you</p>
3
3,013
Spark submit hangs after writing from Cassandra to json
<p>I have a driver program where I write read data in from Cassandra using spark, perform some operations, and then write out to JSON on S3. The program runs fine when I use Spark 1.6.1 and the spark-cassandra-connector 1.6.0-M1.</p> <p>However, if I try to upgrade to Spark 2.0.1 (hadoop 2.7.1) and spark-cassandra-connector 2.0.0-M3, the program completes in the sense that all the expected files are written to S3, but the program never terminates.</p> <p>I do run <code>sc.stop()</code> at the end of the program. I am also using Mesos 1.0.1. In both cases I use the default output committer.</p> <p>Edit: Looking at the thread dump below, it seems like it could be waiting on: <code>org.apache.hadoop.fs.FileSystem$Statistics$StatisticsDataReferenceCleaner</code></p> <p>Code snippet:</p> <pre><code>// get MongoDB oplog operations val operations = sc.cassandraTable[JsonOperation](keyspace, namespace) .where("ts &gt;= ? AND ts &lt; ?", minTimestamp, maxTimestamp) // replay oplog operations into documents val documents = operations .spanBy(op =&gt; op.id) .map { case (id: String, ops: Iterable[T]) =&gt; (id, apply(ops)) } .filter { case (id, result) =&gt; result.isInstanceOf[Document] } .map { case (id, document) =&gt; MergedDocument(id = id, document = document .asInstanceOf[Document]) } // write documents to json on s3 documents .map(document =&gt; document.toJson) .coalesce(partitions) .saveAsTextFile(path, classOf[GzipCodec]) sc.stop() </code></pre> <p>Thread dump on the driver:</p> <pre><code> 60 context-cleaner-periodic-gc TIMED_WAITING 46 dag-scheduler-event-loop WAITING 4389 DestroyJavaVM RUNNABLE 12 dispatcher-event-loop-0 WAITING 13 dispatcher-event-loop-1 WAITING 14 dispatcher-event-loop-2 WAITING 15 dispatcher-event-loop-3 WAITING 47 driver-revive-thread TIMED_WAITING 3 Finalizer WAITING 82 ForkJoinPool-1-worker-17 WAITING 43 heartbeat-receiver-event-loop-thread TIMED_WAITING 93 java-sdk-http-connection-reaper TIMED_WAITING 4387 java-sdk-progress-listener-callback-thread WAITING 25 map-output-dispatcher-0 WAITING 26 map-output-dispatcher-1 WAITING 27 map-output-dispatcher-2 WAITING 28 map-output-dispatcher-3 WAITING 29 map-output-dispatcher-4 WAITING 30 map-output-dispatcher-5 WAITING 31 map-output-dispatcher-6 WAITING 32 map-output-dispatcher-7 WAITING 48 MesosCoarseGrainedSchedulerBackend-mesos-driver RUNNABLE 44 netty-rpc-env-timeout TIMED_WAITING 92 org.apache.hadoop.fs.FileSystem$Statistics$StatisticsDataReferenceCleaner WAITING 62 pool-19-thread-1 TIMED_WAITING 2 Reference Handler WAITING 61 Scheduler-1112394071 TIMED_WAITING 20 shuffle-server-0 RUNNABLE 55 shuffle-server-0 RUNNABLE 21 shuffle-server-1 RUNNABLE 56 shuffle-server-1 RUNNABLE 22 shuffle-server-2 RUNNABLE 57 shuffle-server-2 RUNNABLE 23 shuffle-server-3 RUNNABLE 58 shuffle-server-3 RUNNABLE 4 Signal Dispatcher RUNNABLE 59 Spark Context Cleaner TIMED_WAITING 9 SparkListenerBus WAITING 35 SparkUI-35-selector-ServerConnectorManager@651d3734/0 RUNNABLE 36 SparkUI-36-acceptor-0@467924cb-ServerConnector@3b5eaf92{HTTP/1.1}{0.0.0.0:4040} RUNNABLE 37 SparkUI-37-selector-ServerConnectorManager@651d3734/1 RUNNABLE 38 SparkUI-38 TIMED_WAITING 39 SparkUI-39 TIMED_WAITING 40 SparkUI-40 TIMED_WAITING 41 SparkUI-41 RUNNABLE 42 SparkUI-42 TIMED_WAITING 438 task-result-getter-0 WAITING 450 task-result-getter-1 WAITING 489 task-result-getter-2 WAITING 492 task-result-getter-3 WAITING 75 threadDeathWatcher-2-1 TIMED_WAITING 45 Timer-0 WAITING </code></pre> <p>Thread dump on the executors. It's the same on all of them:</p> <pre><code>24 dispatcher-event-loop-0 WAITING 25 dispatcher-event-loop-1 WAITING 26 dispatcher-event-loop-2 RUNNABLE 27 dispatcher-event-loop-3 WAITING 39 driver-heartbeater TIMED_WAITING 3 Finalizer WAITING 58 java-sdk-http-connection-reaper TIMED_WAITING 75 java-sdk-progress-listener-callback-thread WAITING 1 main TIMED_WAITING 33 netty-rpc-env-timeout TIMED_WAITING 55 org.apache.hadoop.fs.FileSystem$Statistics$StatisticsDataReferenceCleaner WAITING 59 pool-17-thread-1 TIMED_WAITING 2 Reference Handler WAITING 28 shuffle-client-0 RUNNABLE 35 shuffle-client-0 RUNNABLE 41 shuffle-client-0 RUNNABLE 37 shuffle-server-0 RUNNABLE 5 Signal Dispatcher RUNNABLE 23 threadDeathWatcher-2-1 TIMED_WAITING </code></pre>
3
1,743
Python - Update XML row in SqlServer (TypeError: 'type' object has no attribute '__getitem__')
<p>I've been saving xml in a <strong>SQLServer</strong> database from python like this:</p> <pre><code>import pypyodbc as pyodbc import urllib from xml.dom.minidom import Document doc = Document() base = doc.createElement('PERSONA') doc.appendChild(base) entry = doc.createElement('INFORMACION') base.appendChild(entry) nombre = doc.createElement('NOMBRE') contenidoNombre = doc.createTextNode('Jack') nombre.appendChild(contenidoNombre) entry.appendChild(nombre) apellido = doc.createElement('APELLIDO') contenidoApellido = doc.createTextNode('Black') apellido.appendChild(contenidoApellido) entry.appendChild(apellido) print doc.toxml() cnxn = pyodbc.connect( 'Trusted_Connection=yes;DRIVER={SQL Server};SERVER=localhost;DATABASE=HOLA;UID=sa;PWD=CPTZ@VPN-2011' ) idPerson = 2 cursor = cnxn.cursor() cursor.execute("INSERT INTO prueba VALUES (?, ?)", (idPerson, doc.toxml())) cnxn.commit() print("XML Guardado"); </code></pre> <p>And this is the script for the database:</p> <pre><code>USE [HOLA] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[prueba]( [id] [int] NOT NULL, [xml] [xml] NULL, CONSTRAINT [PK_prueba] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO </code></pre> <p><a href="https://i.stack.imgur.com/OYdEW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OYdEW.png" alt="enter image description here"></a></p> <p>Now, I want to update the <em>XML</em> field from <strong>Python</strong>, I've been trying this:</p> <pre><code>import pypyodbc as pyodbc import urllib from xml.dom import minidom from xml.dom.minidom import parse, parseString # Replace text from nodes of the xml def replaceText(node, newText): if node.firstChild.nodeType != node.TEXT_NODE: raise Exception("node does not contain text") node.firstChild.replaceWholeText(newText) # Connection string cnxn = pyodbc.connect( 'Trusted_Connection=yes;DRIVER={SQL Server};SERVER=localhost;DATABASE=TEST;UID=sa;PWD=123456' ) idPersona = 3 # Load the selected row cursor = cnxn.cursor() cursor.execute('SELECT id, xml FROM prueba WHERE id=?', (idPersona,)) for row in cursor.fetchall(): print row[1] # Create a xml from the result string xml = row[1] dom = parseString(xml) # Update the nodes in the XML node = dom.getElementsByTagName('NOMBRE')[0] replaceText(node, "Modificado") nombre = node.firstChild.nodeValue node = dom.getElementsByTagName('APELLIDO')[0] replaceText(node, "Modificado") apellido = node.firstChild.nodeValue # Show the result... print ("Nombre: " + nombre) print ("Apellido: " + apellido) # The problem is here... cursor = cnxn.cursor() cursor.execute("UPDATE prueba SET xml=? WHERE id=?", (dom, idPersona)) cnxn.commit() print 'Actualizacion Realizada con Exito' </code></pre> <p>When the program runs the update query, It gives me the next error:</p> <pre><code>Traceback (most recent call last): File "C:\Users\cnavarro\Downloads\test.py", line 44, in &lt;module&gt; cursor.execute("UPDATE prueba SET xml=? WHERE id=?", (dom, idPersona)) File "build\bdist.win32\egg\pypyodbc.py", line 1470, in execute self._BindParams(param_types) File "build\bdist.win32\egg\pypyodbc.py", line 1275, in _BindParams if param_types[col_num][0] == 'u': TypeError: 'type' object has no attribute '__getitem__' </code></pre> <p>What am I doing wrong...?</p>
3
1,399
Using MPI's Scatterv returns different data than data sent
<p>I am trying to partially solve the Travelling Salesman Problem for 10 cities to show the best tour and its cost. The first part of the solution using mpi4py should have the root process=0 share partial tours equally between the other processes using Scatterv. This is the code that attempts to do that below:</p> <pre><code>def partition_tree(my_rank, my_stack, comm_size): # Process 0 will generate a list of comm_size partial tours . # Memory wont be shared, it will send the initial partial tours to the ap # So it will send many tours using scatter to each process # process 0 will need to send the initial tours to the appropriate process partial_tours = [] split_sizes = [] split =[] if my_rank == 0: # first to create the different partial tours for i in range(1, n): partial_tours.append([0, i]) snd_buf = np.array(partial_tours) # now to equally divide the number of processes split = np.array_split(partial_tours, comm_size, axis = 0) print(f&quot;This is split {split}&quot;) split_sizes = [] for i in range(0,len(split),1): split_sizes = np.append(split_sizes, len(split[i])) # displacement: the starting index of each sub-task # displ = [sum(count[:p]) for p in range(comm_size)] # displ = np.array(displ) split_sizes_input = split_sizes * (n-1) displacements_input = np.insert(np.cumsum(split_sizes_input), 0, 0)[0:-1] print(f&quot;this is displ {displacements_input}&quot;) split_sizes_output = split_sizes* (n-1) displacements_output = np.insert(np.cumsum(split_sizes_output),0,0)[0:-1] print(&quot;Input data split into vectors of sizes %s&quot; %split_sizes_input) print(&quot;Input data split with displacements of %s&quot; %displacements_input) else: snd_buf = None # initialize count on worker processes # count = np.zeros(comm_size, dtype=np.intc) displacements_input = None split_sizes_input = None displacements_input = None split_sizes_output = None displacements_output = None # on all processes we have the initial rcv_buf # recv_buf = np.zeros(count[my_rank]) split = comm_world.bcast(split, root = 0) split_sizes = comm_world.bcast(split_sizes_input, root = 0) displacements = comm_world.bcast(displacements_input, root = 0) split_sizes_output = comm_world.bcast(split_sizes_output, root = 0) displacements_output = comm_world.bcast(displacements_output, root = 0) recv_buf = np.empty(np.shape(split[my_rank])) print(f&quot;this is recv_buf {recv_buf} for process {my_rank}&quot;) print(f&quot;this is snd_buf {snd_buf}&quot;) # recv_buf = np.empty(np.shape(split[my_rank])) print(&quot;Rank %d with recv_buf shape %s&quot; %(my_rank,recv_buf.shape)) comm_world.Scatterv([snd_buf, split_sizes_input, displacements_input, MPI.INT], recv_buf, root = 0) print(f&quot;After scatter this is the partial tour {recv_buf} with process {my_rank}&quot;) </code></pre> <p>However, the output of the console yields this:</p> <pre><code>This is split [array([[0, 1], [0, 2], [0, 3]]), array([[0, 4], [0, 5], [0, 6]]), array([[0, 7], [0, 8], [0, 9]])] this is displ [ 0. 27. 54.] Input data split into vectors of sizes [27. 27. 27.] Input data split with displacements of [ 0. 27. 54.] this is recv_buf [0. 2.73861279 2.23606798 4.70372193 2.73861279 2.23606798 4.70372193 2.73861279 2.23606798 0. ] for process 1 this is snd_buf None Rank 1 with recv_buf shape (10,) this is recv_buf [[0.0000e+000 1.0094e-320] [4.9407e-324 0.0000e+000] [0.0000e+000 0.0000e+000]] for process 0 this is recv_buf [0.00000000e+000 1.99803933e+161 8.11662299e+217 5.59943824e-067 4.26215333e+180 1.36559641e+161 8.38861115e+242 6.96409704e+252 0.00000000e+000 0.00000000e+000] for process 2 this is snd_buf None Rank 2 with recv_buf shape (10,) this is snd_buf [[0 1] [0 2] [0 3] [0 4] [0 5] [0 6] [0 7] [0 8] [0 9]] Rank 0 with recv_buf shape (3, 2) After scatter this is the partial tour [[0.0e+000 4.9e-324] [0.0e+000 9.9e-324] [0.0e+000 1.5e-323]] with process 0 Traceback (most recent call last): File &quot;/Users/jahan/Desktop/CS381-16/Assignments/Project/tree-search.py&quot;, line 230, in &lt;module&gt; Traceback (most recent call last): File &quot;/Users/jahan/Desktop/CS381-16/Assignments/Project/tree-search.py&quot;, line 230, in &lt;module&gt; partition_tree(my_rank, my_stack, comm_size) File &quot;/Users/jahan/Desktop/CS381-16/Assignments/Project/tree-search.py&quot;, line 199, in partition_tree partition_tree(my_rank, my_stack, comm_size) File &quot;/Users/jahan/Desktop/CS381-16/Assignments/Project/tree-search.py&quot;, line 199, in partition_tree comm_world.Scatterv([snd_buf, split_sizes_input, displacements_input, MPI.INT], recv_buf, root = 0) File &quot;mpi4py/MPI/Comm.pyx&quot;, line 759, in mpi4py.MPI.Comm.Scatterv comm_world.Scatterv([snd_buf, split_sizes_input, displacements_input, MPI.INT], recv_buf, root = 0) File &quot;mpi4py/MPI/Comm.pyx&quot;, line 759, in mpi4py.MPI.Comm.Scatterv mpi4py.MPI.Exception: MPI_ERR_TRUNCATE: message truncated mpi4py.MPI.Exception: MPI_ERR_TRUNCATE: message truncated -------------------------------------------------------------------------- Primary job terminated normally, but 1 process returned a non-zero exit code. Per user-direction, the job has been aborted. -------------------------------------------------------------------------- -------------------------------------------------------------------------- mpirun detected that one or more processes exited with non-zero status, thus causing the job to be terminated. The first process to do so was: Process name: [[55033,1],2] Exit code: 1 -------------------------------------------------------------------------- </code></pre> <p>The receive buffer receives these results. I suspect it might have to do with the shape of the snd_buf and the recv_buf not matching but this still has the errors. Does anyone know how to use the scatterv function? Specifically:</p> <pre><code> comm_world.Scatterv([snd_buf, split_sizes_input, displacements_input, MPI.INT], recv_buf, root = 0) </code></pre>
3
2,338
Overload RequestMappings - Java
<p>I am using Java with Spring Security and i wanna Overload my RequestMapping but i found errors:</p> <pre><code>@RequestMapping("/") public ModelAndView index(OAuth2AuthenticationToken authentication) { Map&lt;String, Object&gt; userInfo = authentication.getPrincipal().getAttributes(); String nome = (String) userInfo.get("name"); System.out.println(nome); ModelAndView mv = new ModelAndView("index"); mv.addObject("nome", nome); System.out.println("Index"); return mv; } @RequestMapping("/") public ModelAndView index() { String nome = "Blaa"; System.out.println(nome); ModelAndView mv = new ModelAndView("index"); mv.addObject("nome", nome); System.out.println("Index"); return mv; } </code></pre> <p>The errors i found is:</p> <pre><code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'appController' method public org.springframework.web.servlet.ModelAndView br.com.mblabs.controller.AppController.index(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) to { /}: There is already 'appController' bean method public org.springframework.web.servlet.ModelAndView br.com.mblabs.controller.AppController.index() mapped. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:845) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) ~[spring-context-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:744) [spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:391) [spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:312) [spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1204) [spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE] at br.com.mblabs.EventoappApplication.main(EventoappApplication.java:32) [classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_111] at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_111] at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_111] at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_111] at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.1.8.RELEASE.jar:2.1.8.RELEASE] Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'appController' method public org.springframework.web.servlet.ModelAndView br.com.mblabs.controller.AppController.index(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) to { /}: There is already 'appController' bean method public org.springframework.web.servlet.ModelAndView br.com.mblabs.controller.AppController.index() mapped. at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.assertUniqueMethodMapping(AbstractHandlerMethodMapping.java:618) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.register(AbstractHandlerMethodMapping.java:586) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.registerHandlerMethod(AbstractHandlerMethodMapping.java:312) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.lambda$detectHandlerMethods$1(AbstractHandlerMethodMapping.java:282) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] at java.util.LinkedHashMap.forEach(Unknown Source) ~[na:1.8.0_111] at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.detectHandlerMethods(AbstractHandlerMethodMapping.java:280) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.processCandidateBean(AbstractHandlerMethodMapping.java:252) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.initHandlerMethods(AbstractHandlerMethodMapping.java:211) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.afterPropertiesSet(AbstractHandlerMethodMapping.java:199) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.afterPropertiesSet(RequestMappingHandlerMapping.java:164) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE] ... 21 common frames omitted </code></pre> <p>How can i do that ?</p> <p>My desire is if the user is logged with Oauth2 then i got his name by parameter. If he's not then i set a default name</p>
3
2,744
Combine two onEdit() functions in google app script
<p>I have a two simple scripts two make a dynamic dependent drop-down lists based on two different data sources in google sheet. In my sheet value in column B depends on the A, and value in column I depends on H. If I run one script, second doesn't work. I know I have to combine them into one function but I am totally begginer in JavaScript so thats why I ask you. </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>function onEdit(){ var tabLists = "source1"; var tabValidation = "main"; var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var datass = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(tabLists); var activeCell = ss.getActiveCell(); if(activeCell.getColumn() == 1 &amp;&amp; activeCell.getRow() &gt; 1 &amp;&amp; ss.getSheetName() == tabValidation){ activeCell.offset(0, 1).clearContent().clearDataValidations(); var makes = datass.getRange(1, 1, 1, datass.getLastColumn()).getValues(); var makeIndex = makes[0].indexOf(activeCell.getValue()) + 1; if(makeIndex != 0){ var validationRange = datass.getRange(3, makeIndex, datass.getLastRow()); var validationRule = SpreadsheetApp.newDataValidation().requireValueInRange(validationRange).build(); activeCell.offset(0, 1).setDataValidation(validationRule); } } }</code></pre> </div> </div> </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>function onEdit(){ var tabLists = "source2"; var tabValidation = "MAINTENANCE"; var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var datass = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(tabLists); var activeCell = ss.getActiveCell(); if(activeCell.getColumn() == 8 &amp;&amp; activeCell.getRow() &gt; 1 &amp;&amp; ss.getSheetName() == tabValidation){ activeCell.offset(0, 1).clearContent().clearDataValidations(); var makes = datass.getRange(1, 1, 1, datass.getLastColumn()).getValues(); var makeIndex = makes[0].indexOf(activeCell.getValue()) + 1; if(makeIndex != 0){ var validationRange = datass.getRange(3, makeIndex, datass.getLastRow()); var validationRule = SpreadsheetApp.newDataValidation().requireValueInRange(validationRange).build(); activeCell.offset(0, 1).setDataValidation(validationRule); } } } </code></pre> </div> </div> </p> <p>I have tried to combine them into one If statement with more variables like "tablist1", "tablists2", "datass1", "datass2" etc. Im so consufed so I would be grateful If you help me. </p> <p>Regards </p>
3
1,065
Rails form_with (remote: true) errors
<p>I need some help here,</p> <p>I'm getting a error when I try to update a model using ajax from Rails (form_with / remote: true). I was able to work fine with XHR requests for urls that were resources by Rails (see routes below), but with custom urls I'm getting a error.</p> <h3>controller:</h3> <pre><code>def criar @user = current_user respond_to do |format| if @user.update_attributes(user_params) format.js { flash[:success] = "Success!" redirect_to root_path } else format.js end end end </code></pre> <h3>rspec (request):</h3> <pre><code>put user_criar_path(user), xhr: true, :params =&gt; { ... } </code></pre> <h3>view:</h3> <pre><code>&lt;%= form_with model: @user, url: user_criar_path(@user), method: :put do |f| %&gt; </code></pre> <h3>routes:</h3> <pre><code>namespace :any do namespace :things do put '/criar', to: 'user#criar' # problem with XHR put '/atualizar', to: 'user#atualizar' # problem with XHR end end resources :anything # this one works fine with XHR </code></pre> <p>As you can see in the test.log, <code>Processing by UserController#criar as</code> don't have a specific format (maybe that is the problem?).</p> <h3>test.log:</h3> <pre><code>Processing by UserController#criar as Parameters: { ... } </code></pre> <h3>error message:</h3> <pre><code>Failure/Error: respond_to do |format| if @user.update_attributes(user_params) format.js { flash[:success] = "Success!" redirect_to root_path } else format.js end ActionController::UnknownFormat: ActionController::UnknownFormat </code></pre> <h3>Another request test</h3> <pre><code>it "should be redirect to (criar)" do put user_criar_path(1), xhr: true expect(response).to redirect_to(new_session_path) expect(request.flash_hash.alert).to eq "To continue, please, sign in." end </code></pre> <h3>Error message</h3> <pre><code>Failure/Error: expect(response).to redirect_to(new_session_path) Expected response to be a &lt;3XX: redirect&gt;, but was a &lt;401: Unauthorized&gt; Response body: To continue, please, sign in. </code></pre> <p>Observations:</p> <ul> <li>I already try to changing the url on routes to: <code>put '/criar', to: 'user#criar', constraints: -&gt; (req) { req.xhr? }</code></li> <li>As I said before, I was doing the same thing (tests, controller) to others resources using XHR from <code>form_with</code> and they are working fine. This one with a custom url that didn't work.</li> <li>Rails 5.2 and Rspec 3.6</li> <li>Any question, just ask on comments</li> </ul> <p>Thanks in advance!</p>
3
1,052
Pandas DataFrame : How to groupby and sort "by blocks"?
<p>I'm working with a DataFrame containing data as follows, and group the data two different ways.</p> <pre><code>&gt;&gt;&gt; d = { &quot;A&quot;: [100]*7 + [200]*7, &quot;B&quot;: [&quot;one&quot;]*4 + [&quot;two&quot;]*3 + [&quot;one&quot;]*3 + [&quot;two&quot;]*4, &quot;C&quot;: [&quot;foo&quot;]*3 + [&quot;bar&quot;] + [&quot;foo&quot;] + [&quot;bar&quot;]*2 + [&quot;foo&quot;]*2 + [&quot;bar&quot;] + [&quot;foo&quot;]*3 + [&quot;bar&quot;], &quot;D&quot;: [&quot;yay&quot;] + [&quot;nay&quot;]*2 + [&quot;yay&quot;] + [&quot;nay&quot;]*3 + [&quot;yay&quot;] + [&quot;nay&quot;] + [&quot;yay&quot;]*3 + [&quot;nay&quot;] + [&quot;yay&quot;], &quot;X&quot;: [2, 8, 3, 5, 1, 4, 3, 2, 6, 5, 1, 2, 4, 7] } &gt;&gt;&gt; df = pd.DataFrame(d) &gt;&gt;&gt; df A B C D X 0 100 one foo yay 2 1 100 one foo nay 8 2 100 one foo nay 3 3 100 one bar yay 5 4 100 two foo nay 1 5 100 two bar nay 4 6 100 two bar nay 3 7 200 one foo yay 2 8 200 one foo nay 6 9 200 one bar yay 5 10 200 two foo yay 1 11 200 two foo yay 2 12 200 two foo nay 4 13 200 two bar yay 7 &gt;&gt;&gt; df_grp = df.groupby(['A', 'B']) &gt;&gt;&gt; df_grp_sorted = df_grp.sum().sort_values('X', ascending = False) &gt;&gt;&gt; df_grp_long = df.groupby(['A', 'B', 'C', 'D']) &gt;&gt;&gt; df_grp_sorted_long = df_grp_long.sum().sort_values('X', ascending = False) </code></pre> <p>This gives us :</p> <pre><code>&gt;&gt;&gt; df_grp_sorted X 100 one 18 200 two 14 one 13 100 two 8 &gt;&gt;&gt; df_grp_sorted_long X 100 one foo nay 11 two bar nay 7 200 two bar yay 7 one foo nay 6 100 one bar yay 5 200 one bar yay 5 two foo nay 4 yay 3 100 one foo yay 2 200 one foo yay 2 100 two foo nay 1 </code></pre> <p>Now, I would like to have the detail from df_grp_sorted_long, with the structure of df_grp_sorted. That would be :</p> <pre><code>&gt;&gt;&gt; df_result X 100 one foo nay 11 yay 5 foo yay 2 200 two bar yay 7 foo nay 4 yay 3 one foo nay 6 bar yay 5 foo yay 2 100 two bar nay 7 foo nay 1 </code></pre> <p>I have done this with the following code (which goes against <a href="https://stackoverflow.com/a/56746204/4909087">this post</a>'s advice) :</p> <pre><code>&gt;&gt;&gt; col_names = ['A', 'B', 'C', 'D'] &gt;&gt;&gt; df_result = pd.DataFrame(columns=col_names) &gt;&gt;&gt; for (i, (a, b)) in enumerate(df_grp_sorted.index): df_result = pd.concat( ( df_result, (df[(df['A']==a) &amp; (df['B']==b)] .groupby(col_names) .sum() .sort_values('X', ascending=False) ) ) ) &gt;&gt;&gt; df_result = df_result[&quot;X&quot;] </code></pre> <p>This gives the right answer, but is very slow for big data sets. I'm also wondering if there's a native way to do such a combination of grouping/sorting.</p> <p>Also, maybe this approach is not the right one and there's a much simpler way to obtain this result of an equivalent one?</p>
3
1,869
Exception in thread django-main-thread, SECRET_KEY already installed
<p>I cloned my own repository in GitHub and after installing the necessary dependencies I tried to run my project with:</p> <pre><code>python3 manage.py runserver </code></pre> <p>But when I do that, I get this exception in the thread and I can't see any particular error</p> <pre><code>Exception in thread django-main-thread: Traceback (most recent call last): File &quot;/home/gitpod/.pyenv/versions/3.8.11/lib/python3.8/threading.py&quot;, line 932, in _bootstrap_inner self.run() File &quot;/home/gitpod/.pyenv/versions/3.8.11/lib/python3.8/threading.py&quot;, line 870, in run self._target(*self._args, **self._kwargs) File &quot;/workspace/.pip-modules/lib/python3.8/site-packages/django/utils/autoreload.py&quot;, line 64, in wrapper fn(*args, **kwargs) File &quot;/workspace/.pip-modules/lib/python3.8/site-packages/django/core/management/commands/runserver.py&quot;, line 110, in inner_run autoreload.raise_last_exception() File &quot;/workspace/.pip-modules/lib/python3.8/site-packages/django/utils/autoreload.py&quot;, line 87, in raise_last_exception raise _exception[1] File &quot;/workspace/.pip-modules/lib/python3.8/site-packages/django/core/management/__init__.py&quot;, line 375, in execute autoreload.check_errors(django.setup)() File &quot;/workspace/.pip-modules/lib/python3.8/site-packages/django/utils/autoreload.py&quot;, line 64, in wrapper fn(*args, **kwargs) File &quot;/workspace/.pip-modules/lib/python3.8/site-packages/django/__init__.py&quot;, line 24, in setup apps.populate(settings.INSTALLED_APPS) File &quot;/workspace/.pip-modules/lib/python3.8/site-packages/django/apps/registry.py&quot;, line 122, in populate app_config.ready() File &quot;/workspace/.pip-modules/lib/python3.8/site-packages/django/contrib/admin/apps.py&quot;, line 27, in ready self.module.autodiscover() File &quot;/workspace/.pip-modules/lib/python3.8/site-packages/django/contrib/admin/__init__.py&quot;, line 24, in autodiscover autodiscover_modules('admin', register_to=site) File &quot;/workspace/.pip-modules/lib/python3.8/site-packages/django/utils/module_loading.py&quot;, line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File &quot;/home/gitpod/.pyenv/versions/3.8.11/lib/python3.8/importlib/__init__.py&quot;, line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1014, in _gcd_import File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 991, in _find_and_load File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 975, in _find_and_load_unlocked File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 671, in _load_unlocked File &quot;&lt;frozen importlib._bootstrap_external&gt;&quot;, line 843, in exec_module File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 219, in _call_with_frames_removed File &quot;/workspace/.pip-modules/lib/python3.8/site-packages/django/contrib/auth/admin.py&quot;, line 6, in &lt;module&gt; from django.contrib.auth.forms import ( File &quot;/workspace/.pip-modules/lib/python3.8/site-packages/django/contrib/auth/forms.py&quot;, line 11, in &lt;module&gt; from django.contrib.auth.tokens import default_token_generator File &quot;/workspace/.pip-modules/lib/python3.8/site-packages/django/contrib/auth/tokens.py&quot;, line 117, in &lt;module&gt; default_token_generator = PasswordResetTokenGenerator() File &quot;/workspace/.pip-modules/lib/python3.8/site-packages/django/contrib/auth/tokens.py&quot;, line 18, in __init__ self.secret = self.secret or settings.SECRET_KEY File &quot;/workspace/.pip-modules/lib/python3.8/site-packages/django/conf/__init__.py&quot;, line 90, in __getattr__ raise ImproperlyConfigured(&quot;The SECRET_KEY setting must not be empty.&quot;) django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. </code></pre>
3
1,579
How to refer the foriegnkey which is an identity column in ASP.Net WebAPI models
<p>This is how my ASP.Net REST Web API models looks like and their DataTransferObject models are just a replica of these models without any attributes. I didn't mention ModelDto classes since they look very similar to Models. And I want to populate the database with Entity Framework Code First approach in c#.</p> <pre><code> class Customer { public int id { get; set; } // this an identity column in db public string name { get; set; } public string UserId { get; set; } public string Source { get; set; } public DateTime RegisteredOn { get; set; } } // Note: Other than identity column , The combinmation of UserId and Source is unique. class Ticket { public int id { get; set; } // this an identity column in db and its ticketid which is unique [ForeignKey("Customer")] public int id { get; set; } // i am thinking this should refer the identity column of the Customer class since its unique. but if i refer the foreign key as "id" , then i will have two properties in this class one for its own identity column and other one referring to the Customer class. public string Description { get; set; } // ticket problem description public DateTime CreatedOn { get; set; } } class TicketComment { public int id { get; set; } // this an identity column in db and its commentid which is unique [ForeignKey("Ticket")] public int id { get; set; } // i am thinking this should refer the identity column of the Ticket class since its unique. but if i refer the foreign key as "id" , then i will have two properties in this class one for its own identity column and other one referring to the tTicket class. public string Comment { get; set; } // user may add a comment or notes to existing ticket to provide more info or asking for status } class TicketUpdates { public int id { get; set; } // this an identity column in db and its updateid which is unique [ForeignKey("Ticket")] public int id { get; set; } // i am thinking this should refer the identity column of the Ticket class since its unique. but if i refer the foreign key as "id" , then i will have two properties in this class one for its own identity column and other one referring to the tTicket class. public string Status { get; set; } // agent may add a status to existing ticket along with some notes } </code></pre> <p>i have three questions here:</p> <p>How do i refer to the identity column of the other table/entity when the current table or entity already has an identity column with the same name.( Since i am using Entity framework it always create a table with the identity column name as "id".)</p> <p>And how do we retrieve the Customer records along with each customer's tickets, each ticket's comments and each ticket's updates in one get call in REST Web API ? How should my GET method look like in <strong>CustomerController</strong> ?</p> <p>Should I look at other fields than identity column field to refer the foreign keys ?</p> <p>I looked at some of the existing posts but my scenario looks a bit different. </p>
3
1,073
keycloak Spring Security : Unable to login with Bearer token as null
<p>I have integrated the Keylock with Spring boot using @KeycloakConfiguration in SecurityConfig Class,</p> <pre><code>@KeycloakConfiguration @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true) public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter { // configureGlobal() tasks the SimpleAuthorityMapper to make sure roles are not // prefixed with ROLE_. @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider(); keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper()); auth.authenticationProvider(keycloakAuthenticationProvider); } // keycloakConfigResolver defines that we want to use the Spring Boot properties // file support instead of the default keycloak.json. @Bean public KeycloakSpringBootConfigResolver KeycloakConfigResolver() { return new KeycloakSpringBootConfigResolver(); } @Bean @Override protected SessionAuthenticationStrategy sessionAuthenticationStrategy() { return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl()); } // we are permitting all here but we are gonna have method level // pre-authorization @Override protected void configure(HttpSecurity http) throws Exception { super.configure(http); http.cors().and().csrf().disable() .authorizeRequests().antMatchers(&quot;/admin**&quot;).hasAnyRole(&quot;admin&quot;) .anyRequest().permitAll(); } // we configure to accepts CORS requests from all and any domains @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping(&quot;/**&quot;).allowedOrigins(&quot;*&quot;).allowedMethods(&quot;GET&quot;, &quot;POST&quot;, &quot;PUT&quot;, &quot;DELETE&quot;); } }; } @PostMapping(&quot;/login&quot;) public @ResponseBody AuthToken login(@RequestBody LoginForm form) { Collection&lt;SimpleGrantedAuthority&gt; authorities = (Collection&lt;SimpleGrantedAuthority&gt;) SecurityContextHolder .getContext().getAuthentication().getAuthorities(); AuthToken authToken = authService.login(form); authToken.setAuthorities(authorities); return authToken; } </code></pre> <p>and I am able to log in without a Bearer token and with an empty Bearer token. <a href="https://i.stack.imgur.com/QTzml.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QTzml.png" alt="enter image description here" /></a> I have created a login page in angular, and from that, I am passing the bearer token is null. <a href="https://i.stack.imgur.com/PY2lI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PY2lI.png" alt="enter image description here" /></a></p> <p>I am getting</p> <p>status&quot;: 401, “error”: “Unauthorized”</p> <p>and there are no security logs on eclipse.</p> <p><a href="https://i.stack.imgur.com/wH0y9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wH0y9.png" alt="enter image description here" /></a></p> <p>Thanks and Regards</p>
3
1,328
Rails: Finding records where a nested association is empty
<p>In a Rails application I'm working on, I've got a few different models associated like this (condensed for clarity):</p> <p><code>group.rb</code></p> <pre><code>class Group &lt; ApplicationRecord has_many :members, class_name: 'GroupMember' has_many :newsletters end </code></pre> <p><code>group_member.rb</code></p> <pre><code>class GroupMember &lt; ApplicationRecord belongs_to :group has_many :authorships, inverse_of: :group_member, class_name: &quot;Newsletter::Author&quot; has_many :stories, inverse_of: :author, class_name: &quot;Newsletter::Story&quot; end </code></pre> <p><code>newsletter.rb</code></p> <pre><code>class Newsletter &lt; ApplicationRecord has_many :authors, inverse_of: :newsletter has_many :stories end </code></pre> <p><code>newsletter/author.rb</code></p> <pre><code>class Newsletter::Author &lt; ApplicationRecord belongs_to :newsletter, inverse_of: :authors belongs_to :group_member, class_name: &quot;GroupMember&quot;, inverse_of: :authorships end </code></pre> <p><code>newsletter/story.rb</code></p> <pre><code>class Newsletter::Story &lt; ApplicationRecord belongs_to :newsletter, inverse_of: :stories, optional: true belongs_to :author, inverse_of: :stories, class_name: &quot;GroupMember&quot; enum status: {draft: &quot;draft&quot;, submitted: &quot;submitted&quot;, published: &quot;published&quot;}, _default: &quot;draft&quot; end </code></pre> <p>Given the above associated models, here's the framework I'm working within:</p> <ul> <li>Each Newsletter has <em>n</em> Authors (Group Members) and <em>n</em> Newsletters.</li> <li>Each Group Member can author multiple stories for a given newsletter.</li> <li>Each story is one of theses status states: <strong>draft</strong>, <strong>submitted</strong>, or <strong>published</strong></li> <li>A draft story may or may not be associated with a Newsletter</li> <li>A submitted or published story is associated with a Newsletter</li> </ul> <p>I'd like to find out which Authors for a given newsletter have NO stories with a <strong>draft</strong> or <strong>submitted</strong> status.</p> <p>Given <code>newsletter_id</code>, I can find out the members that DO have a draft or submitted story with a query like this:</p> <pre><code> Newsletter.find(newsletter_id).authors .joins(group_member: :stories) .where(stories: {status: [:draft, :submitted]}) .distinct </code></pre> <p>However, I'm not sure how to negate that and get the the opposite of that set of authors. That is, authors for a given newsletter who DON'T have draft or submitted stories. Whether or not they have published stories should make no difference.</p> <p><strong>EDIT</strong></p> <p>I asked <a href="https://stackoverflow.com/questions/68212648/filtering-an-association-by-missing-records-in-rails">a similar question</a> a few months ago about identifying records where records of an associated model did not exist. I think that's a very similar approach for what I need to do here, but I haven't quite cracked how to apply that answer to this question due to the nested association of <code>GroupMember (as Newsletter::Author)</code> -&gt; <code>Newsletter</code> -&gt; <code>Newsletter::Story</code></p> <p>A pure SQL answer here would also be enlightening.</p>
3
1,026
Issue with state update approach for nested objects
<p><em>Major EDIT</em></p> <p>I have quite huge object which is 3 level deep. I use it as a template to generate components on the page and to store the values which later are utilized, eg:</p> <pre><code>obj = { &quot;group&quot;: { &quot;subgroup1&quot;: { &quot;value&quot;: { &quot;type&quot;: &quot;c&quot;, &quot;values&quot;: [] }, &quot;fields_information&quot;: { &quot;component_type&quot;: &quot;table&quot;, &quot;table_headers&quot;: [ &quot;label&quot;, &quot;size&quot; ], } }, &quot;subgroup2&quot;: { &quot;value&quot;: { &quot;type&quot;: &quot;c&quot;, &quot;values&quot;: [] }, &quot;fields_information&quot;: { &quot;component_type&quot;: &quot;table&quot;, &quot;table_headers&quot;: [ &quot;label&quot;, &quot;size&quot; ], } }, }, } </code></pre> <p>Thanks to this I can dynamically generate view which is, as a template, stored in DB.</p> <p>I'm struggling with 2 things. Firstly, updating values basing on user input for textbox, checkboxes and similar. I'm doing it this way:</p> <pre><code> const updateObj = (group, subgroup, value) =&gt; { let tempObj = {...obj} tempObj[group][subgroup].value.value = value toggleObj(tempObj) } </code></pre> <p>I know that the spread operator is not in fact doing deep copy. However it allows me to work on the object and save it later. Is that an issue? Do I have to cloneDeep or it is just fine? Could cloneDeep impact performance?</p> <p>Second case is described below</p> <pre><code>export const ObjectContext = React.createContext({ obj: {}, toggleObj: () =&gt; {}, }); export const Parent = (props) =&gt; { const [obj, toggleObj] = useState() const value = {obj, toggleObj} return ( &lt;FormCreator /&gt; ) } const FormCreator = ({ catalog }) =&gt; { const {obj, toggleObj} = React.useContext(ObjectContext) return (&lt;&gt; {Object.keys(obj).map((sectionName, sectionIdx) =&gt; { const objFieldsInformation = sectionContent[keyName].fields_information const objValue = sectionContent[keyName].value ... if (objFieldsInformation.component_type === 'table') { return ( &lt;CustomTable key={keyName + &quot;id&quot;} label={objFieldsInformation.label} headers={objFieldsInformation.table_headers} suggestedValues={[{label: &quot;&quot;, size: &quot;&quot;}, {label: &quot;&quot;, size: &quot;&quot;}, {label: &quot;&quot;, size: &quot;&quot;}]} values={objValue.values} sectionName={sectionName} keyName={keyName}/&gt; ) } ... })} &lt;/&gt;) } const CustomTable= (props) =&gt; { const { label = &quot;&quot;, headers = [], suggestedValues = [], values, readOnly = false, sectionName, keyName } = props const {obj, toggleObj} = React.useContext(ObjectContext) //this one WORKS useEffect(() =&gt; { if (obj[sectionName][keyName].value.type === &quot;complex&quot;) { let temp = {...obj} temp[sectionName][keyName].value.values = [...suggestedValues] toggleObj(temp) } }, []) //this one DOES NOT useEffect(() =&gt; { if (obj[sectionName][keyName].value.type === &quot;c&quot;) { let temp = {...obj, [sectionName]: {...obj[sectionName], [keyName]: {...obj[sectionName][keyName], value: {...obj[sectionName][keyName].value, values: [{label: &quot;&quot;, size: &quot;&quot;}, {label: &quot;&quot;, size: &quot;&quot;}, {label: &quot;&quot;, size: &quot;&quot;}]}}}} toggleObj(temp) } }, []) return ( //draw the array ) } </code></pre> <p>Please refer to CustomTable component. As on the example Object above, I have 2 CustomTables to be printed. Unfortunately, one useEffect that should work is not working properly. I'm observing, that values field is set only for the last &quot;table&quot; in Obj. When I'm doing shallow copy of obj, it works fine. But I'm afraid of any repercussion that might happens in future.</p> <p>I'm also totally new to using createContext and maybe somehow it is the issue.</p> <p>Kudos to anyone understanding that chaos :)</p>
3
1,971
Custom QueryVars and pretty URL with Wordpress
<p>I have working 'solution' but I'm not able to make a clean URL.</p> <p>My Setup: Two CPT 'objekte' and 'onlineauktion'.</p> <pre><code> register_post_type( 'objekte', array( 'labels' =&gt; array( 'name' =&gt; __( 'Objekte'), 'singular_name' =&gt; __( 'Objekt' ) ), 'public' =&gt; true, 'has_archive' =&gt; true, 'rewrite' =&gt; array('slug'=&gt;'objekt'), 'capability_type' =&gt; 'page', 'supports' =&gt; array('thumbnail', 'title', 'custom-fields', 'revisions', 'page-attributes', 'post-formats'), // see http://www.kevinleary.net/wordpress-dashicons-list-custom-post-type-icons/ 'menu_icon' =&gt; 'dashicons-star-filled', 'hierarchical' =&gt; true, ) ); flush_rewrite_rules(); register_post_type( 'onlineauktion', array( 'labels' =&gt; array( 'name' =&gt; __( 'Online Auktionskatalog'), 'singular_name' =&gt; __( 'Online Auktionskatalog' ) ), 'public' =&gt; true, 'has_archive' =&gt; true, 'rewrite' =&gt; array('slug'=&gt;'onlineauktion'), 'capability_type' =&gt; 'page', 'supports' =&gt; array('thumbnail', 'title', 'custom-fields', 'revisions', 'page-attributes', 'post-formats'), // see http://www.kevinleary.net/wordpress-dashicons-list-custom-post-type-icons/ 'menu_icon' =&gt; 'dashicons-star-filled', 'hierarchical' =&gt; true, ) ); flush_rewrite_rules(); </code></pre> <p>Archivpage ('objekte'): /objekt/page_title That's fine. Archivepage ('onlineauktion') with a ACF realtionship field for 'objekte' with the same link /objekt/page_tiel but I would like to have /onlineauktion/objekt/page_title</p> <p>Registration of the QueryVars</p> <pre><code>function registerQueryVars( $vars ) { $vars[] = 'cm_status'; return $vars; } add_filter( 'query_vars', 'registerQueryVars' ); </code></pre> <p>Permalink on the Archivpage ('onlineauktion')</p> <pre><code>&lt;a class=&quot;black&quot; href=&quot;{{post.link}}{{type == 'onlineauktion' ? '?cm_status=onlineauktionen'}}&quot;&gt; </code></pre> <p>If I visit the page 'onlineauktion' i get this URL: /objekt/abgehaeutetes-rind-−-1968/?cm_status=onlineauktionen</p> <p>this is not working:</p> <pre><code>add_action('init', 'add_my_rewrite'); function add_my_rewrite() { global $wp_rewrite; $wp_rewrite-&gt;add_rule('objekt/([^/]+)','index.php?cm_status=$matches[1]','top'); $wp_rewrite-&gt;flush_rules(false); // This should really be done in a plugin activation } </code></pre> <p>What am i missing.</p> <p>Thanks in advance</p> <p>C</p>
3
1,154
Fill in table after form submit in vuejs
<p>I need the table to populate after I submit a form to an api in ASP.NET c#, the api request send the data back and then the table needs to fill.</p> <p>At the moment I tried to check if the form value is null or not, and after the submit it does show the table, but not the data inside the table.</p> <p>How do you make it so that after the form submit, the data from the api shows?</p> <pre class="lang-js prettyprint-override"><code> new Vue({ el: '#app', data: { info: [], IngredientCategory: '', IngredientCategory1: '', }, methods: { getFormValues() { console.log("test " + this.IngredientCategory); axios .get("https://localhost:44331/Api/ShowRecipes/"+ this.ingredientCategory + "/" + this.ingredientCategory1 ) .then(response =&gt; this.info.concat(response.data)) }, } }); </code></pre> <p>html </p> <pre><code> &lt;table v-if="info !== null"&gt; &lt;thead class="thead-dark"&gt; &lt;tr&gt; &lt;th&gt;#&lt;/th&gt; &lt;th&gt;IngredientCategory&lt;/th&gt; &lt;th&gt;IngredientName&lt;/th&gt; &lt;th&gt;Calories&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr v-for="inf in info" :key="inf.Id"&gt; &lt;td&gt;{{inf.Id}}&lt;/td&gt; &lt;td&gt;{{inf.IngredientCategory}}&lt;/td&gt; &lt;td&gt;{{inf.IngredientName}}&lt;/td&gt; &lt;td&gt;{{inf.Calories}}&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;form @@submit.prevent="getFormValues()"&gt; &lt;input type="text" v-model="IngredientCategory"&gt; &lt;input type="text" ref="IngredientCategory1" v-model="IngredientCategory1"&gt; &lt;button&gt;Get values&lt;/button&gt; &lt;/form&gt; </code></pre> <p>api data </p> <pre><code>[ { "Id": 1, "IngredientName": "something", "IngredientCategory": "test", "Calories": 100 }, { "Id": 2, "IngredientName": "something", "IngredientCategory": "test", "Calories": 100 }, ] </code></pre> <p>...</p>
3
1,480
how to delete all records excluding 0th record in array index
<p>As per the code I don't want to delete 0th record and delete rest of the record. But it is deleting all the records!</p> <p>Kindly assist where I am making the mistake.</p> <p>Here is the code:</p> <pre><code>list&lt;account&gt; scope = [Select Id,(Select id,CreatedDate,ebMobile__FileType__c,ebMobile__Account__c from Files__r order by CreatedDate DESC) from account where id in ('0016D00000444','0016D000000ugO')]; Set&lt;Id&gt;OldIds = new Set&lt;Id&gt;(); Set&lt;Id&gt;newIds = new Set&lt;Id&gt;(); Set&lt;Id&gt; rIds = new Set&lt;Id&gt;(); Set&lt;Id&gt; rrIds = new Set&lt;Id&gt;(); list&lt;File__c&gt; listmemb = new list&lt;File__c&gt;(); List&lt;File__c&gt; listmemb3 = new List&lt;File__c&gt;(); List&lt;File__c&gt; listmemb4 = new List&lt;File__c&gt;(); for(Account Acc : scope) { for(File__c fi : Acc.ebMobile__Files__r) { listmemb = [select id,CreatedDate,ebMobile__FileType__c from File__c where id =: fi.id]; if(fi.ebMobile__Account__c != Null) { for(Integer i=0; i&lt;listmemb.size(); i++) { if(fi.ebMobile__FileType__c == 'Signature' &amp;&amp; i==0) { rIds.add(listmemb[0].id); // Exclude 0th record } if(i&gt;0 &amp;&amp; listmemb[i].ebMobile__FileType__c == 'Signature' || i &gt; 0 &amp;&amp; listmemb[i].ebMobile__FileType__c != 'signature') { rrIds.add(listmemb[i].id); // Delete all record excluding 0th record } if(fi.ebMobile__FileType__c != 'Signature') { OldIds.add(fi.id); } } } } } listmemb3 = [Select id,CreatedDate,ebMobile__FileType__c from File__c where id in : OldIds]; listmemb4 = [Select id,CreatedDate,ebMobile__FileType__c from ebMobile__File__c where id in : rrIds]; if(listmemb3.size() &gt; 0 &amp;&amp; listmemb4.size()&gt;0) { delete listmemb3; delete listmemb4; } } </code></pre>
3
1,303
Controller to write contents or msg varaibles to specific iframe
<p>I am using an JSP page which has two iframe, one of the iframe in the left pane shows the link's and iframe in the right pane is the display window, when I click on the link in the left iframe, the controller is called, to display the content in the right pane/iframe, but it always display the content in the same pane/left pane/left iframe itself, how to display the contents in the right iframe/display window.</p> <p>refer to the picture for more details <a href="https://i.stack.imgur.com/Tq2yv.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tq2yv.jpg" alt="enter image description here"></a></p> <p>showMessage</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%&gt; &lt;%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%&gt; &lt;%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%&gt; &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" type="text/css" href="/LDODashBoard/css/mystyle.css" /&gt; &lt;title&gt;L1 DashBoard page&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;iframe id="mainContent" src="/LDODashBoard/L1SrcLinkPage.htm" height="500" width=20% scrolling="no"&gt;Main&lt;/iframe&gt; &lt;iframe id="displayContent" src="/LDODashBoard/L1OutputDisplayPage.htm" height="500" width=70% scrolling="no"&gt;Content&lt;/iframe&gt; &lt;h2&gt;${message}&lt;/h2&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>MainController </p> <pre><code>package com.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.validation.*; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.RedirectView; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.security.UrlAuthenticationSuccessHandler; import org.apache.log4j.Logger; /* * author: Crunchify.com * */ @Controller public class MainController { static Logger log = Logger.getLogger(MainController.class.getName()); @RequestMapping("/showMessage") public ModelAndView helloWorld() { System.out.println("inisde showmessage method"); log.info("inisde showmessage method"); String message = "&lt;br&gt;&lt;div style='text-align:center;'&gt;" + "&lt;h3&gt;********** Welcome to LDO Support Landing page **********&lt;h3&gt; &lt;/div&gt;&lt;br&gt;&lt;br&gt;"; return new ModelAndView("showMessage", "message", message); } @RequestMapping(value = "/L1SrcLinkPage") public String srcLinkMethod(HttpSession session) { log.info("inside srcLinkMethod method"); // session.invalidate(); return "L1SrcLinkPage"; } @RequestMapping(value = "/L1OutputDisplayPage") public String srcOutputDisplayMethod(HttpSession session) { log.info("inside L1OutputDisplayPage method"); // session.invalidate(); return "L1OutputDisplayPage"; } @RequestMapping(value = "/gcmmLink1", method = RequestMethod.GET) public ModelAndView gcmmLink1(Model model, HttpServletResponse response) { log.info("inisde gcmmLink1 method"); String message = "&lt;br&gt;&lt;div style='text-align:center;'&gt;" + "&lt;h3&gt;********** Showing the output of gcmmLink1 **********&lt;h3&gt; &lt;/div&gt;&lt;br&gt;&lt;br&gt;"; return new ModelAndView("L1OutputDisplayPage", "message", message); } @RequestMapping(value = "/gcmmLink2", method = RequestMethod.GET) public ModelAndView gcmmLink2() { log.info("inisde gcmmLink2 method"); String message = "&lt;br&gt;&lt;div style='text-align:center;'&gt;" + "&lt;h3&gt;********** Showing the output of gcmmLink2 **********&lt;h3&gt; &lt;/div&gt;&lt;br&gt;&lt;br&gt;"; return new ModelAndView("L1OutputDisplayPage", "message", message); } } </code></pre> <p>L1SrcLinkPage.jsp</p> <pre><code> &lt;!DOCTYPE html&gt; &lt;%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%&gt; &lt;%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Welcome&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;c:url value="/gcmmLink1" var="messageUrl1" /&gt; &lt;a href="${messageUrl1}" &gt;GCMM process check!!&lt;/a&gt; &lt;br&gt; &lt;c:url value="/gcmmLink2" var="messageUrl2" /&gt; &lt;a href="${messageUrl2}"&gt;GCMM second process check!!&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>L1OutputDisplayPage.jsp</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Welcome&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h2&gt;${message}&lt;/h2&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <h2>solution:</h2> <pre><code>&lt;!DOCTYPE html&gt; &lt;%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%&gt; &lt;%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %&gt; &lt;html&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; function doSomething(UrlValue){ var ifrm = parent.document.getElementById('displayContent'); var doc = ifrm.contentDocument? ifrm.contentDocument: ifrm.contentWindow.document; alert (doc.getElementById("h1").innerHTML); doc.getElementById("h1").innerHTML = "hello, changing the value"; var urlString = "/LDODashBoard/L1OutputDisplayPage?" + UrlValue + "=true"; alert (urlString); ifrm.contentWindow.location.href = urlString; } &lt;/script&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Welcome&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;c:url value="/L1OutputDisplayPage?gcmmLink1=true" var="messageUrl1" /&gt; &lt;a href="${messageUrl1}" onClick="doSomething('gcmmLink1');return false;"&gt;GCMM process check!!&lt;/a&gt; &lt;br&gt; &lt;c:url value="/L1OutputDisplayPage?gcmmLink2=true" var="messageUrl2" /&gt; &lt;a href="${messageUrl2}" onClick="doSomething('gcmmLink2');return false;"&gt; GCMM second process check!!&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
3
2,747
Asp.net how to correct the error
<pre><code> using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; public partial class Bookcheck : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { SqlDataAdapter da=new SqlDataAdapter (); SqlConnection cnn=new SqlConnection(); DataSet ds = new DataSet(); string constr = null; SqlCommand cmd = new SqlCommand(); if (IsValid != null) { constr = @"Data Source=DEVI\SQLEXPRESS; Initial Catalog =librarymanagement; Integrated Security=SSPI"; cnn.ConnectionString = constr; try { if (cnn.State != ConnectionState.Open) cnn.Open(); } catch (Exception ex) { string str1 = null; str1 = ex.ToString(); } cmd.Connection = cnn ; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "spbookcheck"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("bookid", txtid.Text); cmd.Parameters.AddWithValue("Nameofthebook", txtnb.Text); da.SelectCommand=cmd; try { da.Fill(ds); } catch (Exception ex) { string strErrMsg = ex.Message; // throw new ApplicationException } finally { da.Dispose(); cmd.Dispose(); cnn.Close(); cnn.Dispose(); } if (ds.Tables[0].Rows.Count &gt; 0) { Msg.Text = "bookcheck successfully"; Response.Redirect("Issueofbook.aspx"); } else { Msg.Text="bookcheck failed"; } } } } </code></pre> <p>My error </p> <blockquote> <p>Index out of range exception the unhandle by the user cannot find table 0</p> </blockquote>
3
1,241
Why are old variables reused when using event handler functions with Javascript?
<p>I'm trying to create a Simon game (project from a Udemy course) where you have to memorize a pattern sequence and click the right buttons. At each level, the pattern sequence increases by one. You have to repeat the entire sequence each time. If you lose, you have to press a key to restart the game. Here is an example:</p> <p><a href="https://londonappbrewery.github.io/Simon-Game/" rel="nofollow noreferrer">https://londonappbrewery.github.io/Simon-Game/</a></p> <p>However, when my game is restarted with my current code, everything falls apart. I don't know if old variables from a previous game continue into the new one, or maybe my code is just written really poorly.</p> <p>I've implemented the entire game within a keypress event handler. Doing this initiates all the functions and variables of the game. The sequence is stored within an array, and each subsequent click on a box compares its colour value against the array. If it doesn't match - its game over. If it does match, it will either wait for you to finish the sequence correctly, or go to the next level.</p> <p>Can anyone give me pointers on what I might be doing wrong? And whether it's at all possible to make this work the way I have it set up?</p> <pre><code>$(document).on(&quot;keypress&quot;, function(){ let counter = 0; let level = 1; let colours = [&quot;green&quot;,&quot;red&quot;,&quot;yellow&quot;,&quot;blue&quot;]; let nodeList = []; function nextNode(){ randomNumberGen = Math.floor(Math.random()*4); currentNode = colours[randomNumberGen]; nodeList.push(currentNode); $(&quot;.&quot;+currentNode).fadeOut(200).fadeIn(200); } $(&quot;h1&quot;).text(&quot;Level &quot;+level); setTimeout(function() { nextNode(); },500); $(document).on(&quot;click&quot;, &quot;.box&quot;, function(){ selectedNode = $(this).attr(&quot;id&quot;); $(&quot;#&quot;+selectedNode).addClass(&quot;pressed&quot;); setTimeout(function(){ $(&quot;#&quot;+selectedNode).removeClass(&quot;pressed&quot;); },100); if (nodeList[counter] != selectedNode){ gameSounds(&quot;wrong&quot;); $(&quot;body&quot;).addClass(&quot;game-over&quot;); setTimeout(function(){ $(&quot;body&quot;).removeClass(&quot;game-over&quot;); },100); $(&quot;h1&quot;).text(&quot;Game Over, Press Any Key to Restart&quot;); } else{ gameSounds(selectedNode); counter++; if (counter&gt;= nodeList.length){ level++; setTimeout(function(){ $(&quot;h1&quot;).text(&quot;Level &quot;+(level)); }, 1000); counter = 0; setTimeout(function() { nextNode(); },1000); } } }); }); function gameSounds(key){ var soundPlay = new Audio(&quot;sounds/&quot;+key+&quot;.mp3&quot;); soundPlay.play(); } </code></pre>
3
1,309
Changing user preferences in a flutter app when navigating to new screen
<p>I have 2 screens in my flutter app and they're defined as follows:</p> <ol> <li><p><code>allFriends</code>: has a list of users on cards, which when clicked on will bring up a full view of the user (<code>otherUserProfileView</code>).</p> </li> <li><p><code>otherUserProfileView</code>: shows the profile view (information is loaded from a Firebase Realtime Database)</p> </li> </ol> <p>When I navigate to <code>otherUserProfileView</code>, I still see content about the user that I first viewed after reloading.</p> <p>Do you know how I can fix this so I can see a new user each time I navigate to <code>otherUserProfileView</code>, after clicking a new user? Any help is appreciated.</p> <p>Below is the code:</p> <p><code>allFriends</code>:</p> <pre><code>child: InkWell( onTap: (){ Navigator.of(context).push(MaterialPageRoute( builder: (context) =&gt; Screen2( friendID: friend.userID, friendName: friend.name, profilePic: friend.picture, ), )); }, child: Card() ) </code></pre> <p><code>otherUserProfileView</code>:</p> <pre><code>class OtherUserProfileView extends StatefulWidget { final String friendID; final String friendName; final String profilePic; const OtherUserProfileView( {Key? key, required this.friendID, required this.friendName, required this.profilePic}) : super(key: key); @override _OtherUserProfileViewState createState() =&gt; _OtherUserProfileViewState(); } class _OtherUserProfileViewState extends State&lt;OtherUserProfileView&gt; { List&lt;String&gt; images = []; StreamSubscription? _imagesStream; @override void initState() { super.initState(); addImages(); } void addImages() { images.add(widget.profilePic); final db = FirebaseDatabase.instance .ref() .child('users') .child(widget.friendID) .child(&quot;pictures&quot;); _imagesStream = db.onValue.listen((event) { if (event.snapshot.exists) { final data = new Map&lt;dynamic, dynamic&gt;.from( event.snapshot.value as Map&lt;dynamic, dynamic&gt;); data.forEach((key, value) { db.child(key).onValue.listen((event) { setState(() { images.add(value); }); }); }); } }); } @override Widget build(BuildContext context) { return Scaffold( extendBodyBehindAppBar: true, body: _getContent(), ); } Widget _getContent() { return new ListView( scrollDirection: Axis.vertical, children: &lt;Widget&gt;[ CardRow(friendID: widget.friendID), images == null ? Container() : Column( children: [ Container( height: 200, child: ListView.builder( scrollDirection: Axis.horizontal, shrinkWrap: true, itemBuilder: (context, index) =&gt; BuildPicture(images[index]), itemCount: images.length, ), ), ], ), ], ); } @override void deactivate() { _imagesStream?.cancel(); super.deactivate(); } } class BuildPicture extends StatelessWidget { final String url; BuildPicture(this.url); @override Widget build(BuildContext context) { return Container( height: 200, child: Image.network(url), ); } } class CardRow extends StatefulWidget { final String friendID; const CardRow({Key? key, required this.friendID}) : super(key: key); @override State&lt;CardRow&gt; createState() =&gt; _CardRowState(); } class _CardRowState extends State&lt;CardRow&gt; { late StreamSubscription _userStream; late StreamSubscription _friendsStream; static String uid = &quot;&quot;; static DatabaseReference userDatabase = FirebaseDatabase.instance.ref().child('users').child(&quot;$uid&quot;); static List&lt;String&gt; theirFriends = []; var _userName = &quot;&quot;; var _emailAddress = &quot;&quot;; var _country = &quot;&quot;; var _bio = &quot;&quot;; var _profileUrl; var user; int mutualFriends = theirFriends.length; @override void initState() { super.initState(); uid = widget.friendID; _activateListeners(); _retrieveFriends(); } void _activateListeners() { _userStream = userDatabase.onValue.listen((event) { if (event.snapshot.exists) { final data = new Map&lt;dynamic, dynamic&gt;.from( event.snapshot.value as Map&lt;dynamic, dynamic&gt;); final username = data['username'] as String; final emailAdd = data['emailAdd'] as String; final country = data['country'] as String; final bio = data['bio'] as String; final profilePicUrl = data['profilePicUrl'] as String; setState(() { _userName = username; _emailAddress = emailAdd; _country = country; _bio = bio; _profileUrl = profilePicUrl; }); } }); } void _retrieveFriends() { final friendsDb = FirebaseDatabase.instance .ref() .child('users') .child(uid) .child(&quot;friends&quot;); _friendsStream = friendsDb.onValue.listen((event) { if (event.snapshot.exists) { final data = new Map&lt;dynamic, dynamic&gt;.from( event.snapshot.value as Map&lt;dynamic, dynamic&gt;); theirFriends.clear(); data.forEach((key, value) { friendsDb.child(key).onValue.listen((event) { final acc = new Map&lt;dynamic, dynamic&gt;.from( event.snapshot.value as Map&lt;dynamic, dynamic&gt;); final userID = acc['userID'] as String; theirFriends.add(userID); }); }); } }); } @override Widget build(BuildContext context) { return userCardContent(); } Container userCardContent() { return new Container( child: ClipOval( child: SizedBox( width: 110, height: 110, child: (_profileUrl != null) ? Image.network(_profileUrl, fit: BoxFit.cover) : Image.asset( 'assets/Blank-Avatar.png', fit: BoxFit.cover, )), ), ); } @override void deactivate() { _userStream.cancel(); _friendsStream.cancel(); super.deactivate(); } } </code></pre>
3
2,905
Make image of slider fit 100% parent container
<p>I have an <code>slider</code> with Bootstrap. In the <code>XL</code> version shows good, but when you resize the Window and the right <code>container</code> of text grow his <code>height</code>, the image didn't fit the <code>parent container</code> to adapt his <code>height</code> to make the same height that the <code>container</code> text. You can see an live example <a href="http://residenciarucab.es/rucab/" rel="nofollow noreferrer">here</a>, in the middle section of the page.</p> <p>So, in the XL version:</p> <p><a href="https://i.stack.imgur.com/5LYdQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5LYdQ.png" alt="enter image description here"></a></p> <p>But if you resize the <code>width</code> of the Window, the container text's <code>height</code> grow, not happens the same <code>with</code> the image of the slider, happening that:</p> <p><a href="https://i.stack.imgur.com/OZI3L.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OZI3L.png" alt="enter image description here"></a></p> <p>Now the code:</p> <pre><code> &lt;div class="container-fluid mejores-instalaciones"&gt; &lt;div class="row m-0"&gt; &lt;div class="col-lg-9 col-md-12 col-sm-12 col-12 no-padding"&gt; &lt;div id="carouselExampleControls2" class="carousel slide" data-ride="carousel"&gt; &lt;div class="carousel-inner"&gt; &lt;div class="carousel-item active"&gt; &lt;img class="d-block w-100" src="img/mejores-instalaciones/slider/slider-mejores-instalaciones-1.jpg" alt="Niñas haciendo yoga" title="Niñas haciendo yoga"&gt; &lt;/div&gt; &lt;div class="carousel-item"&gt; &lt;img class="d-block w-100" src="img/mejores-instalaciones/slider/slider-mejores-instalaciones-2.jpg" alt="Jugando al tenis" title="Jugando al tenis"&gt; &lt;/div&gt; &lt;div class="carousel-item"&gt; &lt;img class="d-block w-100" src="img/mejores-instalaciones/slider/slider-mejores-instalaciones-3.jpg" alt="El comedor" title="El comedor"&gt; &lt;/div&gt; &lt;div class="carousel-item"&gt; &lt;img class="d-block w-100" src="img/mejores-instalaciones/slider/slider-mejores-instalaciones-4.jpg" alt="La entrada" title="La entrada"&gt; &lt;/div&gt; &lt;div class="carousel-item"&gt; &lt;img class="d-block w-100" src="img/mejores-instalaciones/slider/slider-mejores-instalaciones-5.jpg" alt="La biblioteca" title="La biblioteca"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-lg-3 col-md-12 col-sm-12 col-12"&gt; &lt;h1 class="desc text-right"&gt;LAS MEJORES INSTALACIONES DE EXTREMADURA&lt;/h1&gt; &lt;p class="home-text-p text-right"&gt;La RUCAB es un referente en Extremadura desde hace 32 años, cuanta con el mayor numero de plazas, un total de 205, repartidas en 36 habitaciones dobles, 132 habitaciones individuales y una habitación adaptada. La construcción se extiende por una amplia zona ajardinada, con seis edificios o núcleos residenciales, además de los edificios de las zonas comunes. El total de superficie construida es de 8.492 m².&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
3
1,317
OpenSSL EVP_DecryptFinal_ex returns "wrong final block length" error when decrypting a file
<p>I am using the <code>EVP Symmetric Encryption and Decryption</code> algorithm to encrypt and decrypt a file of text.</p> <p>The encryption works file, a new encrypted file is generated, but when I try to decrypt the file back it always crashes when <code>EVP_DecryptFinal_ex</code> is called the first time.</p> <p>I am using two Visual Studio projects: one for encryption and one for decryption.<br> The libraries I am using I presumed they are build in DEBUG mode (because they have the .pdb files), so that is how my project is also build. (if I choose release mode, the compiler cannot find the openssl include header anymore).</p> <p>This is the error I get: </p> <pre><code>digital envelope routines:EVP_DecryptFinal_ex:wrong final block length </code></pre> <p>I am using the C++11 version, here is my code:</p> <pre><code>void Cipher::Encrypt(const byte key[KEY_SIZE], const byte iv[BLOCK_SIZE], const secure_string&amp; ptext, secure_string&amp; ctext) { EVP_CIPHER_CTX_free_ptr ctx(EVP_CIPHER_CTX_new(), ::EVP_CIPHER_CTX_free); int rc = EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_cbc(), NULL, key, iv); if (rc != 1) throw std::runtime_error("EVP_EncryptInit_ex failed"); // Recovered text expands upto BLOCK_SIZE ctext.resize(ptext.size() + BLOCK_SIZE); int out_len1 = (int)ctext.size(); rc = EVP_EncryptUpdate(ctx.get(), (byte*)&amp;ctext[0], &amp;out_len1, (const byte*)&amp;ptext[0], (int)ptext.size()); if (rc != 1) throw std::runtime_error("EVP_EncryptUpdate failed"); int out_len2 = (int)ctext.size() - out_len1; rc = EVP_EncryptFinal_ex(ctx.get(), (byte*)&amp;ctext[0] + out_len1, &amp;out_len2); if (rc != 1) throw std::runtime_error("EVP_EncryptFinal_ex failed"); // Set cipher text size now that we know it ctext.resize(out_len1 + out_len2); } void Cipher::Decrypt(const byte key[KEY_SIZE], const byte iv[BLOCK_SIZE], const secure_string&amp; ctext, secure_string&amp; rtext) { EVP_CIPHER_CTX_free_ptr ctx(EVP_CIPHER_CTX_new(), ::EVP_CIPHER_CTX_free); int rc = EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_cbc(), NULL, key, iv); if (rc != 1) throw std::runtime_error("EVP_DecryptInit_ex failed"); // Recovered text contracts upto BLOCK_SIZEB rtext.resize(ctext.size()); int out_len1 = (int)rtext.size(); rc = EVP_DecryptUpdate(ctx.get(), (byte*)&amp;rtext[0], &amp;out_len1, (const byte*)&amp;ctext[0], (int)ctext.size()); if (rc != 1) throw std::runtime_error("EVP_DecryptUpdate failed"); int out_len2 = (int)rtext.size() - out_len1; rc = EVP_DecryptFinal_ex(ctx.get(), (byte*)&amp;rtext[0] + out_len1, &amp;out_len2); if (rc != 1) { ERR_print_errors_fp(stderr); throw std::runtime_error("EVP_DecryptFinal_ex failed"); } // Set recovered text size now that we know it rtext.resize(out_len1 + out_len2); } int main(int argc, char* argv[]) { // Load the necessary cipher EVP_add_cipher(EVP_aes_256_cbc()); // create Cipher object Cipher cipher; ifstream f("d:/temp.YML"); ofstream out("d:/tempDecrypt.YML"); byte key[KEY_SIZE] = {1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2}; byte iv[BLOCK_SIZE] = {1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6}; //cipher.gen_params(key, iv); secure_string line; secure_string temp; while (getline(f, line)) { cipher.Decrypt(key, iv, line, temp); std::cout &lt;&lt; temp &lt;&lt; std::endl; out &lt;&lt; temp; } OPENSSL_cleanse(key, KEY_SIZE); OPENSSL_cleanse(iv, BLOCK_SIZE); return 0; } </code></pre> <p>I also read that it could be a padding issue, not sure if that is the case and what should I do. I am not that good with encryption. </p> <p>Any pointers on how to proceed further would be welcomed. If you need more information let me know.</p>
3
1,627
Shell Script to find JPG and MOV files
<p><strong>Background</strong></p> <p>iPhone has live photo's, i thought i could use VLC on Windows or some iPhone app to take a still of the desired frame. Long story short, you can but the quality of the image as well as the resolution is drastically lowered. So i gave up on this.</p> <p><strong>Problem</strong></p> <p>I have actual movie files hidden along side the Live Photo's</p> <p><strong>My Goal</strong></p> <p>Using cygwin to run a bash shell script to iterate through 0000 to 9999 and find all JPG and MOV files that have the same name ONLY.</p> <p><strong>Problem</strong></p> <p>I am having issues with the <code>regex</code></p> <p>I tried <code>ls | grep -E &quot;IMG_0016\.(JPG|MOV)&quot;</code></p> <p>I need a bash script that will return true if it finds <strong>both</strong> a jpg and mov file for the given filename. Is this doable in a one liner? Can anyone give me some ideas on how to make the above bash command more robust?</p> <p>It finds both but how do i say, okay, good job, you have both, now do the following with those two files.</p> <p><strong>EDIT</strong></p> <h1>!/bin/bash</h1> <pre><code>for i in $(seq -f &quot;%04g&quot; 0 20) do FILENAME=&quot;IMG_$i&quot; #echo &quot;$FILENAME&quot; var=$(ls -l | grep &quot;$FILENAME&quot; | grep -E &quot;(JPG|MOV)&quot; | wc -l) if [ &quot;$var&quot; == 2 ] ; then echo we found both for $FILENAME echo $var fi done </code></pre> <p><strong>Output</strong></p> <pre><code>we found both for IMG_0018 2 we found both for IMG_0019 2 </code></pre> <p><strong>EXPECTED</strong></p> <p>files in directory are:</p> <ul> <li>IMG_0016.JPG</li> <li>IMG_0018.JPG</li> <li>IMG_0018.MOV</li> <li>IMG_0019.JPG</li> <li>IMG_0019.MOV</li> </ul> <p><strong>COMMENT</strong></p> <p>This is good in the sense that it looks for only 2 files but there has to be a better way to say find <strong>ONE</strong> JPG and <strong>ONE</strong> MOV??</p> <p><strong>EDIT 2</strong></p> <pre><code>#!/bin/bash for i in $(seq -f &quot;%04g&quot; 0 20) do FILENAME=&quot;IMG_$i&quot; #echo &quot;$FILENAME&quot; var=$(ls -l | grep &quot;$FILENAME&quot; | grep -E &quot;(JPG|MOV)&quot; | wc -l) #echo $var if [ &quot;$var&quot; == 2 ] ; then #echo we found both for $FILENAME var=$(ls -l | grep &quot;$FILENAME&quot; | grep -E JPG | wc -l) if [ &quot;$var&quot; == 1 ] ; then var=$(ls -l | grep &quot;$FILENAME&quot; | grep -E MOV | wc -l) if [ &quot;$var&quot; == 1 ] ; then mv &quot;D:\Mike\Pictures\TEST\\$FILENAME.JPG&quot; &quot;D:\Mike\Pictures\TEST\MATCH\\$FILENAME.JPG&quot; mv &quot;D:\Mike\Pictures\TEST\\$FILENAME.MOV&quot; &quot;D:\Mike\Pictures\TEST\MATCH\\$FILENAME.MOV&quot; fi fi fi done </code></pre>
3
1,174
Python CSV: How to extract data with condition from Dataframe, edit the extracted data then put it back into the Dataframe
<p>Sample csv data:</p> <pre><code>ID,AC_Input_Voltage,AC_Input_Current,DC_Output_Voltage,DC_Output_Current,DC_Output_Power,Input_Active_Power,Input_Reactive_Power,Input_Apparent_Power,Line_Frequency,DC_Ref,AC_Ref,Time_Stamp 8301,418,13.2,34.4,136,4673,1,-1,5524.5,0,49,0,22/6/2017 05:11:00 8301,419.3,2.3,0.7,-0.9,-0.6,1,-1,946.2,0,50,0,22/6/2017 05:11:01 8301,417.7,15.2,30.3,196.5,5962,1,-1,6355,0,49,0,22/6/2017 05:11:02 8301,418.7,2.3,0.7,-0.9,-0.6,1,-1,944.7,0,50,0,22/6/2017 05:11:03 8301,419.3,3.4,53.6,10.8,580.2,1,-1,1432.8,0,49,0,22/6/2017 05:11:04 8301,417.7,13.6,30.1,170.4,5122.7,1,-1,5681.8,0,50,0,22/6/2017 05:11:05 8301,418,11.5,41.2,105,4328.2,1,-1,4796.9,0,49,0,22/6/2017 05:11:07 8301,419.7,2.3,0.8,-0.9,-0.7,1,-1,946.9,0,51,0,22/6/2017 05:11:08 8301,419.7,2.3,40.6,-0.7,-27.9,1,-1,974,0,49,0,22/6/2017 05:11:09 8301,417.4,14.9,30.4,194.4,5903.8,1,-1,6215.4,0,51,0,22/6/2017 05:11:10 8301,417.7,14.7,30.5,186.2,5682.9,1,-1,6139.5,0,49,0,22/6/2017 05:11:11 8301,418,12,31.5,141.5,4456.9,1,-1,5012.5,0,51,0,22/6/2017 05:11:12 8301,419,2.3,0.7,-1.4,-0.9,1,-1,945.4,0,49,0,22/6/2017 05:11:13 8301,419,2.3,0.7,-0.9,-0.6,1,-1,945.4,0,50,0,22/6/2017 05:11:14 8301,419.7,2.3,0.8,-0.9,-0.7,1,-1,946.9,0,50,0,22/6/2017 05:11:15 8301,419,2.3,0.7,-0.9,-0.6,1,-1,945.4,0,49,0,22/6/2017 05:11:16 8301,419,2.3,32.9,-0.2,-5.7,1,-1,972.4,0,51,0,22/6/2017 05:11:17 8301,419.3,2.3,50.3,0.3,17.3,1,-1,973.2,0,49,0,22/6/2017 05:11:18 8301,417.4,15.2,30.5,197.4,6010.5,1,-1,6350,0,50,0,22/6/2017 05:11:19 8301,418.7,2.3,0.9,-0.9,-0.7,1,-1,944.7,0,49,0,22/6/2017 05:11:20 8301,419,2.3,42.9,-0.2,-7.4,1,-1,972.4,0,50,0,22/6/2017 05:11:21 8301,417.4,13.9,30.4,180,5477.6,1,-1,5811.8,0,49,0,22/6/2017 05:11:22 8301,419.7,2.3,0.9,-0.9,-0.8,1,-1,946.9,0,50,0,22/6/2017 05:11:23 8301,418.7,2.3,0.7,-0.9,-0.6,1,-1,944.7,0,50,0,22/6/2017 05:11:24 8301,418.3,2.3,0.6,-0.9,-0.5,1,-1,943.9,0,49,0,22/6/2017 05:11:25 </code></pre> <p>I've tried the following code and manage to edit the data then put them into a new dataframe( <code>df_filter2</code> ):</p> <pre><code>import numpy as np from datetime import date,time,datetime import pandas as pd import csv df = pd.read_csv('Data.csv') df["Time_Stamp"] = pd.to_datetime(df["Time_Stamp"]) # convert to Datetime def getMask(start,end): mask = (df['Time_Stamp'] &gt; start) &amp; (df['Time_Stamp'] &lt;= end) return mask; start = '2017-06-22 05:00:00' end = '2017-06-22 05:20:00' timerange = df.loc[getMask(start, end)] df_filter = timerange[timerange["AC_Input_Current"].le(3.0)] # new df with less or equal to 0.5 #print(df_filter) where = (df_filter[df_filter["Time_Stamp"].diff().dt.total_seconds() &gt; 1] ["Time_Stamp"] - pd.Timedelta("1s")).astype(str).tolist() # Find where diff &gt; 1 second df_filter2 = timerange[timerange["Time_Stamp"].isin(where)] # Create new df with those #print(df_filter2) df_filter2["AC_Input_Current"] = 0.0 # Set c1 to 0.0 #display spikes ( high possibility of data being a spike ) for index, row in df_filter2.iterrows(): values = row.astype(str).tolist() print(','.join(values)) </code></pre> <p><strong>Output:</strong> <em>Note</em>: The edited rows below is in the dataframe <code>df_filter2</code> ..</p> <pre><code>8301,418.0,0.0,34.4,136.0,4673.0,1,-1,5524.5,0,49,0,2017-06-22 05:11:00 8301,417.7,0.0,30.3,196.5,5962.0,1,-1,6355.0,0,49,0,2017-06-22 05:11:02 8301,418.0,0.0,41.2,105.0,4328.2,1,-1,4796.9,0,49,0,2017-06-22 05:11:07 8301,418.0,0.0,31.5,141.5,4456.9,1,-1,5012.5,0,51,0,2017-06-22 05:11:12 8301,417.4,0.0,30.5,197.4,6010.5,1,-1,6350.0,0,50,0,2017-06-22 05:11:19 8301,417.4,0.0,30.4,180.0,5477.6,1,-1,5811.8,0,49,0,2017-06-22 05:11:22 </code></pre> <p>What I want is to put back the output ( from <code>df_filter2</code> ) into the main dataframe <code>df</code>, replacing the rows from <code>df</code> with the same <code>Time_Stamp</code>, with the rows from <code>df_filter2</code>. How do I do this? </p>
3
2,216
Android client server won't show object
<p>I made simple Client server to android. I have problem when I send an object from server to the client. The object is received ok and when I check the log, it shows me the the object was sent successfully.</p> <p>The problem occurs when I'm trying to get this object and put it in my <code>ListView</code> adapter. The adapter works, I checked it with a random <code>ArrayList</code> I created. My issue is when I'm trying to to put the values of <code>AsyncTask</code> in my adapter.</p> <pre><code>public class RestaurantListFragment extends Fragment { private ArrayList&lt;Resturant&gt; res = new ArrayList&lt;&gt;(); private ListAdapter adapter; private Firebase restRef = new Firebase("https://restmeup.firebaseio.com/restaurants"); private Client mClient; // private connectTask t = (connectTask)new connectTask().execute(); public RestaurantListFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); new connectTask().execute(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // new connectTask(getView()).execute(); final View rootView = inflater.inflate(R.layout.fragment_two, container, false); ListView restaurantList = (ListView) rootView.findViewById(R.id.list); adapter = new ListAdapter(getContext(), res, getActivity()); restaurantList.setAdapter(adapter); // connectTask t = (connectTask)new connectTask().execute(); if (mClient != null) { mClient.sendMessage("bar"); } SqlQueriesConverter sql = new SqlQueriesConverter(); sql.getResurantsListQuery("bar"); // sql.getUserFavoritesResturants(accessToken.getUserId()); mClient.sendMessage(sql.getQuery()); // t.setArray(res); mClient.sendMessage("/quit"); mClient.stopClient(); final EditText searchText = (EditText)rootView.findViewById(R.id.searchListView); searchText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { System.out.println("Before---------"); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { String text = searchText.getText().toString().toLowerCase(Locale.getDefault()); adapter.filter(text); adapter.notifyDataSetChanged(); System.out.println("array: " + res.toString()); } @Override public void afterTextChanged(Editable s) { System.out.println("After---------"); } }); // Inflate the layout for this fragment return rootView; } public class connectTask extends AsyncTask&lt;ArrayList&lt;?&gt;,ArrayList&lt;?&gt;,Client&gt; { // private Client mClient; private ArrayList&lt;?&gt; arrayList = new ArrayList&lt;&gt;(); @Override protected Client doInBackground(ArrayList&lt;?&gt;... message) { //we create a Client object and mClient = new Client(new Client.OnMessageReceived() { @Override //here the messageReceived method is implemented public void messageReceived(ArrayList&lt;?&gt; message) { //this method calls the onProgressUpdate // publishProgress(message); onProgressUpdate(message); } }); mClient.run(); return null; } // @Override protected void onProgressUpdate(ArrayList&lt;?&gt;... values) { super.onProgressUpdate(values); ArrayList&lt;?&gt; arr2; if (values[0].get(0) instanceof Resturant){ Log.d("step 1", "1"); if (((ArrayList&lt;?&gt;)values[0]).get(0)instanceof Resturant) { // arr2 = (ArrayList&lt;Resturant&gt;) values[0]; res = (ArrayList&lt;Resturant&gt;) values[0]; adapter.notifyDataSetChanged(); Log.d("array",res.toString()); } } if (values[0].get(0)instanceof Review){ arr2 = (ArrayList&lt;Review&gt;) values[0]; } if (values[0].get(0)instanceof UserFavorites){ arr2 = (ArrayList&lt;Review&gt;) values[0]; Log.d("step 2", "2"); } } } } </code></pre>
3
2,111
Properly echo a bunch of CSS options using PHP?
<p>Consider a following function with <b>one option</b> echoed out:</p> <pre><code>function dynamic_options() { $getheadercolor = get_header_textcolor(); $options_social = get_option('sandbox_theme_social_options'); $wrapper_background_color = get_option('wrapper_background_color'); if($getheadercolor !='blank'){ echo '&lt;style type="text/css"&gt;'; } if($getheadercolor !='blank') { echo "\n"."#header a{ color:#$getheadercolor; }"; }//End If $getheadercolor if($getheadercolor !='blank'){ echo "\n".'&lt;/style&gt;'; } }// End Dynamic options </code></pre> <p>It outputs something like this into my header (<i>it works flawlessly and does exactly as I want</i>)</p> <pre><code>&lt;style type="text/css"&gt; #header a{ color:#30409b; } &lt;/style&gt; </code></pre> <p>Now here is the problem: This function will not have only one option but a <b>bunch of options</b> (20-30 options). So to illustrate my point let's say that for now my function will have <b>five</b> options. So it will look like this:</p> <pre><code>function dynamic_options() { $getheadercolor = get_header_textcolor(); $options_social = get_option('sandbox_theme_social_options'); $wrapper_background_color = get_option('wrapper_background_color'); //My main "problem" is an IF Statement below because it will look like a mess //With 20 options or more and with all those OR inside it... if($getheadercolor !='blank' || $sitecolor !='' || $textcolor !='' || $backgroundcolor !='' || $menucolor !=''){ echo '&lt;style type="text/css"&gt;'; } if($getheadercolor !='blank') { echo "\n"."#header a{ color:#$getheadercolor; }"; }//End If $getheadercolor if($sitecolor !='blank') { echo "\n"."#wrapper{ background-color:#$sitecolor; }"; }//End If $sitecolor if($textcolor !='blank') { echo "\n".".entry p{ color:#$textcolor; }"; }//End If $textcolor if($backgroundcolor !='blank') { echo "\n"."body{ background-color:#$backgroundcolor; }"; }//End If $backgroundcolor if($menucolor !='blank') { echo "\n".".nav{ background-color:#$menucolor; }"; }//End If $menucolor //So to even close my style tag i need a bunch of those statments if($getheadercolor !='blank' || $sitecolor !='' || $textcolor !='' || $backgroundcolor !='' || $menucolor !=''){ echo "\n".'&lt;/style&gt;'; } </code></pre> <p>So my function above <i>will work</i> but this part <br/><code>if($getheadercolor !='blank' || $sitecolor !='' || $textcolor !='' || $backgroundcolor !='' || $menucolor !='')</code> just seem wrong to me. <br/>Because this IF statement will have more than <b>20</b> options I am afraid that my code will be Slow and Inefficient.<br/>My PHP Force is not strong... so my only (not ideal) solution is to simply omit those two IF statement like so: </p> <pre><code> function dynamic_options() { $getheadercolor = get_header_textcolor(); $options_social = get_option('sandbox_theme_social_options'); $wrapper_background_color = get_option('wrapper_background_color'); echo '&lt;style type="text/css"&gt;'; if($getheadercolor !='blank') { echo "\n"."#header a{ color:#$getheadercolor; }"; }//End If $getheadercolor if($sitecolor !='blank') { echo "\n"."#wrapper{ background-color:#$sitecolor; }"; }//End If $sitecolor if($textcolor !='blank') { echo "\n".".entry p{ color:#$textcolor; }"; }//End If $textcolor if($backgroundcolor !='blank') { echo "\n"."body{ background-color:#$backgroundcolor; }"; }//End If $backgroundcolor if($menucolor !='blank') { echo "\n".".nav{ background-color:#$menucolor; }"; }//End If $menucolor echo "\n".'&lt;/style&gt;'; }// End Dynamic options </code></pre> <p>Now my code <b>without</b> those IF statements <i>will work too</i> but now problem is, if there are no options my function will still echo an <b>empty</b> CSS style tag inside my header:<code>&lt;style type="text/css"&gt;&lt;/style&gt;</code> and that is something I don't want. <br/><br/>Can somebody give me an example or advice for making this function work better? <br/><br/>P.S. I am considering myself as PHP <i>noob</i> so if someone can give me a nice and clear advice or example it would be much appreciated! Thank You!!! </p>
3
1,773
TCPDF doesn't show a static Google Map
<p>When I generate a PDF content is displayed but not the image. Why?</p> <p>I think the PDF is generated before the image is loaded. Is there any way to slow down the operation?</p> <pre><code>&lt;?php // Include the main TCPDF library (search for installation path). include('tcpdf/tcpdf.php'); // Variables globals $ID = ""; // create new PDF document $pdf = new TCPDF('P', PDF_UNIT, 'A4', true, 'UTF-8', false); // set document information $pdf-&gt;SetCreator (PDF_CREATOR); $pdf-&gt;SetAuthor ('Disseny de bases de dades'); $pdf-&gt;SetTitle ('Llistat dagencies de la ciutat de '); $pdf-&gt;SetSubject ('Exemple de creació de pdf amb intercacció amb una base de dades'); $pdf-&gt;SetKeywords('TCPDF, PDF, example, test, guide'); // add a page $pdf-&gt;AddPage(); // Amb la funció empty verifiquem si l'usuari arriva a la pàgina després d'introduir les dades al formulari o bé si acaba de // carregar la pàgina i encara no ha omplert cap dada al formulari. if (!empty($_GET)) { // La funció "isset" s'utilitza per a saber si una variable ha estat definida. if(isset($_GET['ID'])) { $ID= $_GET['ID']; } } //El tercer pas es realitzar la connexió a la base de dades. // Ens conectem a la base de dades. $localhost = "localhost"; $mysqli = new mysqli( $localhost, $user, $pwd, $database); $mysqli-&gt;set_charset("utf8"); $busqueda = "SELECT A.nombre AS nombre, A.fecha_instalacion AS instalacion, A.descripcion AS descripcion, A.latitud AS latitud, A.longitud AS longitud, T.Nombre AS nombretipo FROM Atraccion AS A INNER JOIN R_clasificacion ON R_clasificacion.ID_Atraccion=A.ID INNER JOIN Tipos AS T ON R_clasificacion.ID_Tipos=T.ID WHERE A.ID= '".$ID."' "; if ($result = $mysqli-&gt;query($busqueda)) { if ($result-&gt;num_rows &gt; 0) { while($row = $result-&gt;fetch_array(MYSQLI_ASSOC)) { $nombre = $row['nombre']; $fecha = $row['instalacion']; $descripcion = $row['descripcion']; $nombretipo = $row['nombretipo']; $longitud = $row['longitud']; $latitud = $row['latitud']; } } } // set some text to print $html = " &lt;style&gt; @import url(http://fonts.googleapis.com/css?family=Muli:400italic); #titulos {text-align: left; font-family: 'Muli', sans-serif;} #imagenes {float: right; margin: 0 0 0 5%;} #textos { color: red;text-align: justify; margin-right: 5em;} #contenedor {margin: 3% 7% 3% 7%;}; &lt;/style&gt;"; $html .=" &lt;html lang=\"es\"&gt; &lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /&gt; &lt;head&gt; &lt;title&gt;Página a imprimir&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id=\"contenedor\"&gt; &lt;div id=\"titulos\"&gt;&lt;h1&gt;".$nombre."&lt;/h1&gt;&lt;/div&gt; </code></pre> <p>here it is where I add the link to the image:</p> <pre><code> &lt;div id=\"imagenes\"&gt;"; $html .=" &lt;div&gt;&lt;img src=\"https://maps.googleapis.com/maps/api/staticmap?center=41.088867,1.156965&amp;zoom=15&amp;size=585x300&amp;maptype=roadmap&amp;markers=color:red%7Clabel:C%7C".$latitud.",".$longitud."\" height=\"200\" width=\"350\"/&gt;&lt;/div&gt;"; $html .=" </code></pre> <p>The rest of PDF content (shown without problems):</p> <pre><code>&lt;div&gt;&lt;img src=\"imagenes/".$ID.".jpg\" height=\"200\" width=\"350\"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div id=\"textos\"&gt; &lt;p&gt;Fecha de inauguración: ".$fecha."&lt;/p&gt; &lt;p&gt;Ubicado en el parque en: ".$nombretipo."&lt;/p&gt; &lt;P&gt;".$descripcion."&lt;/P&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;"; $pdf-&gt;writeHTML($html, true, 0, true, 0); $pdf-&gt;lastPage(); $pdf-&gt;Output('htmlout.pdf', 'I'); ?&gt; </code></pre>
3
1,733
how to show pdf in android emulator
<p>i want to show pdf in emulator.the following code i use.</p> <pre><code>public class PdfActivity extends Activity { public void onCreate(Bundle savedInstanceState) { URL url; Button btn; super.onCreate(savedInstanceState); setContentView(R.layout.main); System.setProperty("http.proxyHost","192.168.0.2"); System.setProperty("http.proxyPort","8080"); btn=(Button)findViewById(R.id.press); try { //url=new URL("http://litofinter.es.milfoil.arvixe.com/PDF/Book6.pdf"); }catch(Exception e) { e.printStackTrace(); } btn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Uri uri = Uri.parse("http://litofinter.es.milfoil.arvixe.com/PDF/Book6.pdf"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } }); } } </code></pre> <p>But it show me errors that is my logcat-</p> <pre><code>09-28 13:16:24.697: ERROR/WindowManager(283): Activity com.android.browser.BrowserActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@44f601d8 that was originally added here 09-28 13:16:24.697: ERROR/WindowManager(283): android.view.WindowLeaked: Activity com.android.browser.BrowserActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@44f601d8 that was originally added here 09-28 13:16:24.697: ERROR/WindowManager(283): at android.view.ViewRoot.&lt;init&gt;(ViewRoot.java:247) 09-28 13:16:24.697: ERROR/WindowManager(283): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148) 09-28 13:16:24.697: ERROR/WindowManager(283): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91) 09-28 13:16:24.697: ERROR/WindowManager(283): at android.view.Window$LocalWindowManager.addView(Window.java:424) 09-28 13:16:24.697: ERROR/WindowManager(283): at android.app.Dialog.show(Dialog.java:241) 09-28 13:16:24.697: ERROR/WindowManager(283): at android.app.AlertDialog$Builder.show(AlertDialog.java:802) 09-28 13:16:24.697: ERROR/WindowManager(283): at com.android.browser.BrowserActivity.onDownloadStartNoStream(BrowserActivity.java:2871) 09-28 13:16:24.697: ERROR/WindowManager(283): at com.android.browser.BrowserActivity.onDownloadStart(BrowserActivity.java:2808) 09-28 13:16:24.697: ERROR/WindowManager(283): at com.android.browser.Tab$4.onDownloadStart(Tab.java:1306) 09-28 13:16:24.697: ERROR/WindowManager(283): at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:387) 09-28 13:16:24.697: ERROR/WindowManager(283): at android.os.Handler.dispatchMessage(Handler.java:99) 09-28 13:16:24.697: ERROR/WindowManager(283): at android.os.Looper.loop(Looper.java:123) 09-28 13:16:24.697: ERROR/WindowManager(283): at android.app.ActivityThread.main(ActivityThread.java:4627) 09-28 13:16:24.697: ERROR/WindowManager(283): at java.lang.reflect.Method.invokeNative(Native Method) 09-28 13:16:24.697: ERROR/WindowManager(283): at java.lang.reflect.Method.invoke(Method.java:521) 09-28 13:16:24.697: ERROR/WindowManager(283): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 09-28 13:16:24.697: ERROR/WindowManager(283): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 09-28 13:16:24.697: ERROR/WindowManager(283): at dalvik.system.NativeStart.main(Native Method) </code></pre>
3
1,338
Laravel controller returning index view instead of json response
<p>I am using apache2 and php artisan serve command to test my project.</p> <p>Have the next controller:</p> <pre><code>&lt;?php // file: Http\Controllers\AuthCtrl.php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\User; // &lt;-- use Illuminate\Support\Facades\Auth; class AuthCtrl extends Controller { public function login(Request $request) { $rules = [ 'email' =&gt; 'required|exists:users', 'password' =&gt; 'required' ]; $request-&gt;validate($rules); $data = [ 'email' =&gt; $request-&gt;get('email'), 'password' =&gt; $request-&gt;get('password') ]; if( Auth::attempt($data) ) { $user = Auth::user(); // the $user-&gt;createToken('appName')-&gt;accessToken generates the JWT token that we can use return response()-&gt;json([ 'user' =&gt; $user, // &lt;- we're sending the user info for frontend usage 'token' =&gt; $user-&gt;createToken('teltask')-&gt;accessToken, // &lt;- token is generated and sent back to the front end 'success' =&gt; true ]); } else { return response()-&gt;json([ 'success' =&gt; false, 'msg' =&gt; 'Credenciales erroneas.' ]); } } } </code></pre> <p>And a simple mock index.php that does an ajax call with the following js:</p> <pre><code>function ExecLogin() { $.ajax({ method: &quot;POST&quot;, url: &quot;http://127.0.0.1:8000/api/login&quot;, data : {email : &quot;fsd@gmail.com&quot;, password: &quot;mypass&quot;} }).done( function(data, status) { if(data.success == true) { localStorage.setItem('appname_token', data.token); // the following part makes sure that all the requests made later with jqXHR will automatically have this header. $( document ).ajaxSend(function( event, jqxhr, settings ) { jqxhr.setRequestHeader('Authorization', &quot;Bearer &quot; + data.token); }); } else { alert(data.msg); } }).fail(function(error){ // handle the error }); } </code></pre> <p>As you can see, when the code enters this part, (when the user authenticated OK), It returns a JSON response allright:</p> <pre><code>$user = Auth::user(); // the $user-&gt;createToken('appName')-&gt;accessToken generates the JWT token that we can use return response()-&gt;json([ 'user' =&gt; $user, // &lt;- we're sending the user info for frontend usage 'token' =&gt; $user-&gt;createToken('teltask')-&gt;accessToken, // &lt;- token is generated and sent back to the front end 'success' =&gt; true ]); </code></pre> <p>But when it did not authenticated OK, it enters at this part, but the response is the index.php text/html, not a json response as I defined:</p> <pre><code>return response()-&gt;json([ 'success' =&gt; false, 'msg' =&gt; 'Credenciales erroneas.' ]); </code></pre> <p>I am recieving the following string on the data object of the ajax call:</p> <pre><code>&quot;&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt; &lt;title&gt;Laravel&lt;/title&gt; &lt;!-- Fonts --&gt; &lt;link href=&quot;https://fonts.googleapis.com/css?family=Nunito:200,600&quot; rel=&quot;stylesheet&quot;&gt; &lt;!-- Styles --&gt; &lt;style&gt; html, body { background-color: #fff; color: #636b6f; font-family: 'Nunito', sans-serif; font-weight: 200; height: 100vh; margin: 0; } .full-height { height: 100vh; } .flex-center { align-items: center; display: flex; justify-content: center; } .position-ref { position: relative; } .top-right { position: absolute; right: 10px; top: 18px; } .content { text-align: center; } .title { font-size: 84px; } .links &gt; a { color: #636b6f; padding: 0 25px; font-size: 13px; font-weight: 600; letter-spacing: .1rem; text-decoration: none; text-transform: uppercase; } .m-b-md { margin-bottom: 30px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class=&quot;flex-center position-ref full-height&quot;&gt; &lt;div class=&quot;top-right links&quot;&gt; &lt;a href=&quot;http://127.0.0.1:8000/login&quot;&gt;Login&lt;/a&gt; &lt;a href=&quot;http://127.0.0.1:8000/register&quot;&gt;Register&lt;/a&gt; &lt;/div&gt; &lt;div class=&quot;content&quot;&gt; &lt;div class=&quot;title m-b-md&quot;&gt; Laravel &lt;/div&gt; &lt;div class=&quot;links&quot;&gt; &lt;a href=&quot;https://laravel.com/docs&quot;&gt;Docs&lt;/a&gt; &lt;a href=&quot;https://laracasts.com&quot;&gt;Laracasts&lt;/a&gt; &lt;a href=&quot;https://laravel-news.com&quot;&gt;News&lt;/a&gt; &lt;a href=&quot;https://blog.laravel.com&quot;&gt;Blog&lt;/a&gt; &lt;a href=&quot;https://nova.laravel.com&quot;&gt;Nova&lt;/a&gt; &lt;a href=&quot;https://forge.laravel.com&quot;&gt;Forge&lt;/a&gt; &lt;a href=&quot;https://vapor.laravel.com&quot;&gt;Vapor&lt;/a&gt; &lt;a href=&quot;https://github.com/laravel/laravel&quot;&gt;GitHub&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; &quot; </code></pre> <p>Am I missing something important here?</p> <p>Authenticate Middleware looks like this:</p> <pre><code>&lt;?php namespace App\Http\Middleware; use Illuminate\Auth\Middleware\Authenticate as Middleware; class Authenticate extends Middleware { /** * Get the path the user should be redirected to when they are not authenticated. * * @param \Illuminate\Http\Request $request * @return string|null */ protected function redirectTo($request) { if (! $request-&gt;expectsJson() ) { return route('login'); } } } </code></pre>
3
4,174
Access/ Excel integration:How to avoid conflicts between simultaneous users?
<p>I'm developing an excel tool which connects to an Access database through VBA, and data is transferred between excel and the DB upon user requests. Each user have his own version of the excel workbook, which connects to the central db. In most cases this works fine, but i have discovered some conflicts when two users are trying to connect at the same time, causing one of the users excel/VBA to crash without any VBA errorcode. </p> <p>I suspect this is caused by the database the connection somehow being interrupted by the second user. </p> <p>So my question is: Is there a way to "lock" the connection when the first user has connected and then knowing the db is in use when the second user tries to connect, so his request can be aborted/delayed, without excel crashing? </p> <p>I have included the code for one of the transactions, which moves data from excel to the database. </p> <pre class="lang-vb prettyprint-override"><code>Public Sub ExportToAccess() ''''Establish connection to DB Set cn = New ADODB.Connection cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" &amp; dbPath &amp; ";Persist Security Info=False;" cn.Open Set rstDbTable = New ADODB.Recordset With rstDbTable .Open "AllCapacity", cn, adOpenKeyset, adLockPessimistic, adCmdTable End With ''''Move data'''' 'one area at the time For area = 0 To UBound(cap_areas) toDbArray = sh_capacity.Range(cap_areas(area)) 'Save the range in question ot the db array. starts at 1 'MsgBox (toDbArray(1, 1)) For i = 1 To UBound(toDbArray, 1) 'for all rows rstDbTable.Filter = "CapArea = '" &amp; NamesArea(area) &amp; "'" _ &amp; " AND Week = '" &amp; week &amp; "'" _ &amp; " AND AreaWeekID = '" &amp; i &amp; "'" If rstDbTable.EOF Then 'Check if its empty and then create new records MsgBox ("Could not find row in DB. Script is ending. CapArea =" &amp; NamesArea(area) &amp; ". AreaWeekId = " &amp; i) Stop ' Debugger GoTo EndOfCode 'rstDbTable.AddNew 'Use if we need to add new row Else 'rstDbTable("AreaWeekID").Value = toDbArray(i, 27) 'rstDbTable("Week").Value = toDbArray(i, 28) 'rstDbTable("CapArea").Value = toDbArray(i, 29) 'start = Timer rstDbTable("MO_DA").Value = toDbArray(i, 2) ' MsgBox (Timer - start) rstDbTable("MO_EV").Value = toDbArray(i, 3) rstDbTable("MO_NI").Value = toDbArray(i, 4) rstDbTable("TU_DA").Value = toDbArray(i, 5) rstDbTable("TU_EV").Value = toDbArray(i, 6) rstDbTable("TU_NI").Value = toDbArray(i, 7) rstDbTable("WE_DA").Value = toDbArray(i, 8) rstDbTable("WE_EV").Value = toDbArray(i, 9) rstDbTable("WE_NI").Value = toDbArray(i, 10) rstDbTable("TH_DA").Value = toDbArray(i, 11) rstDbTable("TH_EV").Value = toDbArray(i, 12) rstDbTable("TH_NI").Value = toDbArray(i, 13) rstDbTable("FR_DA").Value = toDbArray(i, 14) rstDbTable("FR_EV").Value = toDbArray(i, 15) rstDbTable("FR_NI").Value = toDbArray(i, 16) rstDbTable("SA_DA").Value = toDbArray(i, 17) rstDbTable("SA_EV").Value = toDbArray(i, 18) rstDbTable("SA_NI").Value = toDbArray(i, 19) rstDbTable("SU_DA").Value = toDbArray(i, 20) rstDbTable("SU_EV").Value = toDbArray(i, 21) rstDbTable("SU_NI").Value = toDbArray(i, 22) End If rstDbTable.Update Next i Next area EndOfCode: rstDbTable.Close </code></pre>
3
1,663
react-native (js) : generalise a function
<p>I have two functions which I would like to condense into one (with another argument). They are called like so:</p> <pre><code>&lt;ListView automaticallyAdjustContentInsets={false} dataSource={this.state.dataSource_proj} renderRow={this.renderProjRow.bind(this)}/&gt; &lt;ListView automaticallyAdjustContentInsets={false} dataSource={this.state.dataSource_map} renderRow={this.renderMapRow.bind(this)}/&gt; </code></pre> <p>And the functions are:</p> <pre><code>renderProjRow(rowData, sectionID, rowID) { return ( &lt;TouchableHighlight onPress={() =&gt; this.rowProjPressed(rowData.project_name)} underlayColor='#dddddd'&gt; &lt;View&gt; &lt;View style={styles.rowContainer}&gt; &lt;Image source={{uri: 'Letter-' + rowData.project_name.substr(0,1).toUpperCase()}} style={styles.thumb}/&gt; &lt;View style={styles.textContainer}&gt; &lt;Text style={styles.title} numberOfLines={1}&gt;{rowData.project_name}&lt;/Text&gt; &lt;/View&gt; &lt;/View&gt; &lt;View Style={styles.separator}/&gt; &lt;/View&gt; &lt;/TouchableHighlight&gt; ); } renderMapRow(rowData, sectionID, rowID) { return ( &lt;TouchableHighlight onPress={() =&gt; this.rowMapPressed(rowData)} underlayColor='#dddddd'&gt; &lt;View&gt; &lt;View style={styles.rowContainer}&gt; &lt;Image source={{uri: 'Letter-' + rowData.map_name.substr(0,1).toUpperCase()}} style={styles.thumb}/&gt; &lt;View style={styles.textContainer}&gt; &lt;Text style={styles.title} numberOfLines={1}&gt;{rowData.map_name}&lt;/Text&gt; &lt;/View&gt; &lt;/View&gt; &lt;View Style={styles.separator}/&gt; &lt;/View&gt; &lt;/TouchableHighlight&gt; ); } </code></pre> <p>I would like to just have one function: <code>renderRow</code>, which takes <code>rowData.project_name</code> if the data-source is <code>dataSource_proj</code> and <code>rowData.map_name</code> if the data-source is <code>dataSource_map</code>.</p> <p>However, aside from using eval ... I'm not sure how to implement this in a proper way.</p>
3
1,247
Serialising a string which contains backslashes with Json.Net
<p>I am trying to serialise an object which contains a UNC-Windows path to a shared ressource.</p> <p>My code:</p> <pre><code> public class NetworkConnection { public String LocalName { get; private set; } public String RemotePath { get; private set; } public String ResourceType { get; private set; } private NetworkConnection() { LocalName = String.Empty; RemotePath = String.Empty; ResourceType = String.Empty; } public static List&lt;NetworkConnection&gt; getNetworkConnections() { try { List&lt;NetworkConnection&gt; networkConnections = new List&lt;NetworkConnection&gt;(); ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_NetworkConnection"); foreach (var item in searcher.Get()) { NetworkConnection con = new NetworkConnection(); con.LocalName = (string) (item.GetPropertyValue("LocalName") ?? String.Empty); con.RemotePath = (string)(item.GetPropertyValue("RemotePath") ?? String.Empty); Uri uri = new Uri(con.RemotePath); con.RemotePath = uri.AbsoluteUri.Replace("file://", @"\"); con.RemotePath = con.RemotePath.Replace('/', '\\'); con.ResourceType = (string) (item.GetPropertyValue("ResourceType") ?? String.Empty); networkConnections.Add(con); } return networkConnections; } catch (Exception) { return new List&lt;NetworkConnection&gt;(); } } } class PC { public Software.Software Software { get; private set; } public Hardware.Hardware Hardware { get; private set; } public PC() { Software = new Software.Software(); Hardware = new Hardware.Hardware(); } } public class Hardware { public List&lt;NetworkConnection&gt; NetworkConnections { get; private set; } public Hardware() { NetworkConnections = NetworkConnection.getNetworkConnections(); } } //Serialising PC pc = new PC(); using (StreamWriter writer = new StreamWriter("deimama.txt")) { writer.WriteLine(JsonConvert.SerializeObject(pc, Formatting.Indented)); } </code></pre> <p>Output (shortened):</p> <pre><code>\\192.168.1.1\\speech </code></pre> <p>Wanted Output:</p> <pre><code>\\192.168.1.1\speech </code></pre> <p>PS: I tried different ways with string replacing as well</p>
3
1,284
If statement on a sub array of an object
<p>Hope that title made sense but my issue is i have an object with an array like this, this is just 1 from the array as an example</p> <pre><code> object(stdClass)#6 (3) { ["items"]=&gt; array(40) { [0]=&gt; object(stdClass)#7 (22) { ["id"]=&gt; int(46) ["parentId"]=&gt; int(0) ["name"]=&gt; string(22) "Complete monthly wages" ["description"]=&gt; string(294) "Complete monthly wages&lt;span style=""&gt;&lt;/span&gt;&lt;br /&gt;&lt;div&gt;Complete monthly wages&lt;span style=""&gt;&lt;/span&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Complete monthly wages&lt;span style=""&gt;&lt;/span&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Complete monthly wages&lt;span style=""&gt;&lt;/span&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Complete monthly wages&lt;span style=""&gt;&lt;/span&gt;&lt;br /&gt;&lt;/div&gt;" ["tags"]=&gt; string(0) "" ["projectId"]=&gt; int(12) ["ownerId"]=&gt; int(1) ["groupId"]=&gt; int(0) ["startDate"]=&gt; string(19) "2012-09-03T00:00:00" ["priority"]=&gt; int(2) ["progress"]=&gt; float(0) ["status"]=&gt; int(10) ["createdAt"]=&gt; string(19) "2012-09-03T07:35:21" ["updatedAt"]=&gt; string(19) "2012-09-03T07:35:21" ["notifyProjectTeam"]=&gt; bool(false) ["notifyTaskTeam"]=&gt; bool(false) ["notifyClient"]=&gt; bool(false) ["hidden"]=&gt; bool(false) ["flag"]=&gt; int(0) ["hoursDone"]=&gt; float(0) ["estimatedTime"]=&gt; float(0) ["team"]=&gt; object(stdClass)#8 (3) { ["items"]=&gt; array(2) { [0]=&gt; object(stdClass)#9 (1) { ["id"]=&gt; int(2) } [1]=&gt; object(stdClass)#10 (1) { ["id"]=&gt; int(1) } } ["count"]=&gt; int(2) ["total"]=&gt; int(2) } } </code></pre> <p>As we can see it has a team section and this is my focus</p> <pre><code>["team"]=&gt; object(stdClass)#8 (3) { ["items"]=&gt; array(2) { [0]=&gt; object(stdClass)#9 (1) { ["id"]=&gt; int(2) } [1]=&gt; object(stdClass)#10 (1) { ["id"]=&gt; int(1) } } ["count"]=&gt; int(2) ["total"]=&gt; int(2) } } </code></pre> <p>As you can see there is 2 id's in there, 1 and 2, there could be anything up to 30 or so but i cant figure out how to efficently tell it to search the whole array.</p> <p>If i use this it works as long as the Id 1 happens to be the first item in id but thats obviously not always the case. My aim is to search through the object and just run code IF the users ID is in the team array, im new to php and objects in particular so hope someone can point me in the right direction</p> <pre><code>foreach($tasksList-&gt;items as $task_details) { if($task_details-&gt;team-&gt;items-&gt;id === 1) { echo "My Code"; } } </code></pre>
3
1,777
How to connect to Mongo DB in Docker from Scala Play Framework?
<p>I have a Mongo DB Docker container running on <code>192.168.0.229</code>. From another computer, I can access it via:</p> <p><code>&gt; mongo &quot;mongodb://192.168.0.229:27017/test&quot; </code></p> <p>But when I add that configuration string (<code>host=&quot;192.168.0.229&quot;</code>) to my Play Framework app, I get a timeout error:</p> <pre><code>[debug] application - Login Form Success: UserData(larry@gmail.com,testPW) [error] p.a.h.DefaultHttpErrorHandler - ! @7m7kggikl - Internal server error, for (POST) [/] -&gt; play.api.http.HttpErrorHandlerExceptions$$anon$1: Execution exception[[TimeoutException: Future timed out after [30 seconds]]] </code></pre> <p>In the past, the connection was successful with <code>host=&quot;localhost&quot;</code> and even an Atlas cluster (<code>host=&quot;mycluster.gepld.mongodb.net&quot;</code>) for the hostname, so there were no problems connecting previously with the same code. For some reason, Play Framework does not want to connect to this endpoint!</p> <p>Could it be because the hostname is an IP address? Or, maybe Play/ Akka is doing something under the covers to stop the connection (or something to make Mongo/Docker refuse to accept it?)?</p> <p>I'm using this driver:</p> <p><code>&quot;org.mongodb.scala&quot; %% &quot;mongo-scala-driver&quot; % &quot;4.4.0&quot;</code></p> <p>Perhaps I should switch to the Reactive Scala Driver? Any help would be appreciated.</p> <hr /> <p>Clarifications: The Mongo DB Docker container is running on a linux machine on my local network. This container is reachable from within my local network at <code>192.168.0.229</code>. The goal is to set my Play Framework app configuration to point to the DB at this address, so that as long as the Docker container is running, I can develop from any computer on my local network. Currently, I am able to access the container through the mongo shell on any computer:</p> <p><code>&gt; mongo &quot;mongodb://192.168.0.229:27017/test&quot; </code></p> <p>I have a Play Framework app with the following in the <code>Application.conf</code>:</p> <pre><code>datastore { # Dev host: &quot;192.168.0.229&quot; port: 27017 dbname: &quot;test&quot; user: &quot;&quot; password: &quot;&quot; } </code></pre> <p>This data is used in a connection helper file called <code>DataStore.scala</code>:</p> <pre><code>package model.db.mongo import org.mongodb.scala._ import utils.config.AppConfiguration trait DataStore extends AppConfiguration { lazy val dbHost = config.getString(&quot;datastore.host&quot;) lazy val dbPort = config.getInt(&quot;datastore.port&quot;) lazy val dbUser = getConfigString(&quot;datastore.user&quot;, &quot;&quot;) lazy val dbName = getConfigString(&quot;datastore.dbname&quot;, &quot;&quot;) lazy val dbPasswd = getConfigString(&quot;datastore.password&quot;, &quot;&quot;) //MongoDB Atlas Method (Localhost if DB User is empty) val uri: String = s&quot;mongodb+srv://$dbUser:$dbPasswd@$dbHost/$dbName?retryWrites=true&amp;w=majority&quot; //val uri: String = &quot;mongodb+svr://192.168.0.229:27017/?compressors=disabled&amp;gssapiServiceName=mongodb&quot; System.setProperty(&quot;org.mongodb.async.type&quot;, &quot;netty&quot;) val mongoClient: MongoClient = if (getConfigString(&quot;datastore.user&quot;, &quot;&quot;).isEmpty()) MongoClient() else MongoClient(uri) print(mongoClient.toString) print(mongoClient.listDatabaseNames()) val database: MongoDatabase = mongoClient.getDatabase(dbName) def close = mongoClient.close() //Do this when logging out } </code></pre> <p>When you start the app, you open <code>localhost:9000</code> which is simply a login form. When you fill out the data that corresponds with the data in the <code>users</code> collection, the Play app times out:</p> <pre><code>[error] p.a.h.DefaultHttpErrorHandler - ! @7m884abc4 - Internal server error, for (POST) [/] -&gt; play.api.http.HttpErrorHandlerExceptions$$anon$1: Execution exception[[TimeoutException: Future timed out after [30 seconds]]] at play.api.http.HttpErrorHandlerExceptions$.$anonfun$convertToPlayException$2(HttpErrorHandler.scala:381) at scala.Option.map(Option.scala:242) at play.api.http.HttpErrorHandlerExceptions$.convertToPlayException(HttpErrorHandler.scala:380) at play.api.http.HttpErrorHandlerExceptions$.throwableToUsefulException(HttpErrorHandler.scala:373) at play.api.http.DefaultHttpErrorHandler.onServerError(HttpErrorHandler.scala:264) at play.core.server.AkkaHttpServer$$anonfun$2.applyOrElse(AkkaHttpServer.scala:430) at play.core.server.AkkaHttpServer$$anonfun$2.applyOrElse(AkkaHttpServer.scala:422) at scala.concurrent.impl.Promise$Transformation.run(Promise.scala:454) at akka.dispatch.BatchingExecutor$AbstractBatch.processBatch(BatchingExecutor.scala:63) at akka.dispatch.BatchingExecutor$BlockableBatch.$anonfun$run$1(BatchingExecutor.scala:100) Caused by: java.util.concurrent.TimeoutException: Future timed out after [30 seconds] at scala.concurrent.impl.Promise$DefaultPromise.tryAwait0(Promise.scala:212) at scala.concurrent.impl.Promise$DefaultPromise.result(Promise.scala:225) at scala.concurrent.Await$.$anonfun$result$1(package.scala:201) at akka.dispatch.MonitorableThreadFactory$AkkaForkJoinWorkerThread$$anon$3.block(ThreadPoolBuilder.scala:174) at java.base/java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3118) at akka.dispatch.MonitorableThreadFactory$AkkaForkJoinWorkerThread.blockOn(ThreadPoolBuilder.scala:172) at akka.dispatch.BatchingExecutor$BlockableBatch.blockOn(BatchingExecutor.scala:116) at scala.concurrent.Await$.result(package.scala:124) at model.db.mongo.DataHelpers$ImplicitObservable.headResult(DataHelpers.scala:27) at model.db.mongo.DataHelpers$ImplicitObservable.headResult$(DataHelpers.scala:27) </code></pre> <p>The call to the Users collection is defined in <code>UserAccounts.scala</code>:</p> <pre><code>case class UserAccount(_id: String, fullname: String, username: String, password: String) object UserAccount extends DataStore { val logger: Logger = Logger(&quot;database&quot;) //Required for using Case Classes val codecRegistry = fromRegistries(fromProviders(classOf[UserAccount]), DEFAULT_CODEC_REGISTRY) //Using Case Class to get a collection val coll: MongoCollection[UserAccount] = database.withCodecRegistry(codecRegistry).getCollection(&quot;users&quot;) //Using Document to get a collection val listings: MongoCollection[Document] = database.getCollection(&quot;users&quot;) def isValidLogin(username: String, password: String): Boolean = { findUser(username) match { case Some(u: UserAccount) =&gt; if(password.equals(u.password)) { true } else {false } case None =&gt; false } } </code></pre>
3
2,397
Dismiss Rg.Plugins.Popup on scroll down in Xamarin forms
<p>I am using <a href="https://github.com/rotorgames/Rg.Plugins.Popup/issues" rel="nofollow noreferrer">Rg.Plugins.Popup</a> plugin in my xamarin forms app. It is a nice plugin for modal dialogs. However, I am looking to dismiss the dialog when user scrolls down. (Most dialogs in iOS has this behavior of closing with scrolling down).</p> <p>XAML inside Popup page.</p> <p><strong>Option 1</strong></p> <pre><code> &lt;pages:PopupPage xmlns=&quot;http://xamarin.com/schemas/2014/forms&quot; xmlns:x=&quot;http://schemas.microsoft.com/winfx/2009/xaml&quot; xmlns:pages=&quot;clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup&quot; HasSystemPadding=&quot;True&quot; CloseWhenBackgroundIsClicked=&quot;False&quot; x:Name=&quot;MyPage&quot; x:Class=&quot;wQuran.Views.Today.PrayerTimesSettingsPopupPage&quot;&gt; &lt;Frame Style=&quot;{DynamicResource PopupFrame}&quot; VerticalOptions=&quot;FillAndExpand&quot; IsClippedToBounds=&quot;True&quot;&gt; &lt;Grid RowDefinitions=&quot;Auto,*&quot; Style=&quot;{DynamicResource BaseGrid}&quot;&gt; &lt;BoxView Grid.Row=&quot;0&quot; Style=&quot;{DynamicResource PopupTitleBoxView}&quot;/&gt; &lt;Grid Grid.Row=&quot;0&quot; ColumnDefinitions=&quot;*,30&quot; HeightRequest=&quot;40&quot; Padding=&quot;10&quot;&gt; &lt;Label Grid.Column=&quot;0&quot; Text=&quot;{Binding Title}&quot; Style=&quot;{DynamicResource PopupTitleLabel}&quot;/&gt; &lt;ImageButton Grid.Column=&quot;1&quot; Style=&quot;{DynamicResource DialogCloseImageButton}&quot; Command=&quot;{Binding CloseDialogCommand}&quot;/&gt; &lt;/Grid&gt; &lt;/Grid&gt; &lt;/Frame&gt; &lt;/pages:PopupPage&gt; </code></pre> <p><strong>Option 2.</strong> Updated XAML and added the Frame inside ScrollView</p> <pre><code>&lt;ScrollView Scrolled=&quot;ScrollView_Scrolled&quot;&gt; .... &lt;/ScrollView&gt; private void ScrollView_Scrolled(object sender, Xamarin.Forms.ScrolledEventArgs e) { if (e.ScrollY &gt; 100) { itemViewModel.CloseDialogCommand.Execute(null); } } </code></pre> <p>In option 1 I don't have the scroll, so the plug in works with default behavior, but I have no way to close the dialog in scroll.</p> <p>In option 2, I added the frame inside the scrollview to check for Y scroll and dismiss the dialog. The Scrolled event never fires. Additionally, I cannot close the dialog when clicking outside the modal.</p> <p>After all, my question is how to dismiss the dialog while scrolling down?</p>
3
1,157
Why I am getting such a message:java.lang.NoSuchMethodError: No virtual method fetchProvidersForEmail(Ljava/lang/String;)
<p>I am trying to create an Android program, and met an error of which I have no idea how to solve. My app crashes after I put in the email. I suspect that the problem is related with firebase. I have tried different ways of solving of this problem, such as changing the versions of firebase implementations, but without any success.</p> <p>Here is my code</p> <p><strong>MainActivity.java</strong></p> <pre><code>package com.chat.mychatapp; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.firebase.ui.auth.AuthUI; import com.firebase.ui.database.FirebaseListAdapter; import com.github.library.bubbleview.BubbleTextView; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.FirebaseDatabase; import android.text.format.DateFormat; import java.util.Objects; public class MainActivity extends AppCompatActivity { public static int SIGN_IN_CODE = 1; private RelativeLayout activity_main; private FirebaseListAdapter&lt;Message&gt; adapter; private FloatingActionButton sendBtn; @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == SIGN_IN_CODE){ if(resultCode == RESULT_OK){ Snackbar.make(activity_main, "You are authorized", Snackbar.LENGTH_LONG).show(); displayAllMessages(); }else{ Snackbar.make(activity_main, "You are NOT authorized", Snackbar.LENGTH_LONG).show(); finish(); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); activity_main = findViewById(R.id.activity_main); sendBtn = findViewById(R.id.sendBtn); sendBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText textField = findViewById(R.id.messageField); if(textField.getText().toString().equals("")) return; FirebaseDatabase.getInstance().getReference().push().setValue( new Message(Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getEmail(), textField.getText().toString() ) ); textField.setText(""); } }); //User not autorized if(FirebaseAuth.getInstance().getCurrentUser() == null){ startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(), SIGN_IN_CODE); }else{ Snackbar.make(activity_main, "You are authorized", Snackbar.LENGTH_LONG).show(); displayAllMessages(); } } private void displayAllMessages() { ListView listOfMessages = findViewById(R.id.messageList); adapter = new FirebaseListAdapter&lt;Message&gt;(this, Message.class, R.layout.list_item, FirebaseDatabase.getInstance().getReference()) { @Override protected void populateView(View v, Message model, int position) { TextView m_user, m_time; BubbleTextView m_text; m_user = v.findViewById(R.id.messageUser); m_time = v.findViewById(R.id.messageTime); m_text = v.findViewById(R.id.messageText); m_user.setText(model.getUserName()); m_text.setText(model.getMessage()); m_time.setText(DateFormat.format("dd-mm-yyyy HH:mm:ss",model.getTime())); } }; listOfMessages.setAdapter(adapter); } } </code></pre> <p><strong>build.gradle</strong></p> <pre><code>apply plugin: 'com.android.application' android { compileSdkVersion 29 buildToolsVersion "29.0.2" defaultConfig { applicationId "com.chat.mychatapp" minSdkVersion 19 targetSdkVersion 29 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test.ext:junit:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' implementation 'com.google.firebase:firebase-analytics:17.2.1' implementation 'com.google.android.material:material:1.0.0' implementation 'androidx.legacy:legacy-support-v4:1.0.0' implementation 'com.google.android.gms:play-services-auth:17.0.0' implementation 'com.google.firebase:firebase-auth:19.2.0' implementation 'com.google.firebase:firebase-database:19.2.0' implementation 'com.firebaseui:firebase-ui:0.6.2' implementation 'com.github.lguipeng:BubbleView:1.0.1' //implementation 'com.google.firebase:firebase-firestore:21.3.1' } apply plugin: 'com.google.gms.google-services' </code></pre> <p><strong>Error</strong></p> <pre><code>E/AndroidRuntime: FATAL EXCEPTION: main Process: com.chat.mychatapp, PID: 18455 java.lang.NoSuchMethodError: No virtual method fetchProvidersForEmail(Ljava/lang/String;)Lcom/google/android/gms/tasks/Task; in class Lcom/google/firebase/auth/FirebaseAuth; or its super classes (declaration of 'com.google.firebase.auth.FirebaseAuth' appears in /data/app/com.chat.mychatapp-s_3u6mmiv0A6KE9ijznfqQ==/base.apk) at com.firebase.ui.auth.ui.AcquireEmailHelper.checkAccountExists(AcquireEmailHelper.java:55) at com.firebase.ui.auth.ui.email.SignInNoPasswordActivity.onClick(SignInNoPasswordActivity.java:73) at android.view.View.performClick(View.java:7339) at android.widget.TextView.performClick(TextView.java:14222) at android.view.View.performClickInternal(View.java:7305) at android.view.View.access$3200(View.java:846) at android.view.View$PerformClick.run(View.java:27787) at android.os.Handler.handleCallback(Handler.java:873) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread.java:7078) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964) </code></pre>
3
2,998
INSERT INTO with dynamic pivot statement yields Unknown Table error in certain circumstances
<p>I'm using SQL Server and I have a dynamically built INSERT INTO statement in a stored procedure. The code works without a problem when I execute it manually, but when I execute the SP it returns an Unknown Table error where it tries to create the table from the select statement.</p> <p>The problem is only on the production server. On the development server, it runs fine either way you execute it. So on my development server, my web app is able to display the desired results. But I'm unable to determine what settings or configuration is relevant and might be different. Development server is running a different version of SQL than production, but I'm unsure about which versions.</p> <p>What I'm trying to accomplish is this: My database stores a certain type of form. Header information for each form submitted is stored in a parent table. Detailed line item answers are in the child table. (i.e. answers for each numbered line item: 1.01, 1.02, 1.03, etc.) Each answer consists of a value indicating their Yes/No choice and a text field for notes/comments. My customer needs to see the data in a form where one row displays all info for the submission. So I'm using a pivot to turn multi-row answers into columns on the same row.</p> <p>The reason I need to use dynamic SQL here is that there are actually different form types in the database. Each type has their own number of child rows where questions are broken out differently into sections and numbered accordingly. I've simplified my stored procedure shown here for readability. But the procedure accepts a form type value and uses it to limit the results to only that type. Otherwise, if the structure didn't vary, I would not have needed dynamic SQL.</p> <p>Here is the code:</p> <pre><code>ALTER PROCEDURE [dbo].[sp_Get_Assessment_List_Details] AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; -- ================================================================================================================================================ -- Build tables that transposes answers and comments from the detail records into columns. -- So multiple child records become single detail records with answer values across in columns. -- ================================================================================================================================================ declare @collist nvarchar(max) declare @q nvarchar(max) -- Create a string containing all the line numbers for answers in this set. SET @collist = stuff((select distinct ',' + QUOTENAME(Dtl_Line_Number) FROM dbo.Form_Details as D FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') -- Once for answers set @q = ' select * INTO _Temp_Form_Details from ( select Dtl_Form_ID, Dtl_Line_Number, Dtl_Answer from ( select * from dbo.Form_Details ) as x ) as source pivot ( max(Dtl_Answer) for Dtl_Line_Number in (' + @collist + ') ) as pvt' exec (@q) -- Again for comments/notes SET @collist = stuff((select distinct ',' + QUOTENAME(Dtl_Line_Number) FROM dbo.Form_Details as D FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') set @q = ' select * INTO _Temp_Form_Details_Notes from ( select Dtl_Form_ID, Dtl_Line_Number, Dtl_Comment from ( select * from dbo.Form_Details ) as x ) as source pivot ( max(Dtl_Comment) for Dtl_Line_Number in (' + @collist + ') ) as pvt' exec (@q) -- ================================================================================================================================================ -- Finally, return the Form header data joined with the transposed detail columns -- ================================================================================================================================================ -- Omitted here for simplicity DROP TABLE _Temp_Form_Details DROP TABLE _Temp_Form_Details_Notes END </code></pre> <p>To summarize again: When executed as a stored procedure (<code>exec sp_Get_Assessment_List_Details</code>), it returns the &quot;Unknown Table&quot; error on the first line that says &quot;<code>exec (@q)</code>&quot;. So it doesn't seem to like the tables _Temp_Form_Details and _Temp_Form_Details_Notes.</p> <p>But if I highlight and execute the code manually in a query window, it runs fine and returns the pivoted results with no problem. Also, the error only occurs on the production server. On the development machine, it runs fine either way.</p> <p>I'm open to ways to correct this problem or other approaches that would accomplish the same goal.</p> <p>Thanks!</p>
3
1,444
I can't set the time in a date picker in xcode
<p>I have made the following window in Xcode:</p> <p><a href="https://i.stack.imgur.com/U96pY.jpg" rel="nofollow noreferrer">Window for logging assingments</a></p> <p>And I have written this to go along with that window</p> <pre><code>class logHomeworkViewController: UIViewController { @IBOutlet var dueDatePicker: UIDatePicker! @IBOutlet var promptDatePicker: UIDatePicker! @IBOutlet weak var homeWorkName: UITextField! override func viewDidLoad() { super.viewDidLoad() let today = Date() homeWorkName.addTarget(self, action: #selector(nameChanged), for: .editingChanged) dueDatePicker.date = Calendar.current.date(byAdding: .day, value: 1,to: today)! var dateComponents = DateComponents() //set min date to midnight dateComponents.hour=0 dateComponents.minute = 24 dateComponents.day = Calendar.current.component(.day, from: today) dateComponents.month = Calendar.current.component(.year, from: today) dueDatePicker.minimumDate = Calendar.current.date(from: dateComponents) // Do any additional setup after loading the view. } //once due date has been chosen, allow the user to set up a reminder date @IBAction func dueDateChanged(_ sender: Any) { promptDatePicker.maximumDate = Calendar.current.date(byAdding: .hour, value: -1, to: dueDatePicker.date) promptDatePicker.minimumDate = Calendar.current.date(byAdding: .hour, value: 1, to: Date()) promptDatePicker.isEnabled = true } //once a assingment name has been set, allow input of a due date @objc func nameChanged(_ textField: UITextField){ if(homeWorkName.text! != &quot;&quot;){ dueDatePicker.isEnabled = true }else{ dueDatePicker.isEnabled = false } } } </code></pre> <p>I intend to guide the user through this window from top to bottom. As in one field has been entered the next opens up for input. Upon testing, I found that when I try to open up the date picker and set the time <strong>after setting the assignment name</strong>, it crashes. The logs display this after the crash <code>unrecognized selector sent to instance 0x7fdabb623520 terminating with uncaught exception of type NSException</code>. Keep in mind I'm using the style of the compact date picker. This error does not occur with any another style but I need this one to work as it is best suited for my needs. This only applies to the actual time field not am or pm.</p> <p><a href="https://i.stack.imgur.com/kShA2.jpg" rel="nofollow noreferrer">Time entry field</a></p> <p>I have narrowed down the error to the line <code>dueDatePicker.isEnabled = true</code>. When I leave the first date picker enabled by default in my storyboard and comment out the <code>nameChanged()</code> function, I get no error when attempting to set the time. I have tried to hide it instead of disabling the view but that does not work either and results in the same error. What may I have done to cause this and how can I solve it?</p>
3
1,051
PHP password_hash and password_verify weird issue not verifying
<p>Here is my scenario:</p> <p>I have a function that gives out json response when called for. Its inside a class that has the Signup.class.php included which has the <code>Signup</code> class. Where the GET param <code>pass</code> is being accessed inside the <code>gen_hash()</code> function as shown above. The code is below.</p> <p>The code is live at <a href="https://api1.selfmade.ninja/api/gen_hash?pass=hellooo" rel="nofollow noreferrer">https://api1.selfmade.ninja/api/gen_hash?pass=hellooo</a></p> <pre><code> private function gen_hash(){ if(isset($this-&gt;_request['pass'])){ $s = new Signup(&quot;&quot;, $this-&gt;_request['pass'], &quot;&quot;); $hash = $s-&gt;hashPassword(); $data = [ &quot;hash&quot; =&gt; $hash, &quot;info&quot; =&gt; password_get_info($hash), &quot;val&quot; =&gt; $this-&gt;_request['pass'], &quot;verify&quot; =&gt; password_verify($this-&gt;_request['pass'], $hash), &quot;spot_verify&quot; =&gt; password_verify($this-&gt;_request['pass'], password_hash($this-&gt;_request['pass'], PASSWORD_BCRYPT)) ]; $data = $this-&gt;json($data); $this-&gt;response($data,200); } } </code></pre> <p>This function calls Signup.class.php which has the following code:</p> <pre><code>&lt;?php require_once('Database.class.php'); class Signup { private $username; private $password; private $email; private $db; public function __construct($username, $password, $email){ $this-&gt;db = Database::getConnection(); $this-&gt;username = $username; $this-&gt;password = $password; $this-&gt;email = $email; } public function getInsertID(){ } public function hashPassword(){ //echo $this-&gt;password; return password_hash($this-&gt;$password, PASSWORD_BCRYPT); } } </code></pre> <p>The issue is as follows:</p> <ol> <li>The &quot;spot_verify&quot; array key from <code>gen_hash()</code> has a code that works as intended.</li> <li>But the &quot;verify&quot; array key from <code>gen_hash()</code> has a code that is not working as intended. It is always telling false whatsoever the case is. The hash is being generated from the <code>Signup::hashPassword()</code> function. It is all working as expected. The value is setting right, and is being passed to the <code>password_hash</code> function from within the <code>Signup::hashPassword()</code>. But inside gen_hash() under &quot;verify&quot;, it just tells false.</li> </ol> <p>The code is live at <a href="https://api1.selfmade.ninja/api/gen_hash?pass=hellooo" rel="nofollow noreferrer">https://api1.selfmade.ninja/api/gen_hash?pass=hellooo</a></p> <p>It is giving the following answer and it makes no sense. Why is verify false?:</p> <pre><code>{ &quot;hash&quot;: &quot;$2y$10$Y3bq8EzFmEpgM6zZqONeeeP3gaUkSClyjmS3NCWxrpFS6R8okRHJG&quot;, &quot;info&quot;: { &quot;algo&quot;: &quot;2y&quot;, &quot;algoName&quot;: &quot;bcrypt&quot;, &quot;options&quot;: { &quot;cost&quot;: 10 } }, &quot;val&quot;: &quot;hellooo&quot;, &quot;verify&quot;: false, &quot;spot_verify&quot;: true } </code></pre> <p>What I did already? I ensured that the same password value is being passed to password_hash and password_verify. But this makes no sense. What am I missing?</p>
3
1,562
How to set DataChangePolicy Azure search sdk 3.0.3
<p>I have enabled change policy my db</p> <pre><code>ALTER Database EMR SET CHANGE_TRACKING = ON (CHANGE_RETENTION = 2 DAYS, AUTO_CLEANUP = ON) ALTER TABLE EMR.dbo.ICDCodePCS ENABLE CHANGE_TRACKING WITH (TRACK_COLUMNS_UPDATED = OFF) </code></pre> <p>and on azure index side i use below for Datasource.AzureSql</p> <pre><code> DataChangePolicy = new SqlIntegratedChangeTrackingPolicy() </code></pre> <p>when i insert a new row to this table it does not seem to update the index automatically in azure search side. i have to pretty much run the index job after i add new row. how do i trace or debug what am i doing wrong?</p> <p>i am using azure sql and azure search with sdk 3.0.3</p> <pre><code>var dataIndexer = new AzureDataIndexer() { DataSource = $"{EMRConsts.EMRAzureIndexNameICD10PCS}-datasource", Description = "ICD10 Procedueral Code", IndexName = EMRConsts.EMRAzureIndexNameICD10PCS, Indexer = $"{EMRConsts.EMRAzureIndexNameICD10PCS}-indexer", TableName = EMRConsts.EMRAzureIndexNameICD10PCS, DataChangePolicy = new SqlIntegratedChangeTrackingPolicy(), Settings = new AzureDataIndexerSettings() { ServiceName = _settingManager.GetSettingValue(EMRSettingNames.EmrSearchServiceName), ApiKey = _settingManager.GetSettingValue(EMRSettingNames.EmrSearchServiceApiKeyAdmin) }, Definition = new Index() { Name = EMRConsts.EMRAzureIndexNameICD10PCS, Fields = new[] { new Field("ICDCodePCSId", DataType.String) { IsKey = true, IsSearchable = true, IsFilterable = true, IsSortable = true, IsFacetable = false, IsRetrievable = true }, new Field("ICDCodePCSName", DataType.String) { IsKey = false, IsSearchable = true, IsFilterable = true, IsSortable = false, IsFacetable = false, IsRetrievable = true }, new Field("ICDCodePCSShortName", DataType.String) { IsKey = false, IsSearchable = true, IsFilterable = true, IsSortable = false, IsFacetable = false, IsRetrievable = true } }, Suggesters = new[] { new Suggester() { Name = SuggesterName, SearchMode = SuggesterSearchMode.AnalyzingInfixMatching, SourceFields = new List&lt;string&gt;() {"ICDCodePCSName", "ICDCodePCSId", "ICDCodePCSShortName" } }, } </code></pre> <p>DataSource</p> <pre><code> var dataSource = DataSource.AzureSql( name: dataIndexer.DataSource, sqlConnectionString: _appConfigSqlConnection.GetConnection().ConnectionString, tableOrViewName: dataIndexer.TableName, changeDetectionPolicy: dataIndexer.DataChangePolicy, description: dataIndexer.Description); try { _searchClient.Indexes.Create(dataIndexer.Definition); var indexer = new Indexer() { Name = dataIndexer.Indexer, Description = dataIndexer.Description, DataSourceName = dataSource.Name, TargetIndexName = dataIndexer.IndexName }; _searchClient.Indexers.Create(indexer); _searchClient.DataSources.Create(dataSource); } </code></pre>
3
2,385
Accordion is not working with latest version of ui-bootstrap-tpls.js
<p>I have an accordion which is working with older version(0.13.0) of ui-bootstrap-tpls.js,but its not working with latest version(2.5.0) of ui-bootstrap-tpls.js. Due to older version its effecting other component to work correctly. I need to work with latest version only. Can anyone please help me on it? Below is my code.</p> <h2>HTML</h2> <pre><code>&lt;link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.css'&gt; &lt;body ng-app="app"&gt; &lt;h1&gt;Dynamic accordion: nested lists with html markup&lt;/h1&gt; &lt;div ng-controller="AccordionDemoCtrl"&gt; &lt;accordion close-others="oneAtATime"&gt; &lt;accordion-group is-open="group.isOpen" ng-repeat="group in groups"&gt; &lt;accordion-heading&gt;&lt;i class="glyphicon-plus"&gt;&lt;/i&gt; {{ group.title }} &lt;i class="pull-right glyphicon" ng-class="{'glyphicon-chevron-down': group.isOpen, 'glyphicon-chevron-right': !group.isOpen}"&gt;&lt;/i&gt; &lt;/accordion-heading&gt; {{ group.content }} &lt;ul&gt; &lt;li ng-repeat="item in group.list"&gt; &lt;span ng-bind-html="item"&gt;&lt;/span&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/accordion-group&gt; &lt;/accordion&gt; &lt;/div&gt; &lt;/body&gt; &lt;script src='https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular.js'&gt;&lt;/script&gt; &lt;script src='https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.4/angular-filter.js'&gt;&lt;/script&gt; &lt;script src='https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular-sanitize.js'&gt;&lt;/script&gt; &lt;!--&lt;script src='https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.13.0/ui-bootstrap-tpls.js'&gt;&lt;/script&gt;--&gt; &lt;script src='https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.js'&gt;&lt;/script&gt; &lt;script src="js/index.js"&gt;&lt;/script&gt; </code></pre> <h2>index.js</h2> <pre><code>angular.module('app', ['ui.bootstrap','ngSanitize','angular.filter']); angular.module('app').controller('AccordionDemoCtrl', function ($scope) { $scope.oneAtATime = true; $scope.groups = [ { title: 'title 1', content: 'content 1', isOpen: true, list: ['&lt;i&gt;item1a&lt;/i&gt; blah blah', 'item2a', 'item3a'] }, { title: 'title 2', content: 'Content 2', list: ['item1b', '&lt;b&gt;item2b &lt;/b&gt; blah ', 'item3b'] }, { title: 'title 3', content: 'Content 3' }, { title: 'title 4', content: 'content 4' }, { title: 'title 5', content: 'content 5' } ]; }); </code></pre>
3
1,329
Mozilla WebExtension API storage - Debugging with and without breakpoints leads to different output
<p><br/> Hello guys, <br/> i am trying to implement an add-on for the Mozilla-Firefox Browser. The following script shows one backgorund script I already successfully integrated. It uses the Mozilla WebExtension API storage. It gets executed but the log on the browser console suprises me. I get alternating logged nothing and: <br/></p> <pre><code>bla bla bla </code></pre> <p>If and only if I set breakpoints on significant lines (especially the last 5 lines) of my code in Debugging-Mode I get always the expected result:</p> <pre><code>bla </code></pre> <p>How is it that the output depends on setting breakpoints. I have no idea what is happening and can not find any similar problems on the internet. Can somebody explain to me what is happening and what I can do to prevent the wrong output?<br/><br/> storeManager.js:<br/></p> <pre><code>var localStore = chrome.storage.local; var StoreManager = function(){}; StoreManager.prototype.addItem = function(type, item){ var thisRef = this; localStore.get(type, function(obj){ if(chrome.runtime.lasterror){ console.log(chrome.runtime.lastError); }else{ var oldArr = obj[type]; if(oldArr === undefined) oldArr = []; if(oldArr.indexOf(item) !== -1) return; oldArr.push(item); thisRef.setItem(type, oldArr); } } ); } StoreManager.prototype.removeItem = function(type, item){ var thisRef = this; localStore.get(type, function(obj){ if(chrome.runtime.lasterror){ console.log(chrome.runtime.lastError); }else{ var oldArr = obj[type]; if(oldArr === undefined) return; var index = oldArr.indexOf(item); if(index === -1) return; oldArr.splice(index, 1); thisRef.setItem(type, oldArr); } } ); } StoreManager.prototype.setItem = function(type, item){ localStore.set({ [type] : item }, function(){ if(chrome.runtime.lasterror){ console.log(chrome.runtime.lastError); } } ); } StoreManager.prototype.visitItems = function(type, visit){ localStore.get(type, function(obj){ if(chrome.runtime.lasterror){ console.log(chrome.runtime.lastError); }else{ var oldArr = obj[type]; if(oldArr !== undefined){ for(var i=0; i&lt;oldArr.length; i++){ visit(oldArr[i]); } } } } ); } function justLog(str){ console.log(str); } var sm = new StoreManager(); sm.visitItems("lol", justLog); sm.addItem("lol", "bla"); sm.visitItems("lol", justLog); sm.removeItem("lol", "bla"); sm.visitItems("lol", justLog); </code></pre> <p><br/> manifest.json:<br/></p> <pre><code>{ "manifest_version": 2, "name": "Addon", "version": "0.0", "description": "no desc", "background": { "scripts": [ "storeManager.js" ] }, "permissions": [ "storage" ] } </code></pre>
3
1,616
How to convert li navbar dropdown with dropUp
<p>It's a simple bootstrap navbar with some li links. I want to convert dropdown to dropup.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.navbar { background-color: #34A8F0; } .nav-link{ display: flex; flex-direction: column; align-items: center; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;script src="https://use.fontawesome.com/f1e10fbba5.js"&gt;&lt;/script&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;!-- Latest compiled and minified CSS --&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"&gt; &lt;!-- jQuery library --&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"&gt;&lt;/script&gt; &lt;!-- Popper JS --&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"&gt;&lt;/script&gt; &lt;!-- Latest compiled JavaScript --&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;title&gt;Document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;nav class="navbar navbar-expand-md navbar-light "&gt; &lt;a class="navbar-brand" href="#"&gt; Navbar &lt;/a&gt; &lt;button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"&gt; &lt;span class="navbar-toggler-icon"&gt;&lt;/span&gt; &lt;/button&gt; &lt;div class="collapse navbar-collapse" id="navbarSupportedContent"&gt; &lt;ul class="navbar-nav mx-auto"&gt; &lt;li class="nav-item dropdown"&gt; &lt;a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"&gt; &lt;p class="m-0 p-0"&gt;&lt;i class="fa fa-home"&gt;&lt;/i&gt;&lt;/p&gt; &lt;p class="m-0 p-0"&gt;User Managemnt&lt;/p&gt; &lt;/a&gt; &lt;div class="dropdown-menu" aria-labelledby="navbarDropdown"&gt; &lt;a class="dropdown-item" href="#"&gt;Action&lt;/a&gt; &lt;a class="dropdown-item" href="#"&gt;Another action&lt;/a&gt; &lt;div class="dropdown-divider"&gt;&lt;/div&gt; &lt;a class="dropdown-item" href="#"&gt;Something else here&lt;/a&gt; &lt;/div&gt; &lt;/li&gt; &lt;li class="nav-item active"&gt; &lt;a class="nav-link" href="#"&gt; &lt;p class="m-0 p-0"&gt;&lt;i class="fa fa-home"&gt;&lt;/i&gt;&lt;/p&gt; &lt;p class="m-0 p-0"&gt;Email&lt;/p&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="nav-item dropdown"&gt; &lt;a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"&gt; &lt;p class="m-0 p-0"&gt;&lt;i class="fa fa-home"&gt;&lt;/i&gt;&lt;/p&gt; &lt;p class="m-0 p-0"&gt;Jobs&lt;/p&gt; &lt;/a&gt; &lt;div class="dropdown-menu" aria-labelledby="navbarDropdown"&gt; &lt;a class="dropdown-item" href="#"&gt;Action&lt;/a&gt; &lt;a class="dropdown-item" href="#"&gt;Another action&lt;/a&gt; &lt;div class="dropdown-divider"&gt;&lt;/div&gt; &lt;a class="dropdown-item" href="#"&gt;Something else here&lt;/a&gt; &lt;/div&gt; &lt;/li&gt; &lt;li class="nav-item dropdown"&gt; &lt;a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"&gt; &lt;p class="m-0 p-0"&gt;&lt;i class="fa fa-home"&gt;&lt;/i&gt;&lt;/p&gt; &lt;p class="m-0 p-0"&gt;HRMS&lt;/p&gt; &lt;/a&gt; &lt;div class="dropdown-menu" aria-labelledby="navbarDropdown"&gt; &lt;a class="dropdown-item" href="#"&gt;Action&lt;/a&gt; &lt;a class="dropdown-item" href="#"&gt;Another action&lt;/a&gt; &lt;div class="dropdown-divider"&gt;&lt;/div&gt; &lt;a class="dropdown-item" href="#"&gt;Something else here&lt;/a&gt; &lt;/div&gt; &lt;/li&gt; &lt;li class="nav-item dropdown"&gt; &lt;a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"&gt; &lt;p class="m-0 p-0"&gt;&lt;i class="fa fa-home"&gt;&lt;/i&gt;&lt;/p&gt; &lt;p class="m-0 p-0"&gt;Sell&lt;/p&gt; &lt;/a&gt; &lt;div class="dropdown-menu" aria-labelledby="navbarDropdown"&gt; &lt;a class="dropdown-item" href="#"&gt;Action&lt;/a&gt; &lt;a class="dropdown-item" href="#"&gt;Another action&lt;/a&gt; &lt;div class="dropdown-divider"&gt;&lt;/div&gt; &lt;a class="dropdown-item" href="#"&gt;Something else here&lt;/a&gt; &lt;/div&gt; &lt;/li&gt; &lt;li class="nav-item "&gt; &lt;a class="nav-link" href="#"&gt; &lt;p class="m-0 p-0"&gt;&lt;i class="fa fa-home"&gt;&lt;/i&gt;&lt;/p&gt; &lt;p class="m-0 p-0"&gt;Notification&lt;/p&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="nav-item dropdown"&gt; &lt;a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"&gt; &lt;p class="m-0 p-0"&gt;&lt;i class="fa fa-home"&gt;&lt;/i&gt;&lt;/p&gt; &lt;p class="m-0 p-0"&gt;Expenses&lt;/p&gt; &lt;/a&gt; &lt;div class="dropdown-menu" aria-labelledby="navbarDropdown"&gt; &lt;a class="dropdown-item" href="#"&gt;Action&lt;/a&gt; &lt;a class="dropdown-item" href="#"&gt;Another action&lt;/a&gt; &lt;div class="dropdown-divider"&gt;&lt;/div&gt; &lt;a class="dropdown-item" href="#"&gt;Something else here&lt;/a&gt; &lt;/div&gt; &lt;/li&gt; &lt;li class="nav-item dropdown"&gt; &lt;a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"&gt; &lt;p class="m-0 p-0"&gt;&lt;i class="fa fa-home"&gt;&lt;/i&gt;&lt;/p&gt; &lt;p class="m-0 p-0"&gt;Report&lt;/p&gt; &lt;/a&gt; &lt;div class="dropdown-menu" aria-labelledby="navbarDropdown"&gt; &lt;a class="dropdown-item" href="#"&gt;Action&lt;/a&gt; &lt;a class="dropdown-item" href="#"&gt;Another action&lt;/a&gt; &lt;div class="dropdown-divider"&gt;&lt;/div&gt; &lt;a class="dropdown-item" href="#"&gt;Something else here&lt;/a&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;ul class="navbar-nav"&gt; &lt;li class="nav-item active"&gt; &lt;a class="nav-link" href="#"&gt; &lt;p class="m-0 p-0"&gt;&lt;i class="fa fa-home"&gt;&lt;/i&gt;&lt;/p&gt; &lt;p class="m-0 p-0"&gt;Email&lt;/p&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/nav&gt; &lt;/nav&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> I see how to convert but they use the button but I don't want to use the button I want this li. This dropdown open downward I want it open upward(dropup) I have many li that's why I can't use the button for li to dropup.</p>
3
4,372