id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23535800
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll Additional information: Invalid attempt to read when no data is present. 'Connection Data. Dim LoginData As String = "User ID=User;Password=Password;Initial Catalog=TestDB;Data Source=SQLServer" 'Connection Object. Dim ConnectionObject As New SqlConnection(LoginData) ConnectionObject.Open() 'Query. Dim Query As New SqlCommand Dim Reader As SqlDataReader Dim Result As String Query.CommandText = "SELECT PI_PatternVersion FROM dbo.tb_SystemPatternList WHERE PI_PatternType = 4" Query.Connection = ConnectionObject Reader= QuerySmartScan.ExecuteReader() Result= Reader.Item("PI_PatternVersion") MsgBox(Result)
doc_23535801
Text All Eyez on Me Track Listing # Title Artisttime 1 Ambitionz Az a Ridah 2Pac 4:39 2 All About U 2Pac 4:37       Fatal           Yani Hadati           Dru Down           Snoop Dogg           Nair Dogg           Nate Dogg     3 Skandalouz 2Pac 4:09       Nate Dogg     4 Got My Mind Made Up 2Pac 5:13       Kurupt           Redman           Method Man           Dat N Daz     5 How Do You Want It Jojo the Elf 4:47       2Pac     6 2 of Amerikaz Most Wanted 2Pac 4:07       Snoop Dogg     7 No More Pain 2Pac 6:14 8 Heartz of Men 2Pac 4:43 9 Life Goes On 2Pac 5:02 10 Only God Can Judge Me Rappin' 4-Tay 4:57       2Pac     11 Tradin War Stories Nair Dogg 5:29       The Storm           CPO           C-BO           Outlawz           2Pac     12 California Love [Remix] Dr. Dre 6:25       2Pac           Roger     13 I Ain't Mad at Cha 2Pac 4:53       Danny Boy     14 What'z Ya Phone No. Danny Boy 5:10       2Pac     15 (2) Can't C Me George Clinton 5:30       2Pac     16 (2) Shorty Wanna Be a Thug 2Pac 3:51 17 (2) Holla at Me 2Pac 4:56 18 (2) Wonda Why They Call U B____ 2Pac 4:19 19 (2) When We Ride Nair Dogg 5:09       2Pac     20 (2) Thug Passion Outlawz 5:08       The Storm           Dramarydal           Jewell           2Pac     21 (2) Picture Me Rollin' Danny Boy 5:15       2Pac           CPO           Big Syke     22 (2) Check Out Time Big Syke 4:39       Kurupt           2Pac     23 (2) Ratha Be Ya N____ 2Pac 4:14       Richie Rich     24 (2) All Eyez on Me Big Syke 5:08       2Pac     25 (2) Run tha Streetz The Storm 5:17       Nair Dogg           Michel'le           2Pac     26 (2) Ain't Hard 2 Find B-Legit 4:29       E-40           C-BO           2Pac           Richie Rich     27 (2) Heaven Ain't Hard 2 Find 2Pac 3:58 From this I need to obtain the titles of all the songs. So far, I have def extraction(): f = open('Songs in Albums List.txt', 'r') str = 'Text All Eyez on Me Track Listing # Title Artisttime 1 Ambitionz Az a Ridah 2Pac 4:39' \ ' 2 All About U 2Pac 4:37       Fatal           Yani Hadati           ' \ 'Dru Down           Snoop Dogg           Nair Dogg           Nate Dogg     ' \ '3 Skandalouz 2Pac 4:09       Nate Dogg     4 Got My Mind Made Up 2Pac 5:13       ' \ 'Kurupt           Redman           Method Man           Dat Nigga Daz     ' \ '5 How Do You Want It Jojo the Elf 4:47       2Pac     6 2 of Amerikaz Most Wanted ' \ '2Pac 4:07       Snoop Dogg     7 No More Pain 2Pac 6:14 8 Heartz of Men 2Pac 4:43 ' \ '9 Life Goes On 2Pac 5:02 10 Only God Can Judge Me Rappin 4-Tay 4:57       2Pac     ' \ '11 Tradin War Stories Nair Dogg 5:29       The Storm           CPO           C-BO' \ '           Outlawz           2Pac     12 California Love [Remix] Dr. Dre 6:25       ' \ '2Pac           Roger     13 I Aint Mad at Cha 2Pac 4:53       Danny Boy     ' \ '14 Whatz Ya Phone No. Danny Boy 5:10       2Pac     15 (2) Cant C Me George Clinton 5:30' \ '       2Pac     16 (2) Shorty Wanna Be a Thug 2Pac 3:51 17 (2) Holla at Me 2Pac 4:56' \ ' 18 (2) Wonda Why They Call U B____ 2Pac 4:19 19 (2) When We Ride Nair Dogg 5:09' \ '       2Pac     20 (2) Thug Passion Outlawz 5:08       The Storm           ' \ 'Dramarydal           Jewell           2Pac     21 (2) Picture Me Rollin Danny Boy 5:15' \ '       2Pac           CPO           Big Syke     22 (2) Check Out Time ' \ 'Big Syke 4:39       Kurupt           2Pac     23 (2) Ratha Be Ya N____ 2Pac 4:14' \ '       Richie Rich     24 (2) All Eyez on Me Big Syke 5:08       2Pac     ' \ '25 (2) Run tha Streetz The Storm 5:17       Nair Dogg           Michelle           ' \ '2Pac     26 (2) Aint Hard 2 Find B-Legit 4:29       E-40           C-BO           ' \ '2Pac           Richie Rich     27 (2) Heaven Aint Hard 2 Find 2Pac 3:58' st = " ".join(str.split()) songs = re.findall(r'\d{0,3}(.+?):', st, re.I|re.M) # songs = songs.replace("\xc2\xa0", " ") s = " ".join(songs) s = s.replace("\xc2\xa0", " ") print s # s = re.sub("^\d+\s|\s\d+\s|\s\d+$", " ", s) print s t = re.findall(r'\s*[a-zA-Z0-9]\s*', s, re.I|re.M) x = [] ind = [] y = [] z = 0 for item in t: if len(item) > 2: y.append(z) x.append(t[t.index(item)]) ind.append(t.index(item)) z = z + 1 print y new_x = [] for string in x: new_x.append(string.split(' ')); l = [] for item in new_x: for val in item: l.append(filter(lambda space: space.strip(), val)) # print l l = filter(lambda space: space.strip(), l) x = 0 for vals in y: print vals t.pop(vals) t.insert(vals, l[y.index(vals)]) print t[20], t[33], t[38], t[48] for vals in reversed(y): t.insert(vals+1, ' ') t = ''.join(t) t = re.findall(r'\d{0,3}\s*(.+)\s*\d', t, re.I|re.M) print t which returns a string like this: ['Text All Eyez on Me Track Listing Title Artisttime 1 Ambitionz Az a Ridah 2Pac 4 2 All About U 2Pac 4 Fatal Yani Hadati Dru Down Snoop Dogg Nair Dogg Nate Dogg 3 Skandalouz 2Pac 4 Nate Dogg 4 Got My Mind Made Up 2Pac 5 Kurupt Redman Method Man Dat N Daz 5 How Do You Want It Jojo the Elf 4 2Pac 6 2 of Amerikaz Most Wanted 2Pac 4 Snoop Dogg 7 No More Pain 2Pac 6 8 Heartz of Men 2Pac 4 9 Life Goes On 2Pac 5 10 Only God Can Judge Me Rappin 4Tay 4 2Pac 11 Tradin War Stories Nair Dogg 5 The Storm CPO CBO Outlawz 2Pac 12 California Love Remix Dr Dre 6 2Pac Roger 13 I Aint Mad at Cha 2Pac 4 Danny Boy 14 Whatz Ya Phone No Danny Boy 5 2Pac 15 2 Cant C Me George Clinton 5 2Pac 16 2 Shorty Wanna Be a Thug 2Pac 3 17 2 Holla at Me 2Pac 4 18 2 Wonda Why They Call U B 2Pac 4 19 2 When We Ride Nair Dogg 5 2Pac 20 2 Thug Passion Outlawz 5 The Storm Dramarydal Jewell 2Pac 21 2 Picture Me Rollin Danny Boy 5 2Pac CPO Big Syke 22 2 Check Out Time Big Syke 4 Kurupt 2Pac 23 2 Ratha Be Ya N 2Pac 4 Richie Rich 24 2 All Eyez on Me Big Syke 5 2Pac 25 2 Run tha Streetz The Storm 5 Nair Dogg Michelle 2Pac 26 2 Aint Hard 2 Find BLegit 4 E40 CBO 2Pac Richie Rich 27 2 Heaven Aint Hard 2 Find 2Pac '] I want to get the text between numbers and filter them to find the songs. Also is there is a better way to get the titles of the songs into a list? A: try this regex r = re.split(r"\s+\d+\s+", str) A: Why over-stressing re? import re blah = """All Eyez on Me Track Listing # Title Artisttime 1 Ambitionz Az a Ridah 2Pac 4:39 2 All About U 2Pac 4:37 Fatal Yani Hadati Dru Down Snoop Dogg Nair Dogg Nate Dogg 3 Skandalouz 2Pac 4:09 Nate Dogg 4 Got My Mind Made Up 2Pac 5:13 Kurupt Redman Method Man Dat N Daz 5 How Do You Want It Jojo the Elf 4:47 2Pac 6 2 of Amerikaz Most Wanted 2Pac 4:07 Snoop Dogg 7 No More Pain 2Pac 6:14 8 Heartz of Men 2Pac 4:43 9 Life Goes On 2Pac 5:02 10 Only God Can Judge Me Rappin' 4-Tay 4:57 2Pac 11 Tradin War Stories Nair Dogg 5:29 The Storm CPO C-BO Outlawz 2Pac 12 California Love [Remix] Dr. Dre 6:25 2Pac Roger 13 I Ain't Mad at Cha 2Pac 4:53 Danny Boy 14 What'z Ya Phone No. Danny Boy 5:10 2Pac 15 (2) Can't C Me George Clinton 5:30 2Pac 16 (2) Shorty Wanna Be a Thug 2Pac 3:51 17 (2) Holla at Me 2Pac 4:56 18 (2) Wonda Why They Call U B____ 2Pac 4:19 19 (2) When We Ride Nair Dogg 5:09 2Pac 20 (2) Thug Passion Outlawz 5:08 The Storm Dramarydal Jewell 2Pac 21 (2) Picture Me Rollin' Danny Boy 5:15 2Pac CPO Big Syke 22 (2) Check Out Time Big Syke 4:39 Kurupt 2Pac 23 (2) Ratha Be Ya N____ 2Pac 4:14 Richie Rich 24 (2) All Eyez on Me Big Syke 5:08 2Pac 25 (2) Run tha Streetz The Storm 5:17 Nair Dogg Michel'le 2Pac 26 (2) Ain't Hard 2 Find B-Legit 4:29 E-40 C-BO 2Pac Richie Rich 27 (2) Heaven Ain't Hard 2 Find 2Pac 3:58 Extra""" def extraction2(s): s = re.sub(r'\s+', " ", s) tracks = [] trackno = 1 while 1: track = { "trackno" : trackno, "title" : "", "duration": None } # start of next track from_ = s.find(str(trackno)) if from_ < 0: # last title has additional artists (not the case in the example) tracks[trackno-2]["title"] += " " + s.strip() else: if trackno > 1 and from_ > 0: # add "trailing" artists to previous track tracks[trackno-2]["title"] += s[:from_].strip() # time indicates end of track m = re.search(r'\d{1,2}:\d{2}', s[from_:]) if m: line = s[from_:from_+m.end()].split(" ") track["title"] = " ".join(line[1:-1]).strip() track["duration"] = line[-1:][0] tracks.append(track) if not track["duration"]: break s = s[from_+m.end():] trackno += 1 return tracks tracklist = extraction2(blah) import json print json.dumps(tracklist, indent=4) While I am with @Wiktor Stribiżew, I also love puzzles ;) Remark regarding the original code: Not good style to use name of builtin type str as parameter name.
doc_23535802
string return desc ONE=one [ "ONE=one" ] Array of one element ONE="{}" [ 'ONE="{}"' ] Array of one element with quoted value. ONE='{}' [ "ONE='{}'" ] Array of one element with simple quoted value ONE='{attr: \"value\"}' [ "ONE='{attr: \\"value\\"}'" ] Array of one element ONE='{attr1: \"value\", attr2:\"value attr 2\"}' [ "ONE='{attr1: \\"value\\", attr2:\\"value attr 2\\"}'" ] Array of one element and json inside with multiples values ONE=one,TWO=two [ "ONE=one", "TWO=two" ] Array of two elements ONE=one, TWO=two [ "ONE=one", "TWO=two" ] Array of two elements (Ignoring space after comma) ONE='{}', TWO=two [ "ONE='{}', TWO=two" ] Array of two elements, one quoted ONE='{}',TWO='{}',THREE='{}' [ "ONE='{}'", "TWO='{}'", "THREE='{}'" ] Array of three elements ONE='{}', TWO=two, THREE=three [ "ONE='{}',", "TWO=two", "THREE=three" ] Array of three elements, one quoted How can i get the correct regex or process to get the expected result on each one? This is what i have: function parseVars(envString) { let matches = envArg.matchAll(/([A-Za-z][A-Za-z0-9]+=(["']?)((?:\\\2|(?:(?!\2)).)*)(\2))(\,\s?)?/g); let ret = []; for (const match of matches) { ret.push(match[1].trim()) } return ret; } And tests: describe("parseVars function", () => { it("should be one simple variable", () => { expect(parseVars("ONE=one")).toMatchObject([ "ONE=one" ]); }); it("should be two simple variable", () => { expect(parseVars("ONE=one,TWO=two")).toMatchObject([ "ONE=one", "TWO=two" ]); }); it("should be two simple variable (Trim space)", () => { expect(parseVars("ONE=one, TWO=two")).toMatchObject([ "ONE=one", "TWO=two" ]); }); it("should be simple json", () => { expect(parseVars("ONE='{}'")).toMatchObject([ "ONE='{}'", ]); }); it("should be three simple json", () => { expect(parseVars("ONE='{}',TWO='{}',THREE='{}'")).toMatchObject([ "ONE='{}'", "TWO='{}'", "THREE='{}'", ]); }); it("should be three simple json (Simple quote)", () => { expect(parseVars("ONE='{}'")).toMatchObject([ "ONE='{}'", ]); }); it("should be three simple json with attribute", () => { expect(parseVars("ONE='{attr: \"value\"}'")).toMatchObject([ "ONE='{attr: \"value\"}'", ]); }); it("should be complex json with multiple attributes", () => { expect(parseVars("ONE='{attr1: \"value\", attr2:\"value attr 2\"}'")).toMatchObject([ "ONE='{attr1: \"value\", attr2:\"value attr 2\"}'", ]); }); it("should be one json and one simple var", () => { expect(parseVars("ONE='{}', TWO=two")).toMatchObject([ "ONE='{}'", "TWO=two", ]); }); it("should be one json and two simple vars", () => { expect(parseVars("ONE='{}', TWO=two, THREE=three")).toMatchObject([ "ONE='{}'", "TWO=two", "THREE=three", ]); }); }); And the results: parseVars function ✕ should be one simple variable (4ms) ✕ should be two simple variable (1ms) ✕ should be two simple variable (Trim space) ✓ should be simple json (1ms) ✓ should be three simple json ✓ should be three simple json (Simple quote) ✓ should be three simple json with attribute ✓ should be complex json with multiple attributes ✕ should be one json and one simple var (1ms) ✕ should be one json and two simple vars (1ms) A: The issue with your regex is you're only testing the quote enclosures like ONE='{attr: \"value\"}', but not allowing ONE=one. When you use a capture group with an optional match (['"]?), if it doesn't match, the group still captures a zero-width character. When combine it with a negative lookahead (?!\2) it fails everything - any character has a zero-width character in front of it. You just need to combine the quote enclosure test with |[^,]*, so it works for both scenarios. Here's a simplified version of your concept: /(?=\b[a-z])\w+=(?:(['"])(?:(?!\1).)*\1|[^,]*)/gi * *Explanation (?=\b[a-z])\w+ any word characters, but must start with an alphabetic character = equal sign (?: non-capturing group (['"])(?:\\\1|(?!\1).)*\1 a quote enclosure |[^,]* or any string that not made by comma ) See the proof const texts = [ `ONE=one`, `ONE="{}"`, `ONE='{}'`, `ONE='{attr: \"value\"}'`, `ONE='{attr1: \"value\", attr2:\"value attr 2\"}'`, `ONE=one,TWO=two`, `ONE=one, TWO=two`, `ONE='{}', TWO=two`, `ONE='{}',TWO='{}',THREE='{}'`, `ONE='{}', TWO=two, THREE=three` ]; const regex = /(?=\b[a-z])\w+=(?:(['"])(?:\\\1|(?!\1).)*\1|[^,]*)/gi; texts.forEach(text => { console.log(text, '=>', text.match(regex)); }) A: You might also start the match with a char a-z followed by optional word chars. Then match either from an opening till closing " or ', or match all except a whitespace or comma without using lookarounds or capture groups. Using a case insensitive match using /i \b[a-z]\w*=(?:"[^"\\]*(?:\\.[^"\\]*)*"|\'[^\'\\]*(?:\\.[^\'\\]*)*\'|[^\s,]+) The pattern matches: * *\b A word boundary to prevent a partial match *[a-z]\w*= Match a char a-z, optional word chars and = *(?: Non capture group * *"[^"\\]*(?:\\.[^"\\]*)*" Match from " till " not stopping at an escaped one *| Or *\'[^\'\\]*(?:\\.[^\'\\]*)*\' Match from ' till ' not stopping at an escaped one *| Or *[^\s,]+ Match 1+ times any char except a whitspace char or , *) Close non capture group See a Regex demo const regex = /\b[a-z]\w*=(?:"[^"\\]*(?:\\.[^"\\]*)*"|\'[^\'\\]*(?:\\.[^\'\\]*)*\'|[^\s,]+)/gi; [ `ONE=one`, `ONE="{}"`, `ONE='{}'`, `ONE='{attr: \"value\"}'`, `ONE="{attr: \"value\"}"`, `ONE='{attr1: \"value\", attr2:\"value attr 2\"}'`, `ONE=one,TWO=two`, `ONE=one, TWO=two`, `ONE='{}', TWO=two`, `ONE='{}',TWO='{}',THREE='{}'`, `ONE='{}', TWO=two, THREE=three` ].forEach(s => console.log(s.match(regex)))
doc_23535803
Every second cell is order differently, so first row is ok: [{"id":"AA1","cell":["AA1","AD + DNS + WINS","dev"]}, but the next one is ordered like below: {"id":"AA2","cell":["dev","AD + DNS + WINS","AA2"]} when 3rd is ok, and 4th is disordered and so on. Code which is responsible for this process is below: var jsonData = new { total = totalPages, page = page, records = totalRecords, rows = ( from l in lst select new { id = l.HostName, cell = new List<string> { l.HostName, l.Description, l.Type } }).ToArray() }; return Json(jsonData, JsonRequestBehavior.AllowGet); Why is like that? I was trying use instead of List the String[], but Linq doesn't like that and pop up error, which suggest List instead of string array. Is there any way to sustain desired order? A: What was your code to use string[]? I got this working without any trouble: var jsonData = new { total = totalPages, page = page, records = totalRecords, rows = (from l in lst select new { id = l.HostName, cell = new string[] { l.HostName, l.Description, l.Type } }).ToArray() }; You can find similar samples here (but remember that in general they are very old and I would suggest looking at more up to date ones here or here).
doc_23535804
<input id="montant_commande" type="text" name = "total" value = "0"/><br/> <input type="radio" name = "Entree" /> <input type="radio" name = "Entree" /> <input type="radio" name = "Entree" /> <input type="radio" name = "Plats" /> <input type="radio" name = "Plats" /> <input type="radio" name = "Plats" /> <input type="radio" name = "Desserts" /> <input type="radio" name = "Desserts" /> <input type="radio" name = "Desserts" /> <input type="radio" name = "Boissons" /> <input type="radio" name = "Boissons" /> <input type="radio" name = "Boissons" /> Can you provide me a way to achieve that? I've tried some javascript codes that do this: - adding the price (concatenate) on every click in a group instead of adding one price (one item can be selected in a group). <script type="text/javascript"> window.onload = function() { let somme = 0; var montant_commande = document.getElementById('montant_commande'); var Entree = document.getElementsByName('Entree'); var Plats = document.getElementsByName('Plats'); var Desserts = document.getElementsByName('Desserts'); var Boissons = document.getElementsByName('Boissons'); for(var i = 0; i < Entree.length; i++){ Entree[i].addEventListener('change', function() { if(this.checked){ updatePrix(2000); } }); } for(var i = 0; i < Plats.length; i++){ Plats[i].addEventListener('change', function() { if(this.checked){ updatePrix(5000); } }); } for(var i = 0; i < Desserts.length; i++){ Desserts[i].addEventListener('change', function() { if(this.checked){ updatePrix(3000); } }); } for(var i = 0; i < Boissons.length; i++){ Boissons[i].addEventListener('change', function() { if(this.checked){ updatePrix(1000); } }); } function updatePrix(total){ somme += total; montant_commande.value = somme; } } </script> I expect that : in a group, one element can be selected so no concatenation of the total sum while clicking others in the same group to select an item. A: I made the following snippet based on your provided code. Here is what I did: * *Added a form element so as to loop over the radio inputs once *Added the price to the radio's value attribute to generalize the calculation *Changed the updatePrix function to calculate the total when any input is changed let myForm = document.myForm; for (var i = 0; i < myForm.length; i++) { if (myForm[i].type === 'radio') { myForm[i].addEventListener('change', function() { updatePrix(); }); } } function updatePrix() { let somme = 0; let montant_commande = document.getElementById('montant_commande'); for (var i = 0; i < myForm.length; i++) { if (myForm[i].type === 'radio' && myForm[i].checked) { somme += parseInt(myForm[i].value, 10); montant_commande.value = somme; } } } <form name="myForm"> <input id="montant_commande" type="text" name="total" value="0" /><br/> <input type="radio" name="Entree" value="2000" />Entree 1<br /> <input type="radio" name="Entree" value="2000" />Entree 2<br /> <input type="radio" name="Entree" value="2000" />Entree 3<br /> <input type="radio" name="Plats" value="5000" />Plats 1<br /> <input type="radio" name="Plats" value="5000" />Plats 2<br /> <input type="radio" name="Plats" value="5000" />Plats 3<br /> <input type="radio" name="Desserts" value="3000" />Desserts 1<br /> <input type="radio" name="Desserts" value="3000" />Desserts 2<br /> <input type="radio" name="Desserts" value="3000" />Desserts 3<br /> <input type="radio" name="Boissons" value="1000" />Boissons 1<br /> <input type="radio" name="Boissons" value="1000" />Boissons 2<br /> <input type="radio" name="Boissons" value="1000" />Boissons 3<br /> </form>
doc_23535805
public Object myMethod(Object... many) { if (many == null || many.length == 0) return this; for (Object one : many) doSomethingWith(one); return that; } But then I wondered... Am I being too cautious? Do I have to check if many == null? Is that ever possible in any current Java version? If so, how? If not, I'll probably keep checking, just for futureproofing in case Oracle decides it can be null one day. A: I tried it with Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0 on Linux 3.5.0-21-generic Using myMethod(null) doesn't pass new Object[]{null}, it passes null. Arrays are objects in Java and therefore null is valid for the type Object[]. Your nullcheck is, therefore, not overly cautious.
doc_23535806
{{ Form::label('supplier_list', 'Supplier', array('class' => 'control-label')) }} {{ Form::select('supplier', $supplier_list, null, array('class' => 'form-control')) }} This is my code in controller $supplier_list = Supplier::lists('supplier_name', 'id'); My ouput is a Dropdown of SupplierName, what would I need is a Dropdown of displaying both SupplierName and ID, How to do it in laravel 4.2 ? A: Try this: In Controller $supplier_list = Supplier::lists('supplier_name', 'id')->get(); In Template <select name="id" class="form-control"> <option value="">Select Supplier Name</option> @foreach ($supplier_list as $key => $v) <option value="{!! $v['id'] !!}">{!! $v['supplier_name'] !!}{!! $v['id'] !!}</option> @endforeach </select>
doc_23535807
private void setUpList() { String[] items = {"item 1" , "item 2", "item 3","item 4" , "item 5", "item 6"}; ArrayAdapter arrayadp = new ArrayAdapter(this, R.layout.list_layout, items); setListAdapter(arrayadp); } and here is list_layout.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" </LinearLayout> If I change R.layout.list_layout to android.R.layout.simple_list_item_1 it works fine but I need to use a custom one. How do i do this without having the app crash. Here is the crash log 10-06 17:59:55.488: ERROR/AndroidRuntime(6941): FATAL EXCEPTION: main 10-06 17:59:55.488: ERROR/AndroidRuntime(6941): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.srose.forumapp/com.srose.forumapp.HotelsActivity}: java.lang.NullPointerException 10-06 17:59:55.488: ERROR/AndroidRuntime(6941): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1815) 10-06 17:59:55.488: ERROR/AndroidRuntime(6941): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1831) 10-06 17:59:55.488: ERROR/AndroidRuntime(6941): at android.app.ActivityThread.access$500(ActivityThread.java:122) 10-06 17:59:55.488: ERROR/AndroidRuntime(6941): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1024) 10-06 17:59:55.488: ERROR/AndroidRuntime(6941): at android.os.Handler.dispatchMessage(Handler.java:99) 10-06 17:59:55.488: ERROR/AndroidRuntime(6941): at android.os.Looper.loop(Looper.java:132) 10-06 17:59:55.488: ERROR/AndroidRuntime(6941): at android.app.ActivityThread.main(ActivityThread.java:4123) 10-06 17:59:55.488: ERROR/AndroidRuntime(6941): at java.lang.reflect.Method.invokeNative(Native Method) 10-06 17:59:55.488: ERROR/AndroidRuntime(6941): at java.lang.reflect.Method.invoke(Method.java:491) 10-06 17:59:55.488: ERROR/AndroidRuntime(6941): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841) 10-06 17:59:55.488: ERROR/AndroidRuntime(6941): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599) 10-06 17:59:55.488: ERROR/AndroidRuntime(6941): at dalvik.system.NativeStart.main(Native Method) 10-06 17:59:55.488: ERROR/AndroidRuntime(6941): Caused by: java.lang.NullPointerException 10-06 17:59:55.488: ERROR/AndroidRuntime(6941): at com.srose.forumapp.HotelsActivity.setupListView(HotelsActivity.java:38) 10-06 17:59:55.488: ERROR/AndroidRuntime(6941): at com.srose.forumapp.HotelsActivity.onCreate(HotelsActivity.java:29) 10-06 17:59:55.488: ERROR/AndroidRuntime(6941): at android.app.Activity.performCreate(Activity.java:4397) 10-06 17:59:55.488: ERROR/AndroidRuntime(6941): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048) 10-06 17:59:55.488: ERROR/AndroidRuntime(6941): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1779) 10-06 17:59:55.488: ERROR/AndroidRuntime(6941): ... 11 more new crash log 10-06 19:11:08.648: ERROR/ArrayAdapter(8552): You must supply a resource ID for a TextView 10-06 19:11:08.648: DEBUG/AndroidRuntime(8552): Shutting down VM 10-06 19:11:08.648: WARN/dalvikvm(8552): threadid=1: thread exiting with uncaught exception (group=0x40014760) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): FATAL EXCEPTION: main 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:390) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.widget.ArrayAdapter.getView(ArrayAdapter.java:366) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.widget.AbsListView.obtainView(AbsListView.java:1970) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.widget.ListView.measureHeightOfChildren(ListView.java:1228) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.widget.ListView.onMeasure(ListView.java:1139) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.view.View.measure(View.java:10828) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4351) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1284) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.widget.LinearLayout.measureVertical(LinearLayout.java:613) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.widget.LinearLayout.onMeasure(LinearLayout.java:519) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.view.View.measure(View.java:10828) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4351) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.widget.FrameLayout.onMeasure(FrameLayout.java:267) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.view.View.measure(View.java:10828) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4351) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1284) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.widget.LinearLayout.measureVertical(LinearLayout.java:613) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.widget.LinearLayout.onMeasure(LinearLayout.java:519) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.view.View.measure(View.java:10828) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4351) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.widget.FrameLayout.onMeasure(FrameLayout.java:267) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:1889) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.view.View.measure(View.java:10828) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.view.ViewRoot.performTraversals(ViewRoot.java:938) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.view.ViewRoot.handleMessage(ViewRoot.java:2040) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.os.Handler.dispatchMessage(Handler.java:99) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.os.Looper.loop(Looper.java:132) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.app.ActivityThread.main(ActivityThread.java:4123) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at java.lang.reflect.Method.invokeNative(Native Method) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at java.lang.reflect.Method.invoke(Method.java:491) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at dalvik.system.NativeStart.main(Native Method) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): Caused by: java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.TextView 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:383) 10-06 19:11:08.678: ERROR/AndroidRuntime(8552): ... 32 more A: try adding this to your textView android:id="@android:id/text1" , you need an id for textView , simple_list_item_1 has a textView with the above line. I think that is what you are missing. A: In addition to adding android:id="@android:id/text1", remove the Layout tags so that it looks like: <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/text1" android:layout_width="match_parent" android:layout_height="match_parent" />
doc_23535808
A: You can do something simple like creating a namespace and then putting your methods from signup.js, login.js and upload.js into it. This will allow you to put everything in one file. Example: var FormProcessor = {}; FormProcessor.prototype.signup_form_process = function() { }; FormProcessor.prototype.login_form_process = function() { }; FormProcessor.prototype.upload_form_process = function() { }; Then within your html files, just include the one js file and call your code like FormProcessor.signup_form_process(), etc...
doc_23535809
The reason I mention the chemical context is just to assure that this is a realistic example of what I am dealing with, not a made up one. In doing so, I need a regex expression that has the following structure: 1 - Starts by the chemical formula string "2h-tetrazolium, 2,2'-(3,3'-dimethoxy[1,1'-biphenyl]-4,4'-diyl)bis[3-(4-nitrophenyl)-5-phenyl-,chloride (1:2)" 2 - followed by 0 up to 15 characters 3 - followed by the chemical code string "298-83-9" 4 - followed by 0 up to 15 characters 5 - followed by a non-alphanumerical character 6 - followed by the string "5" 7 - ends with a non-alphanumerical value. The reason that I added the non-alphanumerical requirements #5 and #7 is that the text in which the regex search is to be performed is a long messy text and I wanted to ensure that the string "5" is not part of another entity such as these two examples: "bluh bluh 298-83-9 bluh bluh 564" or "bluh bluh 298-83-9 bluh bluh 645". The way I approached was building an expression like the following: reg_exp = name_entity[0] + r".{0,15}\s*" + name_entity[1] + r".{0,15}\s*" + r"[^a-zA-Z\d]+" + name_entity[2] + r"[^a-zA-Z\d]+" where name_entity is the array that contains the strings in requirements 1, 3, and 6. However, the issue is that the chemical formula and code in requirements 1 and 3 have so much escaping, hyphens, etc that my expression does not work. I need a way to prompt regex in thinking that name_entity elements are to be treated as exactly literal phrases, not containing some regex expression. In case it matters, I am coding in Python. I would appreciate your help. Here, I copy a portion of the multi-page long text that is intended to contain what the the regex expression is intended to find. The part that my python code re.findall(reg_exp, text) should find is bolded: "composition/information on ingredients substance / mixture : mixture substance name : nbt/bcip stock solution, mbf components chemical name cas-no. concentration (% w/w) methane, 1,1'-sulfinylbis- 67-68-5 >= 50 - < 70 2h-tetrazolium, 2,2'-(3,3'- dimethoxy[1,1'-biphenyl]-4,4'- diyl)bis[3-(4-nitrophenyl)-5-phenyl-, chloride (1:2) 298-83-9 >= 1 - < 5 actual concentration is withheld as a trade secret section 4. first aid measures general advice : do not leave the victim unattended. safety data sheet nbt/bcip stock solution version 3.0 revision date: 09-25-2019" A: There's a few issues here, but it works with the following code: def new_regex(entity): return fr"{re.escape(entity[0])}.{{0,15}}\s*{re.escape(entity[1])}.{{0,15}}\s*[^a-zA-Z\d]+{re.escape(entity[2])}[^a-zA-Z\d]+" entity = [ "2h-tetrazolium, 2,2'-(3,3'- dimethoxy[1,1'-biphenyl]-4,4'- diyl)bis[3-(4-nitrophenyl)-5-phenyl-, chloride (1:2)", '298-83-9', '5' ] n = "composition/information on ingredients substance / mixture : mixture substance name : nbt/bcip stock solution, mbf components chemical name cas-no. concentration (% w/w) methane, 1,1'-sulfinylbis- 67-68-5 >= 50 - < 70 2h-tetrazolium, 2,2'-(3,3'- dimethoxy[1,1'-biphenyl]-4,4'- diyl)bis[3-(4-nitrophenyl)-5-phenyl-, chloride (1:2) 298-83-9 >= 1 - < 5 actual concentration is withheld as a trade secret section 4. first aid measures general advice : do not leave the victim unattended. safety data sheet nbt/bcip stock solution version 3.0 revision date: 09-25-2019" regex = new_regex(entity) regex.findall(n) # ["2h-tetrazolium, 2,2'-(3,3'- dimethoxy[1,1'-biphenyl]-4,4'- diyl)bis[3-(4-nitrophenyl)-5-phenyl-, chloride (1:2) 298-83-9 >= 1 - < 5 "] This was fixed by using re.escape, as well as fixing a few issues with whitespace in your chemical formula. You likely however want to change your entities to handle whitespace better.
doc_23535810
I use Amazon SES. The app is hosted on AWS (multi core Linux instance). How to best write php to send emails at rapid rate by using multi-threading and multi-processing? Thanks. A: The AWS PHP SDK offers support for promises based on the guzzle promises implementation and the CommandPool to manage concurrent command execution. If the PHP language is optional for the email sending component in your application I'd recommend taking a look at AWS Lambda which would allow you to scale email processing to your maximum workload needs without needing to manage concurrency. Performance would also be highly predictable. Node.js, Python, Java and C# are currently supported in Lambda.
doc_23535811
I have a test file, call it test.R, that contains a bunch of testthat::test_that("test_name", {testthat::expect ...}) statements. If I run Rscript test.R, or if I just paste the statements from the test into the R console and manually check that the expect would pass, everything works as expected and my tests seem to succeed. However, if I use library(devtools); devtools::test(), there is a failing test with a subscript out of bounds error. I haven't included any specific code because I'm not looking to try to debug the particular error, but rather hope to understand how this is possible. Would testthat be running a different version? Is there differing behaviour between Rscript and the R console compared to what testthat would run under? A: FWIW, I experienced the same problem. In my case, the objects created in the script were not exactly the same as those created in a test helper file, so the tests were receiving slightly different information to the script, and hence were returning different results.
doc_23535812
Child function inheriting parent function through prototype works when I have both parent and child functions in same js file. Parent function: var BaseFunction = function (params) { } Child function: ChildFunction.prototype = new BaseFunction(); ChildFunction.prototype.constructor = ChildFunction; var ChildFunction = function (params) { BaseFunction.call(this, params); } If I move all the child related code to a different js file, it is complaining BaseFunction is not defined. So, I changed it to below. Now, it is ending up as undefined. ChildFunction.prototype = new window['BaseFunction'](); Wondering if inheriting a function from another file is possible? Greatly appreciate if you can share an example or point me to some article online. Thanks
doc_23535813
In case it matters, here is how I'm setting up my ModelMetadataProvider in my Global.asax: private void RegisterModelMetadataProvider() { var metadataProvider = DependencyResolver.Current.GetService<CustomModelMetadataProvider>(); ModelMetadataProviders.Current = metadataProvider; } A: [I'm answering my own question (Q&A style), but I'm not convinced this is an ideal solution. Please comment or leave an alternative answer if you have a better way (such as one that only needs configuration).] Instead of passing PropertyAccess directly into the singleton class, pass in a PropertyAccessLocator, which can be used to get the PropertyAccess for the current request as needed. Here is the PropertyAccessLocator public class PropertyAccessLocator { public PropertyAccess Get() { return DependencyResolver.Current.GetService<PropertyAccess>(); } } Here is an example ModelMetadataProvider public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider { private readonly PropertyAccessLocator _propertyAccessLocator; public CustomModelMetadataProvider( PropertyAccessLocator propertyAccessLocator) { _propertyAccessLocator = propertyAccessLocator; // required because PropertyAccess is request scoped // while this class is a singleton } protected override ModelMetadata CreateMetadata( IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName) { var metadata = base.CreateMetadata( attributes, containerType, modelAccessor, modelType, propertyName); var propertyAccess = _propertyAccessLocator.Get(); // todo use propertyAccess to do something with the metadata... return metadata; } }
doc_23535814
I have added the following in my .vimrc, which tells Vim to enable the mouse only in Normal Mode and Visual Mode. set mouse=nv However, this does not work. I can enter Operator-Pending Mode and still use a mouse click as the motion. Is it possible to tell Vim not to accept mouse clicks for motions in Operator-Pending Mode? A: :help 'mouse' won't help, here, so you can set it to a or any desired value. You could disable the left mouse in operator-pending mode, though: onoremap <LeftMouse> <Nop> which prevents mouse clicks motions in operator-pending mode. Note that, with that mapping, a mouse click is not considered as a motion anymore but it also sort of "breaks out" of operator-pending mode, which may or may not be a problem.
doc_23535815
[Timestamp] public byte[] TimeStamp { get; set; } throws the validation error Required. I am not setting any value on TimeStamp before save. Saving an existing item changes the TimeStamp in the DB as expected. This value is set by the DB itself and as such does not need to be initialized, or am I wrong here? EDIT: This works i think because it is nullable [ConcurrencyCheck] public int? RowVersion { get; set; } A new DB-Entry has null as value. Any change from within my app changes this and adds 1. A: This was a bug and is now fixed in v 0.76.4. You should be able to use SQL Server timestamps cleanly now. ... Thanks for finding this, Sascha.
doc_23535816
I have tried two different things. * *Constant throughput timer Thread count - 5 Target Throughput - 12.0 Calculated throughput - all active threads in current thread group Result : But i want only one request on 11:36:28.337 then second request is on 11:36:33.337 like this. *Throughput shapping timer Start RPS & End RPS = 0.2 Thread group - 5 Results : This result is also not satisfactory. Please provide me the correct configuration. Thanks in advance for any help. A: You need to either reduce number of threads to 1 or use reasonable ramp-up time as: * *Constant Throughput Timer is precise enough on minute level, don't expect it to pause the threads from the first second, let your test run for a while *If you need throughput limitation to be applied from the very beginning of your test make sure 2nd thread (virtual user) will be added not earlier than on 61st second of the test, i.e. set ramp-up time in the Thread Group to something like 300 given you kick off 5 threads. Despite its name Constant Throughput Timer doesn't need to be "constant", you can define the desired throughput via JMeter Property using __P() function like ${__P(throughput,)} and amend the property value using i.e. __setProperty() function or even outside JMeter via i.e. Beanshell Server, check out How to Adjust the RPS in Your JMeter Test via the Command Line guide for more details.
doc_23535817
On the email sent back to the customer, the order value has been updated and takes into consideration the refund, but the order quantity does not. The quantity stays the same. How can I make sure I am pulling the correct order quantity? When My customers come to collect their goods their receipt still shows they are to receive the original quantity? I know order quantities are stored in the table "woocommerce_order_item_meta" with a separate "order_item_id" for ordered quantity and refunded quantity, the latter signalled by an additional line: "_refunded_item_id". Do I need some code to sum the "_qty"'s? I would like my customer emails and order reports to show the correct quantity, so happy to make just make changes to order-items.php and create a function to input into my report plugin (wp All export) A: Actually, Woocommerce has no any default functionality to restore stock for cancelled and refunded orders. There is one of the plugin to solve this solution. Woocommerce Auto Restore Stock is the plugin that will help you to achieve this. It will automatically restore your WooCommerce inventory/stock for orders that were placed and refunded or canceled. Hope this will work for you. Thanks.
doc_23535818
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/background" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text="@string/one_string" android:onClick="goToScene2" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:text="@string/two_string" android:onClick="goToScene1" /> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="@string/three_string" /> <ImageView android:id="@+id/custView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:url="@drawable/panel_sets" /> </RelativeLayout> wich renders the activity like this (scene2 in transition): But i want to move ImageView like this image in order to later move it by aplying a transition in other layout.xml (this will be scene1). How can i do it? Thank you very much A: You Can Use Custom SlidingDrawer and canvas object to draw whatever you want 1.Create Custom class by implementing View and try this: Paint paint = new Paint(); paint.setStyle(Paint.Style.FILL);paint.setColor(Color.BLACK); canvas.drawPaint(paint);paint.setColor(Color.WHITE); canvas.drawCircle(100,100,30,paint); In XML Layout try to set yout custom class and slidingdrawer <SlidingDrawer xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/Mydrawer" android:layout_width="fill_parent" android:layout_height="fill_parent" android:handle="@+id/handle" android:content="@+id/content"><com.exmaple.MyCustomView android:id="@+id/customview" android:layout_width="fill_parent" android:layout_height="fill_parent"></com.exmaple.MyCustomView><ImageView android:id="@id/handle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/def_tray" /></SlidingDrawer> And finally in you Activity defined what happen when drawer close and open MyslidingDrawer.setOnDrawerCloseListener(new OnDrawerCloseListener() { @Overridepublic void onDrawerClosed(){}});MyCustomView customView = (MyCustomView) findViewById(R.id.mycontent);customView.setOnTouchListener(new OnTouchListener() {@Override public boolean onTouch(View v, MotionEvent event) {return true;}});
doc_23535819
admin.auth().setCustomUserClaims(uid, {groups: {groupId1: true, groupId2: true}, sections: {sectionId1: true}}); The documentation mentions only storing key - value pairs, not objects. The reason why I need it is that groupIds and sectionIds are auto-generated values, so I would prefere to not mix them together. I would like to read this claims later in (for instance) Realtime database security rules like this: { "rules": { "mydata": { "$groupId": { ".read": "auth.token.sections.sectionId1 === true" ".write": "auth.token.groups[$groupId] === true", } } } } Is this allowed in Firebase Authentication? A: Yes, you can store any JSON object in custom claims, up to the size limit of 1000 bytes. It should be easy to try for yourself.
doc_23535820
For fun, I looked into the .c file, and suddenly I saw the salt that I'm using for my license check.... not good. From the .c file: /* "delay.py":916 * log("serial: " + ser) * * enc = ser+"SecretSalt" # <<<<<<<<<<<<<< * h = hashlib.md5(enc.encode()) * lic = getIni('license','') */ Any ideas on how to improve this? Br Anders A: The first thing to realize is that Cython isn't designed to "protect" Python sources. It's a pretty weak protection, and is entirely accidental rather than by design. The second thing is that any "protection" you do get is when the .c file is compiled to a .so/.pyd file. The .c file itself will be very easy to read and work out what your code does. You can marginally improve things with the Cython directive emit_code_comments. Turning that off well at least make sure that the original Cython code isn't copied into the C file. However all your Python strings will still be there as C strings. Even if you compile the .c file then the strings will still be there in the compiled file in the data section of the .so/.pyd for anyone to see. It requires a little technical knowledge to find them, but not much. In summary, Cython isn't really the tool for this. If you really care about hiding details of your implementation then you'll have to implement your own solution. But there's a few small steps to make it marginally better.
doc_23535821
encodeURIComponent($("#customer_details").serialize()); and that doesn't work as expected. Is there way to get all elements on form and use encodeURIComponent to encode each value? A: It should already be encoded when using the serialize()[docs] method. From the docs: The .serialize() method creates a text string in standard URL-encoded notation. Example: http://jsfiddle.net/WArUG/ If you want to represent a space with a %20 instead of a +, you'll need to do a .replace(/\+/g,'%20').
doc_23535822
Id | Name | Parent ------------------------ 1 | name1 | null 2 | name2 | 1 3 | name3 | 1 4 | name4 | 2 So the result would be: | name1 | --------------------- | name2 | name4 | --------------------- | name3 | How do I pass this tree to View using recursion and how would it be displayed? I checked other threads similar to my question, but none had a complete answer. Thanks
doc_23535823
could get rid of boost's regex-implementation (boost version 1.54.0) and use the one provided by gcc (it didn't work with gcc before version 4.9 AFAIK). However, this turned out to be a problem because those two implementations behave differently: #include <regex> #include <boost/regex.hpp> #include <iostream> #include <string> int main() { std::string s="\\needs_another_backslash"; std::string reg("^(\\\\)(needs)(.+)"); std::string rep("\\\\got$3"); std::regex sr(reg); boost::regex br(reg); std::cout<<"string before replacement:\n"<<s<<std::endl<< "regular expression:\n"<<reg<<std::endl<< "replacement string:\n"<<rep<<std::endl<< "std::regex_replace:\n"<<std::regex_replace(s,sr,rep)<<std::endl<< "boost::regex_replace:\n"<<boost::regex_replace(s,br,rep)<<std::endl; return 0; } This gives the following output: string before replacement: \needs_another_backslash regular expression: ^(\\)(needs)(.+) replacement string: \\got$3 std::regex_replace: \\got_another_backslash boost::regex_replace: \got_another_backslash It seems as if boost treats the '\' in a replacement string specially whereas gcc does not. Since the magical character for backreference in the replacement string for std::regex_replace is '$' (which it also is in boost as the example proofs), I tend to think that gcc is right. However, in many other programs (like vim e.g.) it is '\'. Therefore, boost might have a point in treating '\' specially. So who is right? A: First, the std example actually is not a matter of gcc, but of C++ standard, to which gcc (in this case) is compliant. The standard states in 28.5.2: When a regular expression match is to be replaced by a new string, the new string shall be constructed using the rules used by the ECMAScript replace function in ECMA-262, part 15.5.4.11 String.prototype.replace. In addition, during search and replace operations all non-overlapping occurrences of the regular expression shall be located and replaced, and sections of the input that did not match the expression shall be copied unchanged to the output string. And ECMA states: Otherwise, let newstring denote the result of converting replaceValue to a String. The result is a String value derived from the original input String by replacing each matched substring with a String derived from newstring by replacing characters in newstring by replacement text as specified in Table 22. These $ replacements are done left-to-right, and, once such a replacement is performed, the new replacement text is not subject to further replacements. For example, "$1,$2".replace(/(\$(\d))/g, "$$1-$1$2") returns "$1-$11,$1-$22". A $ in newstring that does not match any of the forms below is left as is. (If part: replaceValue is a function.) Nothing mentioned about escape sequences being replaced. Tried out with firefox: var test = "\\needs_another_backslash"; test = test.replace(/^(\\)(needs)(.+)/, "\\\\got$3"); alert(test); Result: \\got_another_backslash. boost documentation states: Effects: If fmt is either a null-terminated string, or a container of char_type's, then copies the character sequence [fmt.begin(), fmt.end()) to OutputIterator out. For each format specifier or escape sequence in fmt, replace that sequence with either the character(s) it represents, or the sequence of characters within *this to which it refers. The bitmasks specified in flags determines what format specifiers or escape sequences are recognized, by default this is the format used by ECMA-262, ECMAScript Language Specification, Chapter 15 part 5.4.11 String.prototype.replace. Additionally, it states for match_type_flags: Specifies that when a regular expression match is to be replaced by a new string, that the new string is constructed using the rules used by the ECMAScript replace function in ECMA-262, ECMAScript Language Specification, Chapter 15 part 5.4.11 String.prototype.replace. (FWD.1). This is functionally identical to the Perl format string rules. [...] Tried with perl 5.18.2 on linux: my $test = "\\needs_another_backslash"; $test =~ s/^(\\)(needs)(.+)/\\\\got$3/; print "$test\n"; Resulted in \\got_another_backslash. With std::string reg("^(\\\\)(needs)(.+)");, as a string literal is passed, reg holds a string ^(\\)(needs)(.+) (not a literal, so left out the quotes!), and with std::string rep("\\\\got$3");, rep holds \\got$3. But there is obviously a difference in interpretation. Assume we had for both std and boost one and the same ECMAScript engine. Then, what both std and boost yet do consistently, is compiling the reg string as regular expression: sprintf(b, "/%s/", reg); sr /* br, respectively */ = ECMAScriptEngine::compileFromSource(b); I think this is reflected quite nicely by creating an instance of std/boost::regex class. Then comes the difference, however: std passes s, sr and rep to the ECMAScript engine such that it calls directly s.(String.prototype.replace)(sr, rep); (of course there is no such function for s in reality – just lets assume we could do it this way). boost lets compile the rep string, too (side note: I haven't installed boost, so I did not verify this behaviour myself...): sprintf(b, "'%s'", rep); // note: '', not //! ecma_rep = ECMAScriptEngine::compileFromSource(b); and then makes the engine call s.(String.prototype.replace)(sr, ecma_rep);. Interestingly, boost does not compile the source string s, where it again agrees with std... In the end, I think, however, the standard implementation reflects closer what we actually want to do: s.replace(regex, string); s.replace(/reg/, rep); (std::string).replace(std::regex(std::string), std::string); std::regex_replace(s, std::regex(reg), rep); vs s.replace(regex, string); s.replace(/reg/, "rep"); (std::string).replace(boost::regex(std::string), boost::???(std::string)); boost::regex_replace(s, boost::regex(reg), rep); // not boost::???(rep)! Not sure if this is sufficient to say one is right and the other wrong, however (would mean that the wrong one is buggy!). Possibly we even have to remain with a third option: Both approaches are valid (so both are right and none is wrong) and, unfortunately, they are incompatible...
doc_23535824
However, the method that I'm using is not working. It's my understanding the problem is that in Javascript, objects are passed by reference. Here's what I'm trying. let myArray = Array(10).fill({}); When I try to set the value of an object in the array, it sets the value for all of the objects (because they're all referring to the same place in memory, I think). For example: myArray[3]['text'] = 'Some text'; This returns the following array: 0: {text: "someText"} 1: {text: "someText"} 2: {text: "someText"} 3: {text: "someText"} 4: {text: "someText"} 5: {text: "someText"} 6: {text: "someText"} 7: {text: "someText"} 8: {text: "someText"} 9: {text: "someText"} How can I create an empty array and fill it with unique objects, so that I can set property values individually? My desired output would be: 0: {} 1: {} 2: {text: "someText"} 3: {} 4: {} 5: {} // And so on A: You take a constant value with Array#fill for filling. Instead, you need to map new object to the array and you could take Array.from and the built-in mapping. let myArray = Array.from({ length: 10 }, _ => ({})); myArray[3]['text'] = 'Some text'; console.log(myArray); .as-console-wrapper { max-height: 100% !important; top: 0; }
doc_23535825
I would like to edit VALUE_TIME for particular APP_NAME and APP_TYPE. So my query should look like below mentioned if VALUE_TIME column is Nullable. So what would be the best way to delete the data for particular condition ? UPDATE TABLE_NAME SET VALUE_TIME = null WHERE APP_NAME = 'XYZ' AND APP_TYPE = 'TEST'; Thanks A: If you want to delete the row: DELETE TABLE_NAME WHERE APP_NAME = 'XYZ' AND APP_TYPE = 'TEST'; The column VALUE_TYPE is defined as NOT NULL, so you can't set it to null. You could alter the table to make it nullable: ALTER TABLE TABLE_NAME MODIFY VALUE_TYPE VARCHAR2(500) NULL; And then run the UPDATE statement in your question. Hopefully this answers your question - it wasn't clear what you want to do exactly. A: Simple Answer, You can't update non-nullable column data to NULL or ' ' in oracle. I could only think of is Alter the column to have null. ALTER TABLE TABLE_NAME MODIFY VALUE_TYPE VARCHAR2(500) NULL
doc_23535826
<fa-icon class="file-excel-icon" title="Export to Excel" [icon]="['sil', 'file-excel']"></fa-icon> which translates to this html So the class file-excel-icon does get added to the element. I am now trying to modify some css of SVG element but it is never getting applied. I have tried this .file-excel-icon { border:1px solid red; svg { vertical-align: -0.170em !important; border:1px solid blue !important; } } and this .file-excel-icon { border:1px solid red; .svg-inline--fa { vertical-align: -0.170em !important; border:1px solid blue !important; } } and this .file-excel-icon .svg-inline--fa { vertical-align: -0.170em !important; border:1px solid blue !important; } But nothing seems to work for svg, no style is applying to it, while the style does apply to fa-icon element
doc_23535827
class Base{ public: virtual void foo(){....} }; class Derived{ public: void foo(){....} }; If d is a Derived object, can I in some way invoke the foo method defined in the Base class for this object? Edit: i mean from the outside, such that d.foo() binds to Base::foo() A: Specify it explicitly in the call. #include <iostream> class Base{ public: virtual void foo(){ std::cout << "Base" << std::endl; } }; class Derived : public Base{ public: void foo(){ std::cout << "Derived" << std::endl; } }; int main() { Derived d; d.Base::foo(); return 0; } A: Just qualify the call (Assuming that Derived actually inherits from Base, which in your code it doesn't): Derived d; d.Base::foo(); Now, while this is doable, it is also quite questionable. If the method is virtual, it is meant to be overridden and users should not call a particular override, but the final-overrider, or else they risk breaking class invariants all the way through. Consider that the implementation of Derived::foo did some extra work needed to hold some invariant, if users call Base::foo that extra work would not be done and the invariant is broken, leaving the object in an invalid state. A: To call it from outside code, you can still explicitly qualify the name in the call: #include <iostream> #include <vector> struct base { virtual void do_something() { std::cout << "Base::do_something();\n"; } }; struct derived : public base { virtual void do_something() { std::cout << "derived::do_something();\n"; } }; int main() { derived d; d.base::do_something(); return 0; } If you're using a pointer to the object, you'd change that to d->base::do_something();.
doc_23535828
Views.py: def showScrapbookPage(request,userID): if request.method == 'POST': image = ImageUploadForm(request.POST, request.FILES) user = User.objects.get(pk=userID) if image.is_valid(): image.save() scrapbook_gen = Pictures.objects url = Pictures.objects.filter(user=User.objects.get(pk=userID)) return render(request, 'scrapbook/scrapbook.html', {'scrapbook_gen':scrapbook_gen, 'url':url, 'form': ImageUploadForm(),'userID':userID}) class PhotoWizard(SessionWizardView): file_storage = FileSystemStorage(location = os.path.join(settings.MEDIA_ROOT, '')) def done(self, form_list, **kwargs): do_something_with_the_form_data(form_list) return HttpResponseRedirect('/page-to-redirect-to-when-done/') Models.py: class Pictures(models.Model): user = models.ForeignKey(User) picture = models.ImageField(upload_to = 'scrapbook_uploads', default = 'static/scrapbook/images/no_pic_uploaded.jpg'); date = models.DateTimeField('date published', auto_now=True) caption = models.TextField(blank = True) title = models.CharField(max_length = 100, blank = True) #New def __unicode__(self): return self.caption Forms.py: class ImageUploadForm(ModelForm): class Meta: model = Pictures fields = ['picture'] user = ['userID'] class TitleCommentForm(ModelForm): class Meta: model = Pictures field = ["caption", "title"] urls: url(r'^(?P<userID>[-\w]+)/scrapbook/',views.showScrapbookPage, name='showScrapbook'), url(r'^contact/$', PhotoWizard.as_view([ImageUploadForm, TitleCommentForm])), Relevant section in template: {% load i18n %} {% block head %} {{ wizard.form.media }} {% endblock %} {% block content %} <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="" method="post">{% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form }} {% endfor %} {% else %} {{ wizard.form }} {% endif %} </table> {% if wizard.steps.prev %} <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button> <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button> {% endif %} <input type="submit" value="{% trans "submit" %}"/> </form> {% endblock %} <!--Grid --> <div id='frame'> <table id = "frame-table"> <tr> <td id = "left"> <span class="glyphicon glyphicon-chevron-left" alt = "left"></span> </td> <td id = "right"> <span class = "glyphicon glyphicon-chevron-right" alt = "right"/> </td> </tr> </table> <img id = "main" src="" alt=""/> </div> <div id = "wrapper" class="showpiece"> <ul id = "portfolio"> {% for x in url %} {{ x.picture }} <li><img src = '{{ MEDIA_URL }}{{ x.picture }}' ></li> {% endfor %} </ul> </div> Thanks! A: Completely remove your added UserID stuff and use user = request.userinstead in your views.
doc_23535829
import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.ImageView; when I import andorid.graphics.Bitmap in classes in Jar File Android Studio shows error:Cannot resolve symbol 'Bitmap','BitmapFactory' 'Context'and .. I Follow these steps to build Jar File: File > New > New Module > java library I know how to use the library and I know that andorid api classes like Bitmap available in AAR (also in AAR file available resource file) my problem is the use android api classes in JAR File. A: You can create your .jar with own classes, that may be using Bitmap or any Android API class. This is a file BitmapHelper.java package com.its.test; import android.graphics.Bitmap; import android.graphics.BitmapFactory; public class BitmapHelper { public static void getBitmap(String fileName){ Bitmap bitmap= BitmapFactory.decodeFile(fileName); } } Jar file is just a zip file having number of .class file, so BitmapHelper.class file is inside my .jar When we need to use that .jar just add it in build path so that it compile. Or in gradle project put your .jar inside libs folder and compile in this way dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) } If you deployed your .jar in local/remote maven repo or any other you can compile by using group name, artifact and version of that artifact. The main difference between a Jar and a AAR is that AARs include resources such as layouts, drawables etc. This makes it a lot easier to create self-contained visual components. For example if you have multiple apps that use the same login screen, with Jars you could share classes but not the layout, styles, etc., you still had to duplicate them. With AARs everything is bundled in one neat package. EDIT Java Library is different from .jar, library is a collection of jars. You can easily integrate .jars into android project but if you want to add Java library than you need to define a binding between your pure java library and the android. You can check this answer. https://stackoverflow.com/a/42099343/3445320
doc_23535830
A: This is not currently possible in CSS3. In the future (CSS4?), you'll be able to do it as follows: body { background-color: red; transition: background-color 1s ease; } $body #theButton:hover { background-color: green; } Note the $ in the second selector; It indicates which element the CSS block applies to. Unfortunately, there's not even a single implementation of this yet, so you'll have to resort to Javascript (which I assume you know how to do. If not, just ask). Update (using jQuery): CSS: ​body { background: red; transition: background-color 1s ease; } body.hover { background: green; } Javascript: ​$('#theButton').hover(function(){ $('body').addClass('hover'); }, function(){ $('body').removeClass('hover'); });​​​​​​​​ Here's the fiddle: http://jsfiddle.net/mWY88/1/ For maximum efficiency, you should cache your selectors. A: In fact, you can change the body background-color very easily with CSS3 transition animation like I'm doing it here. I got the logic from here.
doc_23535831
Any help is greatly appreciated. let level = 0; let path; const getReply = (userInput) => { if (level === 0) { level = 1; if (userInput === "name") { path = "name"; return "Hello, name. Do you have like ice cream?"; } } if (level === 1) { level = 2; if (path === "yes") { if (userInput === "yes") { return "Great, what flavour do you like?"; } } A: let level = 0; const getReply = (userInput) => { if (level === 0) { level = 1; return "Hello, name. Do you have like ice cream?"; } if (level === 1) { level = 2; if (userInput === "yes") { return "Great, what flavour do you like?"; } } } console.log(getReply('Jack')); console.log(getReply('yes')); level = 0; console.log(getReply('Jill')); console.log(getReply('no'));
doc_23535832
g = [('a', 'w', 14), ('a', 'x', 7), ('a', 'y', 9), ('b', 'w', 9), ('b', 'z', 6), ('w', 'a', 14), ('w', 'b', 9), ('w', 'y', 2), ('x', 'a', 7), ('x', 'y', 10), ('x', 'x', 15), ('y', 'a', 9), ('y', 'w', 2), ('y', 'x', 10), ('y', 'z', 11), ('z', 'b', 6), ('z', 'x', 15), ('z', 'y', 11)] and would like to convert it to g = { 'a': {'w': 14, 'x': 7, 'y': 9}, 'b': {'w': 9, 'z': 6}, 'w': {'a': 14, 'b': 9, 'y': 2}, 'x': {'a': 7, 'y': 10, 'z': 15}, 'y': {'a': 9, 'w': 2, 'x': 10, 'z': 11}, 'z': {'b': 6, 'x': 15, 'y': 11}, } I am starting off with a text file where I have each tuple in a line as strings - not ordered: a w 14 b w 9 x a 7 ... To get to the list of tuples: have currently the following code: with open(filename, 'r') as reader: num_nodes = int(reader.readline()) edges = [] for line in islice(reader, num_nodes + 1, None): values = line.split() values[2] = int(values[2]) edges.append(tuple(values)) The text file has the following format: <number of nodes> <ID of node> ... <ID of node> <number of edges> <from node ID> <to node ID> <distance> ... <from node ID> <to node ID> <distance> Any help/advice is highly appreciated. A: Using itertools.groupby: from itertools import groupby from operator import itemgetter g_dict = {k: dict(x[1:] for x in grp) for k, grp in groupby(sorted(g), itemgetter(0))} print(g_dict) #{'a': {'w': 14, 'x': 7, 'y': 9}, # 'b': {'w': 9, 'z': 6}, # 'w': {'a': 14, 'b': 9, 'y': 2}, # 'x': {'a': 7, 'x': 15, 'y': 10}, # 'y': {'a': 9, 'w': 2, 'x': 10, 'z': 11}, # 'z': {'b': 6, 'x': 15, 'y': 11}} A: If you don't want to use anything outside the box you can just try: g = [('a', 'w', 14), ('a', 'x', 7), ('a', 'y', 9), ('b', 'w', 9), ('b', 'z', 6), ('w', 'a', 14), ('w', 'b', 9), ('w', 'y', 2), ('x', 'a', 7), ('x', 'y', 10), ('x', 'x', 15), ('y', 'a', 9), ('y', 'w', 2), ('y', 'x', 10), ('y', 'z', 11), ('z', 'b', 6), ('z', 'x', 15), ('z', 'y', 11)] g_dict = {} # Go through your list of tuples for element in g: # Check if we should create a new key or not if not element[0] in g_dict.keys(): # Create a new key g_dict[element[0]] = {} # Check if we need to make a new key or not for the inner dict if not element[1] in g_dict[element[0]].keys(): g_dict[element[0]][element[1]] = element[2] else: if not element[1] in g_dict[element[0]].keys(): g_dict[element[0]][element[1]] = element[2] print g_dict A: You could do this using defaultdict from collections like, >>> g [('a', 'w', 14), ('a', 'x', 7), ('a', 'y', 9), ('b', 'w', 9), ('b', 'z', 6), ('w', 'a', 14), ('w', 'b', 9), ('w', 'y', 2), ('x', 'a', 7), ('x', 'y', 10), ('x', 'x', 15), ('y', 'a', 9), ('y', 'w', 2), ('y', 'x', 10), ('y', 'z', 11), ('z', 'b', 6), ('z', 'x', 15), ('z', 'y', 11)] >>> from collections import defaultdict >>> d = defaultdict(dict) >>> >>> for item in g: ... a, b, c = item ... d[a].update({b: c}) ... >>> import pprint >>> pprint.pprint(dict(d)) {'a': {'w': 14, 'x': 7, 'y': 9}, 'b': {'w': 9, 'z': 6}, 'w': {'a': 14, 'b': 9, 'y': 2}, 'x': {'a': 7, 'x': 15, 'y': 10}, 'y': {'a': 9, 'w': 2, 'x': 10, 'z': 11}, 'z': {'b': 6, 'x': 15, 'y': 11}} A: This is a good case for using defaultdict from the collections module. from collections import defaultdict g = [('a', 'w', 14), ('a', 'x', 7), ('a', 'y', 9), ('b', 'w', 9), ('b', 'z', 6), ('w', 'a', 14), ('w', 'b', 9), ('w', 'y', 2), ('x', 'a', 7), ('x', 'y', 10), ('x', 'x', 15), ('y', 'a', 9), ('y', 'w', 2), ('y', 'x', 10), ('y', 'z', 11), ('z', 'b', 6), ('z', 'x', 15), ('z', 'y', 11)] d = defaultdict(dict) for k1, k2, v in g: d[k1].setdefault(k2, v) d # returns: defaultdict(dict, {'a': {'w': 14, 'x': 7, 'y': 9}, 'b': {'w': 9, 'z': 6}, 'w': {'a': 14, 'b': 9, 'y': 2}, 'x': {'a': 7, 'x': 15, 'y': 10}, 'y': {'a': 9, 'w': 2, 'x': 10, 'z': 11}, 'z': {'b': 6, 'x': 15, 'y': 11}}) A: I think the easiest solution would be new_dict = {i[0]: {j[1]:j[2] for j in g if j[0]==i[0]} for i in g} It will result in the dict you want. new_dict = {'x': {'y': 10, 'a': 7, 'x': 15}, 'z': {'b': 6, 'y': 11, 'x': 15}, 'y': {'w': 2, 'a': 9, 'x': 10, 'z': 11}, 'b': {'w': 9, 'z':6}, 'w': {'b': 9, 'y': 2, 'a': 14}, 'a': {'w': 14, 'x': 7, 'y': 9}}
doc_23535833
The behaviour I am trying to produce is similar to the Maps App. * *The pin can be dragged. *When there is a long press/ tap, a pin is dropped. However, I have problems having the long press being recognized outside the frame of the MKPinAnnotationView. The long press gesture to drop the pin works fine if the Pin is not draggable. When the pin is draggable however, I can't get the long press gesture recognizer to be recognized so that I can drop pin. Any ideas? By the way, I have tried to set the delegate for the long press recognizer so that - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer { return YES; } In this case, the long press gestures are recognized and the pins are dropped, but the dragging of the pin no longer works. Snippets of the MapView (a subclass of MKMapView) - (id)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { // init the gesture recognizer UILongPressGestureRecognizer* lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; lpgr.minimumPressDuration = 0.5f; //user needs to press for 2 seconds lpgr.delegate = self; [self addGestureRecognizer:lpgr]; [lpgr release]; //add some initial annotation Marker *_annotation = [[Marker alloc] initWithCoordinate:_location]; [_annotation titleWithString:@"some title"]; [self addAnnotation:_annotation]; } return self; } - (void)handleLongPress:(UIGestureRecognizer *)gestureRecognizer { if (gestureRecognizer.state != UIGestureRecognizerStateBegan) { return; } CGPoint touchPoint = [gestureRecognizer locationInView:self]; CLLocationCoordinate2D touchMapCoordinate = [self convertPoint:touchPoint toCoordinateFromView:self]; // add marker to self-map // Marker is subclass of MKAnnotation Marker *_annotation = [[Marker alloc] initWithCoordinate:_location]; [_annotation titleWithString:@"some title"]; [self addAnnotation:_annotation]; } - (MKAnnotationView *)mapView:(MKMapView *)mView viewForAnnotation:(id<MKAnnotation>) annotation { if([annotation isMemberOfClass:[Marker class]] ) { // use MKPinAnnotationView for the view MKPinAnnotationView *_pin = (MKPinAnnotationView *) [mView dequeueReusableAnnotationViewWithIdentifier:@"spot_pin"]; if (_pin == nil) { _pin = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"spot_pin"] autorelease]; } else { _pin.annotation = annotation; } [_pin setDraggable:YES]; [_pin setSelected:YES animated:YES]; [_pin setCanShowCallout:YES]; return _pin; } else { return nil; } } A: Ok guys, I solved it. Apparently when after I subclassed MKMapView, I also added a method handleLongPress. This method apparently interfered with the handleLongPress method of the MKMapView. Just by changing my handleLongPress selector to a different name like handleLongPress2 will make it work like the Maps app. UILongPressGestureRecognizer* lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress2:)];
doc_23535834
tar -zxvf PyOpenGL-3.0.2.tar.gz cd PyOpenGL-3.0.2 python3 setup.py install #I changed 'python' to 'python3' to install it to my python3. next, i typed these to install the accelerate package tar -zxvf PyOpenGL-accelerate-3.0.2.tar.gz cd PyOpenGL-accelerate-3.0.2 python3 setup.py install #Again, 'python' replaced with 'python3' Finally, I ran this code to test the install python3 >>>from OpenGL.GL import * which gave me this lovely string of errors Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/PyOpenGL-3.0.2-py3.3.egg/OpenGL/GL/__init__.py", line 3, in <module> from OpenGL.GL.VERSION.GL_1_1 import * File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/PyOpenGL-3.0.2-py3.3.egg/OpenGL/GL/VERSION/GL_1_1.py", line 10, in <module> from OpenGL import platform, constants, constant, arrays File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/PyOpenGL-3.0.2-py3.3.egg/OpenGL/arrays/__init__.py", line 19, in <module> from OpenGL.arrays.arraydatatype import * File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/PyOpenGL-3.0.2-py3.3.egg/OpenGL/arrays/arraydatatype.py", line 14, in <module> from OpenGL_accelerate.arraydatatype import ArrayDatatype as ADT File "arraydatatype.pyx", line 1, in init OpenGL_accelerate.arraydatatype (src/arraydatatype.c:9315) File "wrapper.pyx", line 2, in init OpenGL_accelerate.wrapper (src/wrapper.c:10792) ValueError: level must be >= 0 Any idea why it's acting up like this? EDIT: managed to get pyopengl working for python3 with following command: sudo pip-3.3 install PyOpenGL So... problem solved I guess... A: Answering my own question here, I managed to get PyOpenGL working with the command sudo pip-3.3 install PyOpenGl
doc_23535835
<h4 class="article_title_list" itemprop="name"> <a href="10-deutsche-pokemon-karten-sparpack">10 deutsche Pokemon Karten - mit Rare oder Holo/EX/GX - wie ein Booster!</a></h4> Python Code: page = requests.get(product_fetch_url, headers=headers) soup = BeautifulSoup(page.content, "html.parser") product_fetch_url_class = "article_title_list" product_fetch_url_html = "h4" find_urls = soup.find_all('{0}'.format(product_fetch_url_html), class_='{0}'.format(product_fetch_url_class)) for row in find_urls: string = row print("Produkt: {0}".format(string)) html = BeautifulSoup(string, "html.parser") for a in html.find('a', href=True): print("Produkt URL-Slug: {0}".format(a['href'])) Output: Produkt: <h4 class="article_title_list" itemprop="name"> <a href="10-deutsche-pokemon-karten-sparpack">10 deutsche Pokemon Karten - mit Rare oder Holo/EX/GX - wie ein Booster!</a></h4> Traceback (most recent call last): File "/usr/share/nginx/html/mp-masterdb/pokefri.de/scraper.py", line 45, in <module> fetch_urls() File "/usr/share/nginx/html/mp-masterdb/pokefri.de/scraper.py", line 38, in fetch_urls html = BeautifulSoup(string, "html.parser") File "/usr/lib/python3.10/site-packages/bs4/__init__.py", line 312, in __init__ markup = markup.read() TypeError: 'NoneType' object is not callable Excpeted Output: Produkt: <h4 class="article_title_list" itemprop="name"><a href="10-deutsche-pokemon-karten-sparpack">10 deutsche Pokemon Karten - mit Rare oder Holo/EX/GX - wie ein Booster!</a></h4> Produkt Url-slug: 10-deutsche-pokemon-karten-sparpack Any ideas how to solve this problem earlier with BeautifulSoup instead of re/regex? A: If you simply try to fetch the links, select your elements a bit more specific. for a in soup.select('h4>a'): print(a.get('href')) Or if you like to go per row: for e in soup.select('#product-list > div'): print(e.h4.a.get('href')) Example import requests from bs4 import BeautifulSoup soup = BeautifulSoup(requests.get('https://www.lotticards.de/pokemon-sammelkarten').text) for e in soup.select('#product-list > div'): print(e.h4.a.get('href')) Output 10-deutsche-pokemon-karten-sparpack Glaenzendes-Schicksal-Booster-Deutsch Pokemon-Celebrations-Booster-Packung-Deutsch Pikachu-V-Kollektion-Glaenzendes-Schicksal-Deutsch Verborgenes-Schicksal-Top-Trainer-Box Sun-Moon-Tag-Team-All-Stars-GX-High-Class-Pack-SM12a-Display-Japanisch Champions-Path-Elite-Trainer-Box-Englisch Glaenzendes-Schicksal-Mini-Tin-Set-Alle-5-Motive-Deutsch ... Or as list comprehension and based on itemprop="url": [a.get('content') for a in soup.select('#product-list [itemprop="url"]')] Output: ['https://www.lotticards.de10-deutsche-pokemon-karten-sparpack', 'https://www.lotticards.deGlaenzendes-Schicksal-Booster-Deutsch', 'https://www.lotticards.dePokemon-Celebrations-Booster-Packung-Deutsch', 'https://www.lotticards.dePikachu-V-Kollektion-Glaenzendes-Schicksal-Deutsch', 'https://www.lotticards.deVerborgenes-Schicksal-Top-Trainer-Box', 'https://www.lotticards.deSun-Moon-Tag-Team-All-Stars-GX-High-Class-Pack-SM12a-Display-Japanisch', 'https://www.lotticards.deChampions-Path-Elite-Trainer-Box-Englisch', 'https://www.lotticards.deGlaenzendes-Schicksal-Mini-Tin-Set-Alle-5-Motive-Deutsch', 'https://www.lotticards.deShining-Fates-Elite-Trainer-Box-Englisch', 'https://www.lotticards.deHidden-Fates-Elite-Trainer-Box-Reprint-Januar-2021', 'https://www.lotticards.deVMAX-Climax-s8b-Display-Japanisch', 'https://www.lotticards.deSonne-Mond-Ultra-Prisma-Booster-Deutsch', 'https://www.lotticards.desonne-mond-2-stunde-der-waechter-booster-deutsch-kaufen', 'https://www.lotticards.deSchwert-Schild-Kampfstile-Display-Deutsch', 'https://www.lotticards.dePokemon-Celebrations-Booster-Pack-Englisch',...]
doc_23535836
My GridView has a row defined the following way: <asp:TextBox ID="txtgvEmailAddress" Text = '<%# Eval("EMAIL")%>' runat="server" Width="200px" onclick="ResetMessage()"/> By doing that, onclick event is highlighted with a message saying that onclick is invalid attribute for element "TextBox". However it works fine on a page. But, I want to get rid of that error and do it the right way. GridView renders a table. The following is a table: <div> <table cellspacing="0" id="MainContent_GridView1" style="border-collapse:collapse;"> <tr> <th scope="col"><a href="javascript:__doPostBack(&#39;ctl00$MainContent$GridView1&#39;,&#39;Sort$CustID&#39;)">Customer ID</a></th><th scope="col"><a href="javascript:__doPostBack(&#39;ctl00$MainContent$GridView1&#39;,&#39;Sort$CustFirstName&#39;)">First Name</a></th><th scope="col"><a href="javascript:__doPostBack(&#39;ctl00$MainContent$GridView1&#39;,&#39;Sort$CustLastName&#39;)">Last Name</a></th><th scope="col"><a href="javascript:__doPostBack(&#39;ctl00$MainContent$GridView1&#39;,&#39;Sort$CustCity&#39;)">City</a></th><th scope="col">Email</th> </tr><tr> <td> <span id="MainContent_GridView1_lblCustID_0">12</span> </td><td> <span id="MainContent_GridView1_lblFirstName_0">Anders</span> </td><td> <span id="MainContent_GridView1_lblLastName_0">Rohansen</span> </td><td> <span id="MainContent_GridView1_lblCity_0">Takoma Park</span> </td><td> <input name="ctl00$MainContent$GridView1$ctl02$txtEmail" type="text" value="a.rohansen@testemail.com" id="MainContent_GridView1_txtEmail_0" /> <span data-val-controltovalidate="MainContent_GridView1_txtEmail_0" data-val-errormessage="Must enter Email Address" data-val-validationGroup="grpEmail" id="MainContent_GridView1_ctl00_0" data-val="true" data-val-evaluationfunction="RequiredFieldValidatorEvaluateIsValid" data-val-initialvalue="" style="visibility:hidden;">Must enter Email Address</span> <input type="submit" name="ctl00$MainContent$GridView1$ctl02$btnUpdate" value="Update Email" onclick="return ValidateEmail(this);WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$MainContent$GridView1$ctl02$btnUpdate&quot;, &quot;&quot;, true, &quot;grpEmail&quot;, &quot;&quot;, false, false))" id="MainContent_GridView1_btnUpdate_0" ButtonType="Button" /> </td> </tr><tr style="background-color:#EEEEEE;"> <td> <span id="MainContent_GridView1_lblCustID_1">8</span> </td><td> <span id="MainContent_GridView1_lblFirstName_1">Deborah</span> </td><td> <span id="MainContent_GridView1_lblLastName_1">Damien</span> </td><td> <span id="MainContent_GridView1_lblCity_1">Fresno</span> </td><td> <input name="ctl00$MainContent$GridView1$ctl03$txtEmail" type="text" value="d.damien@testemail.com" id="MainContent_GridView1_txtEmail_1" /> <span data-val-controltovalidate="MainContent_GridView1_txtEmail_1" data-val-errormessage="Must enter Email Address" data-val-validationGroup="grpEmail" id="MainContent_GridView1_ctl00_1" data-val="true" data-val-evaluationfunction="RequiredFieldValidatorEvaluateIsValid" data-val-initialvalue="" style="visibility:hidden;">Must enter Email Address</span> <input type="submit" name="ctl00$MainContent$GridView1$ctl03$btnUpdate" value="Update Email" onclick="return ValidateEmail(this);WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$MainContent$GridView1$ctl03$btnUpdate&quot;, &quot;&quot;, true, &quot;grpEmail&quot;, &quot;&quot;, false, false))" id="MainContent_GridView1_btnUpdate_1" ButtonType="Button" /> </td> </tr><tr> <td> <span id="MainContent_GridView1_lblCustID_2">7</span> </td><td> <span id="MainContent_GridView1_lblFirstName_2">Derek</span> </td><td> <span id="MainContent_GridView1_lblLastName_2">Chaddick</span> </td><td> <span id="MainContent_GridView1_lblCity_2">Fairfield</span> </td><td> <input name="ctl00$MainContent$GridView1$ctl04$txtEmail" type="text" value="d.chaddick@testemail.com" id="MainContent_GridView1_txtEmail_2" /> <span data-val-controltovalidate="MainContent_GridView1_txtEmail_2" data-val-errormessage="Must enter Email Address" data-val-validationGroup="grpEmail" id="MainContent_GridView1_ctl00_2" data-val="true" data-val-evaluationfunction="RequiredFieldValidatorEvaluateIsValid" data-val-initialvalue="" style="visibility:hidden;">Must enter Email Address</span> <input type="submit" name="ctl00$MainContent$GridView1$ctl04$btnUpdate" value="Update Email" onclick="return ValidateEmail(this);WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$MainContent$GridView1$ctl04$btnUpdate&quot;, &quot;&quot;, true, &quot;grpEmail&quot;, &quot;&quot;, false, false))" id="MainContent_GridView1_btnUpdate_2" ButtonType="Button" /> </td> </tr> </table> </div> What is the best way to reset label as soon as a email field is clicked? A: A little surprising may be, but this is the right way to do it. Here is some explanation form MSDN (actually this article is about doing the very same thing but with another control): Any attribute/value pairs in the control's markup that do not correspond to control properties are passed through to the browser as is. So basically what happens is that you are setting a nonexisting attribute to the control. ASP.NET does not recognize this attribute and gives you a warning about it. However it does not mean that there is an error - as you have said yourself everything is working fine. ASP.NET merely tries to ensure that you are not doing something wrong. However this attribute is something you have written intentionally - you can leave it, and it will be rendered as is in the resulting HTML. If it was not inside a data bound control, a more preferable way of doing it would be setting an Attributes collection: TextBox1.Attributes["onclick"]="ResetMessage();"; But since you are not able to retrieve your control by ID directly, you can either go with FindControl or set attribute in the markup - both are good options. Last slight comment - add a semicolon to the end of the js.
doc_23535837
Below is my requirement: I added product to the cart and set billing and shipping address also I selected the shipping method in PWA Store front. For payment selection I want to redirect current session/cart From PWA Storefront to the Magento store front . On the magento store Front I want to place order and after place order from magento store front redirect back to the PWA Studio How I will achieve above requirement. Please help
doc_23535838
In a component, named stockitems, I have a table which lists the products of the selected category. <ul class="list-group"> <li class="list-group-item d-flex justify-content-between align-items-center" *ngFor ="let stockitem of stockitems"> {{stockitem.name}} <span class="badge bg-primary rounded-pill">X</span> </li> </ul> When accessing the component, I know which category the user selected, but to fill the array 'stockitems' which generates the contents of my table, I use a service like 'SolarpanelService' or 'Inverterservice'. Now to decide which service to access, I use a switch/case-block : switch(this.category) { case "solarpanels" : this.SolarpanelService.getSolarpanel().subscribe( (response :Solarpanel[]) => { this.stockitems = response; }, (error) => console.log('Error'), () => console.log('ready') ); break; .... Now this works, but I was wondering whether I could actually compact the code so I don't have to write n case-blocks. In other words, I would like one code block that, depending on the selected category accesses the right service, method and model like : this."SelectedService".get"SelectedMethod"().subscribe( (response :"SelectedModel"[]) => { this.stockitems = response; }, (error) => console.log('Error'), () => console.log('ready') ); Where the "Selected..." would we SolarpanelService or InverterService or .... etc etc etc ... Basically I want to cast a variable name to a string that is then used to access the right stuff. I think it's a long shot, but maybe it's possible, or maybe there's a whole other way of doing these things. Thanks in advance ! A: You can use an object as a dictionary to look up your services, or their function, as you could use a dictionary for any kind of mapping from keys to values: const serviceMap = { "solarpanel": SolarPanelService.getSolarPanel, "inverters": InverterService.getInverter } let lookupFunction = serviceMap[selected] lookupFunction().subscribe( ... )
doc_23535839
Then I animate another CAShapeLayer (a square). It's constantly moving left and right. The CoreAnimation FPS which the profiler shows are very low (around 20-30) and you can see how much it lags on the device (iPad 3, iOS 8.1). I know that I could potentially increase the performance a little by rasterizing parts of the scene, but I'm looking for another appraoch here. How can I improve the performance of this demo project without rasterizing? (In my main project there's so many layers that I can't use rasterization as it will take up too much memory) Here's the project: https://dl.dropboxusercontent.com/u/40859730/CoreAnimationPerformanceTest.zip EDIT: I forgot to say that I'm CPU bound, the GPU usage is very very low, while the CARenderServer usage goes up to 100-120%
doc_23535840
set @string=(select [Bill Period] from [sqldata].[dbo].[jun1]) select substring (@string,1,3) i got just single value from the entire column [Bill period],i want all the record from [Bill Period] to @string but it is not working. how to increment table INDEX and fetch the records declare @INDEX int set @INDEX=1 while(@INDEX<3) begin Declare @string nvarchar(20) set @string=(select [Bill Period] from [sqldata].[dbo].[jun1]) select substring (@string,1,3) set @INDEX=@INDEX+1 end A: If [sqldata] is your DataBase name thenthe correct order would be: select [Bill Period] from [sqldata].[dbo].[jun1] A: You cannot use a column in a select statement: Taking: [dbo].[sqldata].[jun1] * *dbo is the schema *sqldata is the table - this is where you should select from *jun1 I don't know what this is. Try: Select Declare @string nvarchar(20) set @string=(select [Bill Period] from [dbo].[sqldata]) select substring (@string,1,3) or explain your problem / schema better. A: it Should be like [sqldata].[dbo].[jun1] ^database ^Schema ^Tablename The write Query: Declare @string nvarchar(20) set @string=(select [Bill Period] from [sqldata].[dbo].[jun1]) select substring (@string,1,3) A: Please make sure you are using correct server_name.database_name.schema_name.object_name. You don't need to use all those multipart identifiers but general idea is you should be looking at the correct place. Also, You should SELECT the TOP 1 record before assigning it into a variable, otherwise it will break once you get more than one record in the table Declare @String nvarchar(20) Select Top 1 @String = [Bill Period] From jun1 -- on correct database Order by yourColumn Select substring (@string,1,3) A: something wrong is in your query. make sure that you are calling it in a right way. as Luv answered- [sqldata].[dbo].[jun1] ^database ^Schema ^Tablename this is the format which is supported by SQL server.
doc_23535841
We are using the following telegraf configs * */etc/telegraf * *telegraf.conf (only configures [[agent]]) *telegraf.d * *inputs.conf *output.conf *processors.conf inputs.conf [[inputs.http]] urls = [ "http://myserver.mycompany.com:8080/some/rest/api", ] username = "user" password = "password" name_override = "monitor" interval = "600s" timeout = "3s" data_format = "json" json_query = "rows" json_string_fields = [ "size" ] tagexclude = ["host"] outputs.conf [[outputs.influxdb]] database = "metrics" urls = ["http://influxdb.mycompany.com:8086"] processors.conf [[processors.converter]] [processors.converter.fields] integer = [ "size" ] # Process order is VERY important here # Rename the url tag to target [[processors.rename]] [[processors.rename.replace]] tag = "url" dest = "target" # Extract the target name from the url (I know we just renamed it ... weird) [[processors.regex]] [[processors.regex.tags]] key = "url" pattern='^http://(?P<target>[^:/]+).+' replacement = "${target}" When I run: telegraf --config telegraf.conf --config-directory telegraf.d --test --debug --input-filter http I get back the data I expect and url has been replaced with the regex target i.e. monitor,target=myserver.mycompany.com size=123456789i 1627647959000000000 The problem is in the grafana graph I have created I see the original full url http://myserver.mycompany.com:8080/some/rest/api rather than the processed myserver.mycompany.com. Also very occasionally when I run the telegraf test I will see target returned with the full unprocessed url i.e. monitor,target=http://myserver.mycompany.com:8080/some/rest/api size=123456789i 1627647959000000000 The data is correct and has been processed i.e. the size string returned in the json is always converted to int and url is always renamed to target. Even stranger is I have pushed this config (with different urls in inputs.http depending on the region) to a number of servers and the majority of them work exactly as expected, it's just a few that have this behaviour. I have checked and made sure that all the versions of telegraf on each server match (1.19.1) and they are all running on Centos 7. I have also tried clearing the data from the influxdb. The few servers that return the url in the target always do so, even though when I run the telegraf test on them they show the host stripped out as they should. Any hints as to where to look next? A: I have found the cause! From the telegraf docs. The following config parameters are available for all processors: order: This is the order in which the processor(s) get executed. If this is not specified then processor execution order will be random. Even my comments reveal why it's an issue # Process order is VERY important here # Rename the url tag to target # Extract the target name from the url (I know we just renamed it ... weird) Yes it is weird, but that was because I happened to keep hitting the same 50:50 chance in my tests but the other order is equally likely. When in the wrong order the key is renamed and the regex has nothing to process on. The solution is to use order. processors.conf [[processors.converter]] [processors.converter.fields] integer = [ "size" ] # Extract the target name from the url [[processors.regex]] order = 1 [[processors.regex.tags]] key = "url" pattern='^http://(?P<target>[^:/]+).+' replacement = "${target}" # Rename the url tag to target [[processors.rename]] order = 2 [[processors.rename.replace]] tag = "url" dest = "target" Now the regex will always run before the rename.
doc_23535842
HTML Code <!doctype html> <html class="no-js" lang="en" dir="ltr"> <head> <base href="/"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Test</title> <meta name="description" content="Description"> </head> <body> <jhi-root></jhi-root> </body> </html> Next code snippet is one of the template I use in my project. <div class="d-flex" id="wrapper"> <jhi-sidebar></jhi-sidebar> <div id="page-content-wrapper"> <jhi-header></jhi-header> <div class="inner-page"> <div class="container-fluid"> <div class="row"> <div class="col-12"> <h3 class="card-title text-left">Widgets</h3> </div> </div> </div> <p> Link1 &nbsp; </p> <p> Link2 &nbsp; </p> <p> Link3 &nbsp; </p> </div> </div> </div> Below is the output that is displayed when the above template is rendered. We can see that space is created but with extra special character not sure. Link1  Link2  Link3  I have checked encoding type its UTF-8 but still I didnt understand why a weird character is displayed when rendered. Please help A: That'd be encoding to UTF-8 then, not ISO-8859-1. The non-breaking space character is byte 0xA0 in ISO-8859-1; when encoded to UTF-8 it'd be 0xC2,0xA0, which, if you (incorrectly) view it as ISO-8859-1 comes out as " " Ref Use <meta charset="utf-8">
doc_23535843
Below is the code I am using, can anyone explain what I am doing wrong? The first open always succeeds and the write also always succeeds. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"file.txt"]; result = remove([appFile cStringUsingEncoding:NSASCIIStringEncoding]); int fp = open([appFile cStringUsingEncoding:NSASCIIStringEncoding], O_RDWR | O_CREAT); result = write(fp, "abc", 3); close(fp); fp = open([appFile cStringUsingEncoding:NSASCIIStringEncoding], O_RDONLY); NSLog(@"fp = %i, errno = %i", fp, errno); close(fp); A: From the manpage for open(2): The oflag argument may indicate that the file is to be created if it does not exist (by specifying the O_CREAT flag). In this case, open requires a third argument mode_t mode; As you do not specify the 3rd argument, it will use a random value, that's why it fails sometimes. Add a 3rd parameter 0644, then it will always work. A: Open file folder must have executable permissions, so use: chmod 0760 "dir"
doc_23535844
number = 001 def palindrome(number): print ("The number is: ",number) str1 = str(number) strrev = str1[::-1] if (str1 == strrev): return True else: a = int(str1) b = int(strrev) c = a+b print ("Sum with reverse: ",c) print (" ") return (palindrome(c)) n = palindrome(number) print ("Palindrome: ",n) A: 001 is an integer it will work as 1, instead of 001. If you need 001 use it as string not an integer. As 001 is invalid integer, but when it comes to string variable it works fine. Use : stringNumber = '001'
doc_23535845
function aiStartTimer() { if (shoot == 0) { //creates aitimer variable AItimer = setInterval("aiFireBullet()", 100); shoot = 1 * 1; } else if (shoot == 1) { clearInterval(AItimer); shoot = 0 * 1; } } Here is a JSFiddle A: After changing the order it works so if I have learned something order is important A: * *I do not know if ai timer is declared but it probably is *setInterval does not need a string or (). Proper syntax for setInterval is setInterval(aiFireBullet, 100) *For the shoot variable you do not need to use 1 * 1 or 0 * 1, just use shoot = 1 and shoot = 0
doc_23535846
The code works fine in Safari browser but it always fails to show the joiners videos in a simple ios phonegap app. so basically no one can see others videos. I added iosrtc plugin to my app as well... Spent days trying to find the issue and I think I am getting close. I found out that the event.type is always local for everyone. So, the event.type is never remote for anyone that uses the app. But when i test the same code in safari browser, the first joiner event.type is local and the rest of the joiners event.type is remote and thats why it works fine in the browser. Now that I found the issue (sort of), I need to know why this is happening in the phonegap app and how to eradicate it. This is my entire code, you can run this code directly in your browser as is and it will work fine: Javascript: // ...................................................... // .......................UI Code........................ // ...................................................... document.getElementById('open-room').onclick = function() { disableInputButtons(); connection.open(document.getElementById('room-id').value, function(isRoomOpened, roomid, error) { if(isRoomOpened === true) { showRoomURL(connection.sessionid); } else { disableInputButtons(true); if(error === 'Room not available') { alert('Someone already created this room. Please either join or create a separate room.'); return; } alert(error); } }); }; document.getElementById('join-room').onclick = function() { disableInputButtons(); connection.join(document.getElementById('room-id').value, function(isJoinedRoom, roomid, error) { if (error) { disableInputButtons(true); if(error === 'Room not available') { alert('This room does not exist. Please either create it or wait for moderator to enter in the room.'); return; } alert(error); } }); }; document.getElementById('open-or-join-room').onclick = function() { disableInputButtons(); connection.openOrJoin(document.getElementById('room-id').value, function(isRoomExist, roomid, error) { if(error) { disableInputButtons(true); alert(error); } else if (connection.isInitiator === true) { // if room doesn't exist, it means that current user will create the room showRoomURL(roomid); } }); }; // ...................................................... // ..................RTCMultiConnection Code............. // ...................................................... var connection = new RTCMultiConnection(); // by default, socket.io server is assumed to be deployed on your own URL //connection.socketURL = '/'; // comment-out below line if you do not have your own socket.io server connection.socketURL = 'https://rtcmulticonnection.herokuapp.com:443/'; connection.socketMessageEvent = 'video-conference-demo'; connection.session = { audio: true, video: true }; connection.sdpConstraints.mandatory = { OfferToReceiveAudio: true, OfferToReceiveVideo: true }; connection.videosContainer = document.getElementById('videos-container'); connection.onstream = function(event) { var video = document.createElement('video'); if(event.type === 'local') { video.setAttribute('class', 'myvideo'); //$('.yourVideo').attr('src', event.stream); //$('.yourVideo').attr('id', event.streamid); //alert('local'); /*video.volume = 0; try { video.setAttributeNode(document.createAttribute('muted')); } catch (e) { video.setAttribute('muted', true); }*/ } if (event.type === 'remote') { alert('remote'); video.setAttribute('class', 'othersvideo'); } //video.src = URL.createObjectURL(event.stream); setTimeout(function() { var existing = document.getElementById(event.streamid); if(existing && existing.parentNode) { existing.parentNode.removeChild(existing); } event.mediaElement.removeAttribute('src'); event.mediaElement.removeAttribute('srcObject'); event.mediaElement.muted = true; event.mediaElement.volume = 0; try { video.setAttributeNode(document.createAttribute('autoplay')); video.setAttributeNode(document.createAttribute('playsinline')); } catch (e) { video.setAttribute('autoplay', true); video.setAttribute('playsinline', true); } console.log(JSON.stringify(event)); video.srcObject = event.stream; var width = parseInt(connection.videosContainer.clientWidth / 3) - 20; var width = $(document).width(); var height = $(document).height(); var mediaElement = getHTMLMediaElement(video, { /*title: event.userid,*/ buttons: ['full-screen'], width: width, showOnMouseEnter: false }); connection.videosContainer.appendChild(mediaElement); mediaElement.media.play(); var isInitiator = connection.isInitiator; if (isInitiator === true && event.type === 'local') { // initiator's own stream alert('you are initiator'); }else{ alert('you are remote'); } mediaElement.id = event.streamid; //video.play(); }, 5000); }; var recordingStatus = document.getElementById('recording-status'); var chkRecordConference = document.getElementById('record-entire-conference'); var btnStopRecording = document.getElementById('btn-stop-recording'); btnStopRecording.onclick = function() { var recorder = connection.recorder; if(!recorder) return alert('No recorder found.'); recorder.stopRecording(function() { var blob = recorder.getBlob(); invokeSaveAsDialog(blob); connection.recorder = null; btnStopRecording.style.display = 'none'; recordingStatus.style.display = 'none'; chkRecordConference.parentNode.style.display = 'inline-block'; }); }; connection.onstreamended = function(event) { var mediaElement = document.getElementById(event.streamid); if (mediaElement) { mediaElement.parentNode.removeChild(mediaElement); } }; connection.onMediaError = function(e) { if (e.message === 'Concurrent mic process limit.') { if (DetectRTC.audioInputDevices.length <= 1) { alert('Please select external microphone. Check github issue number 483.'); return; } var secondaryMic = DetectRTC.audioInputDevices[1].deviceId; connection.mediaConstraints.audio = { deviceId: secondaryMic }; connection.join(connection.sessionid); } }; // .................................. // ALL below scripts are redundant!!! // .................................. function disableInputButtons(enable) { document.getElementById('room-id').onkeyup(); document.getElementById('open-or-join-room').disabled = !enable; document.getElementById('open-room').disabled = !enable; document.getElementById('join-room').disabled = !enable; document.getElementById('room-id').disabled = !enable; } // ...................................................... // ......................Handling Room-ID................ // ...................................................... function showRoomURL(roomid) { var roomHashURL = '#' + roomid; var roomQueryStringURL = '?roomid=' + roomid; var html = '<h2>Unique URL for your room:</h2><br>'; html += 'Hash URL: <a href="' + roomHashURL + '" target="_blank">' + roomHashURL + '</a>'; html += '<br>'; html += 'QueryString URL: <a href="' + roomQueryStringURL + '" target="_blank">' + roomQueryStringURL + '</a>'; var roomURLsDiv = document.getElementById('room-urls'); roomURLsDiv.innerHTML = html; roomURLsDiv.style.display = 'block'; } (function() { var params = {}, r = /([^&=]+)=?([^&]*)/g; function d(s) { return decodeURIComponent(s.replace(/\+/g, ' ')); } var match, search = window.location.search; while (match = r.exec(search.substring(1))) params[d(match[1])] = d(match[2]); window.params = params; })(); var roomid = ''; if (localStorage.getItem(connection.socketMessageEvent)) { roomid = localStorage.getItem(connection.socketMessageEvent); } else { roomid = connection.token(); } var txtRoomId = document.getElementById('room-id'); txtRoomId.value = roomid; txtRoomId.onkeyup = txtRoomId.oninput = txtRoomId.onpaste = function() { localStorage.setItem(connection.socketMessageEvent, document.getElementById('room-id').value); }; var hashString = location.hash.replace('#', ''); if (hashString.length && hashString.indexOf('comment-') == 0) { hashString = ''; } var roomid = params.roomid; if (!roomid && hashString.length) { roomid = hashString; } if (roomid && roomid.length) { document.getElementById('room-id').value = roomid; localStorage.setItem(connection.socketMessageEvent, roomid); // auto-join-room (function reCheckRoomPresence() { connection.checkPresence(roomid, function(isRoomExist) { if (isRoomExist) { connection.join(roomid); return; } setTimeout(reCheckRoomPresence, 5000); }); })(); disableInputButtons(); } // detect 2G if(navigator.connection && navigator.connection.type === 'cellular' && navigator.connection.downlinkMax <= 0.115) { alert('2G is not supported. Please use a better internet service.'); } $(document).on('click', '.mybtn', function() { window.cordova.InAppBrowser.open(" https://vps267717.ovh.net/webrtc", "_blank", "location=no,toolbar=yes"); }); HTML: <!-- Demo version: 2019.01.09 --> <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Video Conferencing using RTCMultiConnection</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0"> <script> setTimeout(function() { navigator.splashscreen.hide(); }, 4000); // alert dialog dismissed function alertDismissed() { } </script> <link rel="stylesheet" href="https://rtcmulticonnection.herokuapp.com/demos/stylesheet.css"> <script src="https://rtcmulticonnection.herokuapp.com/demos/menu.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://rtcmulticonnection.herokuapp.com/dist/RTCMultiConnection.min.js"></script> <script src="https://rtcmulticonnection.herokuapp.com/node_modules/webrtc-adapter/out/adapter.js"></script> <script src="https://rtcmulticonnection.herokuapp.com/socket.io/socket.io.js"></script> <!-- custom layout for HTML5 audio/video elements --> <link rel="stylesheet" href="https://rtcmulticonnection.herokuapp.com/dev/getHTMLMediaElement.css"> <script src="https://rtcmulticonnection.herokuapp.com/dev/getHTMLMediaElement.js"></script> <script src="https://rtcmulticonnection.herokuapp.com/node_modules/recordrtc/RecordRTC.js"></script> <script src="cordova.js"></script> <script src="ios-websocket-hack.js"></script> <style> /* .myvideo{ width:100px !important; height:100px !important; background:#ccc; position:absolute; top:0; left:0; z-index:10; } .othersvideo{ width:100% !important; height:100% !important; background:#ccc; position:absolute; top:0; left:0; z-index:0; }*/ * { word-wrap:break-word; } video { object-fit: fill; width: 30%; } button, input, select { font-weight: normal; padding: 2px 4px; text-decoration: none; display: inline-block; text-shadow: none; font-size: 16px; outline: none; } .make-center { text-align: center; padding: 5px 10px; } img, input, textarea { max-width: 100% } @media all and (max-width: 500px) { .fork-left, .fork-right, .github-stargazers { display: none; } } </style> </head> <body> <button class="mybtn" >click me now</button> <section class="make-center"> <div> <label><input type="checkbox" id="record-entire-conference"> Record Entire Conference In The Browser?</label> <span id="recording-status" style="display: none;"></span> <button id="btn-stop-recording" style="display: none;">Stop Recording</button> <br><br> <input type="text" id="room-id" value="abcdef" autocorrect=off autocapitalize=off size=20> <button id="open-room">Open Room</button> <button id="join-room">Join Room</button> <button id="open-or-join-room">Auto Open Or Join Room</button> </div> <div id="videos-container" style="margin: 20px 0;"></div> <div id="room-urls" style="text-align: center;display: none;background: #F1EDED;margin: 15px -10px;border: 1px solid rgb(189, 189, 189);border-left: 0;border-right: 0;"></div> </section> <script src="https://cdn.webrtc-experiment.com/common.js"></script> </body> </html> Any help would be greately appreciated. Thanks in advance.
doc_23535847
CREATE TABLE classes ( class_id INT NOT NULL, class_name VARCHAR(50) NOT NULL, PRIMARY KEY (class_id), UNIQUE (class_name) ); Then I created labs table as: CREATE TABLE labs ( lab_id INT NOT NULL, lab_name VARCHAR(50) NOT NULL, class_id INT NOT NULL, PRIMARY KEY (lab_id), UNIQUE (lab_name), FOREIGN KEY (class_id) REFERENCES classes (class_id) ); After this I created students table as: CREATE TABLE students ( student_id INT AUTO_INCREMENT NOT NULL, student_name VARCHAR(50) NOT NULL, class_id INT NOT NULL, PRIMARY KEY (student_id), FOREIGN KEY (class_id) REFERENCES classes (class_id) ); And finally I created allotments table to allocate the laboratories for students as: CREATE TABLE allotments ( student_id INT NOT NULL, lab_id INT NOT NULL, day_of_week CHAR(3) NOT NULL, PRIMARY KEY (student_id, lab_id), FOREIGN KEY (student_id) REFERENCES students (student_id), FOREIGN KEY (lab_id) REFERENCES labs (lab_id) ); This seems fine. But I want to add a CHECK constraint to allotments table such that students are allocated to the laboratories of their respective classes only, something like this: ALTER TABLE allotments ADD CHECK (student_id IN (SELECT student_id FROM students INNER JOIN labs USING (class_id) WHERE students.class_id = labs.class_id)); But when I tried this I got the following error message: Error Code: 3815. An expression of a check constraint 'allotments_chk_1' contains disallowed function. 0.000 sec Please help me with a solution. A: I followed the idea of @P.Salmon to use a trigger and I found a way to apply the integrity constraint such that a user can only allot a lab to a student only if student_id and lab_id both belongs to the same class. Here is the trigger to use: DELIMITER $$ CREATE TRIGGER before_allotments_insert BEFORE INSERT ON allotments FOR EACH ROW BEGIN DECLARE students_class_id, labs_class_id INT; DECLARE error_message VARCHAR(100); SET error_message = CONCAT('Invalid lab_id for student_id ', NEW.student_id); SELECT class_id INTO students_class_id FROM students WHERE student_id = NEW.student_id; SELECT class_id INTO labs_class_id FROM labs WHERE lab_id = NEW.lab_id; IF students_class_id <> labs_class_id THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = error_message; END IF; END $$ DELIMITER ; This trigger invokes automatically when a user tries to insert a new allotment for a student and validates the entry. If student_id and lab_id does not belong to same class, then an error message is displayed, restricting its entry.
doc_23535848
I checked the logs printed and it shows me a log saying: "I/GCM﹕ GCM message com.package.name 0:1438085xxxxxxxxxxxxxxxxxx" and it means the message is received by the device but it is not forwarded to the app. Any suggestions? Here's how my implementation for onMessageReceived: public void onMessageReceived(String from, Bundle data) { Logger.info(TAG, "GOT PUSH NOTIFICATION"); final Session session = Session.getInstance(); if(session == null){ Logger.error("Not Handling Message.\nSession does not exist."); return; }else{ if(session.apiKey == null){ Logger.error("Not Handling Message.\nUser is not Logged In."); return; } } /** * IF ACTIVITY IS IN CLOSED STATE STOP PRICE TIMER * */ if(session.activityInClosedState){ new Thread(new Runnable() { @Override public void run() { Logger.info("Stopping Price Timer"); session.stopTimer(); } }).start(); } /** ALWAYS WORKS IN BACKGROUND THREAD*/ try{ PushNotification pushNotification = new PushNotification(data); updateNotificationBar(pushNotification); session.onNewAlert(); }catch (Exception ex){ Logger.error("Exception: "+ex); } } Here is the Manifest file: <?xml version="1.0" encoding="utf-8"?> <uses-feature android:glEsVersion="0x00020000" android:required="false"/> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> <permission android:name="com.sentieo.gcm.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <uses-permission android:name="com.sentieo.gcm.permission.C2D_MESSAGE" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <application android:allowBackup="true" android:name=".objects.Session" android:icon="@mipmap/appicon" android:label="@string/app_name" android:theme="@style/AppTheme" android:hardwareAccelerated="true" > <activity android:name=".MainActivity" android:label="@string/app_name" android:windowSoftInputMode="adjustPan" android:screenOrientation="portrait" android:launchMode="singleTop" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!--GCM REGISTRATION STARTS --> <receiver android:name="com.google.android.gms.gcm.GcmReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND" > <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> <category android:name="com.sentieo.gcm" /> </intent-filter> </receiver> <receiver android:name=".pushnotifications.GCMListenerService$NotificationCancelledBroadCastReceiver" android:exported="false" > </receiver> <service android:name=".pushnotifications.RegistrationIntentService" android:enabled="true"></service> <service android:name=".pushnotifications.GCMListenerService" android:exported="false" > <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> </intent-filter> </service> <service android:name=".pushnotifications.InstanceIDListenerService" android:exported="false"> <intent-filter> <action android:name="com.google.android.gms.iid.InstanceID"/> </intent-filter> </service> <!--GCM REGISTRATION ENDS --> </application> A: Try putting these permission in your receiver tag of the manifest file: <receiver android:name=".MyReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </receiver> Also put this permission: <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
doc_23535849
body { background-image: url("https://www.theuiaa.org/wp-content/uploads/2017/12/2018_banner.jpg"); background-attachment: fixed; background-repeat: no-repeat; background-position: center; background-size: cover; height: 200vh; background-color: rgba(255, 255, 255, 0.5); background-blend-mode: soft-light; } .container { display: flex; align-items: center; justify-content: center; height: 50%; } .card { display: flex; align-items: center; justify-content: space-between; flex-direction: column; width: 320px; height: 540px; background: rgba(255, 255, 255, 0.3); backdrop-filter: blur(15px); } .arrow { position: sticky; top: 0px; font-size: 200px; line-height: 1; color: red; } .card p { font-size: 32px; padding: 20px; } <div class="container"> <div class="card"> <div class="arrow"><span>&#129041;</span></div> <p>As you can see when you scroll down, as soon as the card hits the top of the screen, you get a blurred edge. Not cool...</p> </div> </div> Codepen A: I think you found a Chrome issue! (It doesn't happen in Firefox). I very quickly checked in chromium bugs and did not found anything close.. So I suggest you report it! Additionnaly, I made a test to determine where that black "gradient" was coming from... I changed the background color of Codepen's .main-header!! To reproduce, paste that in the console: document.querySelector(".main-header").style.background = "red" The expected result is: But the surprise is the "gradient" now turned red. You certainly know that the codepen result is an iframe... So I think that is called a "paint" issue.
doc_23535850
Unexpected character encountered while parsing value: {. Path '[0]', line 1, position 3. The JSON Text validated properly using JSONLint.com, here is the JSON text: [ [ {"trackingNo":"R2E2003100011429","eventTime":1479184076000,"eventCode":"INF","activity":"Shipping Information received by Australia Post","location":"","referenceTrackingNo":null}, {"trackingNo":"R2E2003100011429","eventTime":1479186149000,"eventCode":"INF","activity":"Shipping Information approved by Australia Post","location":"","referenceTrackingNo":null}, {"trackingNo":"R2E2003100011429","eventTime":1479448620000,"eventCode":"SCN","activity":"Departed facility","location":"","referenceTrackingNo":null} ], [ {"trackingNo":"HBF0003142011420","eventTime":1478666798000,"eventCode":"INF","activity":"Shipping Information received by Australia Post","location":"","referenceTrackingNo":null}, {"trackingNo":"HBF0003142011420","eventTime":1478732453000,"eventCode":"INF","activity":"Shipping Information approved by Australia Post","location":"","referenceTrackingNo":null}, {"trackingNo":"HBF0003142011420","eventTime":1478932980000,"eventCode":"SCN","activity":"Departed facility","location":"","referenceTrackingNo":null}, {"trackingNo":"HBF0003142011420","eventTime":1479082255000,"eventCode":"SCN","activity":"Arrived at facility in destination country","location":"","referenceTrackingNo":null}, {"trackingNo":"HBF0003142011420","eventTime":1479082261000,"eventCode":"CCD","activity":"Cleared by customs","location":"","referenceTrackingNo":null}, {"trackingNo":"HBF0003142011420","eventTime":1479124118000,"eventCode":"SCN","activity":"Processed through Australia Post facility","location":"CHULLORA NSW","referenceTrackingNo":null}, {"trackingNo":"HBF0003142011420","eventTime":1479236805000,"eventCode":"SCN","activity":"With Australia Post for delivery today","location":"KINGSGROVE NSW","referenceTrackingNo":null}, {"trackingNo":"HBF0003142011420","eventTime":1479248135000,"eventCode":"DLD","activity":"Delivered","location":"CARINGBAH NSW","referenceTrackingNo":null} ] ] Here is my code: using (StreamReader reader = new StreamReader(webResponse.GetResponseStream())) { string text = reader.ReadToEnd(); List<string[]> trackingResponse = JsonConvert.DeserializeObject<List<string[]>>(text); // ...Do some stuff... } A: The type you should use is List<List<SomeObject>> var result = JsonConvert.DeserializeObject<List<List<SomeObject>>>(json); public class SomeObject { public string trackingNo { get; set; } public long eventTime { get; set; } public string eventCode { get; set; } public string activity { get; set; } public string location { get; set; } public string referenceTrackingNo { get; set; } }
doc_23535851
Global.asax, in Application_Start(): GlobalFilters.Filters.Add(new FilterA(), 1); GlobalFilters.Filters.Add(new FilterB(), 2); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); FilterA: public class FilterA : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { if (long thing that evaluates to true) { context.Result = new RedirectResult("~/Foo/Bar"); } } } FilterB: public class FilterB : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { if (...also true, but shouldn't run...) { context.Result = new RedirectResult("~/Foo/Baz"); } } } I must be missing something... I've tried running base.OnActionExecuting(context) both before and after I set Result, but it doesn't seem to matter. A: This results in a redirect loop probably because your logic in the filters is not excluding requests for "Foo/Bar" and "Foo/Baz". Basically setting the result on FilterA is preventing the other filter from running in that request and returning a redirect, but FilterB is getting executed on the next request after the redirect. The following works for me in a new MVC5 application: public class FilterA : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { if (!context.RouteData.GetRequiredString("controller").Equals("account", StringComparison.CurrentCultureIgnoreCase) //long condition evaluating to true //logic controlling these filters dont apply to Foo/Bar and Foo/Baz && (!context.RouteData.GetRequiredString("controller").Equals("Foo", StringComparison.CurrentCultureIgnoreCase) || (!context.RouteData.GetRequiredString("action").Equals("Bar", StringComparison.CurrentCultureIgnoreCase) && !context.RouteData.GetRequiredString("action").Equals("Baz", StringComparison.CurrentCultureIgnoreCase)) ) ) { context.Result = new RedirectResult("~/Foo/Bar"); } } } public class FilterB : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { if (true /*long condition evaluating to true*/ //logic controlling these filters dont apply to Foo/Bar and Foo/Baz && (!context.RouteData.GetRequiredString("controller").Equals("Foo", StringComparison.CurrentCultureIgnoreCase) || (!context.RouteData.GetRequiredString("action").Equals("Bar", StringComparison.CurrentCultureIgnoreCase) && !context.RouteData.GetRequiredString("action").Equals("Baz", StringComparison.CurrentCultureIgnoreCase)) ) ) { context.Result = new RedirectResult("~/Foo/Baz"); } } } I have added some logic (you may probably want to refactor it) to both filters that makes sure that the current controller is not the Foo controller, or in case the current controller is Foo then the actions may be different from Bar and Baz. This should prevent a loop where the filter FilterA redirects to ~/Foo/Bar, then the new request is intercepted by FilterB that redirects to ~/Foo/Baz which will be intercepted again by FilterA and so on. As an example, if you create a new MVC5 application with those filters, if you go to ~/, you are redirected to ~/Foo/Bar by FilterA. However if you go to ~/Account/Login, you are redirected to ~/Foo/Baz by FilterB. Hope it helps!
doc_23535852
I have a HEADER.php : <TABLE> <TR> <TD>Link bar (left)</TD> <TD> Then, here I put the contents of the page and include a FOOTER.php </TD> </TR> <TR> <TD>Footer Contents</TD> </TR> </TABLE> Ok, I should use newer DIV, but I am too affectionate to old table methods ;) The issue: everything is centered (as you can see)! I tried to put align-left everything with no success. The strange thing, is if I remove that contents (and put just "Hello World") everything is fine. So I think that the HTML/CSS (content) - copy and pasted from a Blogger post - is the source of the issue. But was wondering how a "corrupted" HTML/CSS (content) can alter previuos entities (Also 'Link bar' is centered!) The same header.php/footer.php for other pages works fine Thank you in advance A: "newer DIV", "old table methods"... using tables for your layout is not old, its prehistoric! Please learn how to use div's, you'll see soon enough that it works soooo much easier. But I also would like to provide an answer, add this to your stylesheet: table tr td { text-align: left; } A: Remove your tr{text-align:center;} line 222 AND line 296 of timer.html You have it twice on both line so remove them all. You really should put all your CSS on the same place, it would be easier for you to debug. A: Just define this mentioned below css to achieve your desired result..... CSS table tr td { text-align:left; } see the attached demo :-
doc_23535853
public abstract class XTimeViewModel : DevExpress.Xpf.Mvvm.ViewModelBase { public bool PropertiesChanged { get; set; } [NotifyPropertyChangedInvocator] protected virtual void _onPropertyChanged(/*[CallerMemberName]*/ string propertyName = null) { PropertiesChanged = true; RaisePropertyChanged(propertyName); } } It is contained in an assembly called Common. When I try and add a DirectoryCatalog for a folder containing Common and other assemblies, and dependencies such as DevExpress.Xpf.Mvvm.v13.2: var catalog = new DirectoryCatalog(unitPath, "*.dll"); AggregateCatalog.Catalogs.Add(catalog); I get a ReflectionTypeLoadException, with a TypeLoadException stating: "Could not load type 'Startup.ViewModels.ViewModel' from assembly 'G4S.XTime.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'." I can't see why MEF can't load this type. When I try sample code: var asm = Assembly.LoadFrom(@"C:\Development\XTime\Startup\Units\G4S.XTime.Common.dll"); var vm = asm.GetType("G4S.XTime.Common.XTimeViewModel"); Then vm contains the correct type, i.e. G4S.XTime.Common.XTimeViewModel. Just a hunch, but none of my loaded modules are having Initialize called, and I think this error is close to the root cause of that. If I reference the modules, and use AssemblyCatalog to load them, there is no problem at all and all works as it should. What could moving the assembly out to be loaded at runtime change to stop things working? BTW, Common isn't a module itself , but just a dependency of several modules. A: Most likely, your dll's are not in the same place as your startup exe. They are if they are directly referenced by the exe (by default, referenced dll's are copied to the output dir). Since you mentioned the Initialize() methods not being called, maybe you are using Prism? if so, break into each step of the bootstrapper to see that the catalog is correct (i.e. all the types you think should be in there actually are in there). You didn't show that the ViewModel under question is marked as [Export], too, so make sure that's there and put a break point in its ctor to make sure it is actually being instantiated after the catalog creation is complete (i.e. when you are creating the view the VM is attached to). Try giving us the full exception trace to see what's really going on...sometimes the root is buried in those type load exceptions.
doc_23535854
I have a spider that visits a page, and downloads a file. Ultimately I want to write the name of the file, along with other useful information to a db table. --> Right now, I am struggling to get the file name: from items.py: import scrapy from scrapy.item import Item, Field class NdrItem(scrapy.Item): district = Field() file_urls = Field() file_name = Field() files = Field() from spider: import scrapy from ndr.items import NdrItem class CentralBedfordshireSpider(scrapy.Spider): name = 'central_bedfordshire2' allowed_domains = ['centralbedfordshire.gov.uk'] start_urls = ['http://centralbedfordshire.gov.uk/business/rates/paying/published.aspx'] def parse(self, response): relative_url = response.xpath("//article[@class='page-content__article']/div[@class='editor']/p[3]/a/@href").extract_first() download_url = response.urljoin(relative_url) item = NdrItem() item['district'] = 'central bedfordshire' item['file_urls'] = [download_url] print('------------------ Print the info I want to eventually go in db --------------------------') print(item['district']) print(item['files']) return item Edit: The file is downloading ok and has the sha1 filename when downloaded. I would like to have the sha1 filename. Edit: I get the following error when I run this spider: 2017-08-22 10:39:42 [scrapy.core.scraper] ERROR: Spider error processing <GET http://centralbedfordshire.gov.uk/business/rates/paying/published.aspx> (referer: None) Traceback (most recent call last): File "c:\python27\lib\site-packages\twisted\internet\defer.py", line 653, in _runCallbacks current.result = callback(current.result, *args, **kw) File "C:\Users\MichaelAnderson\GDrive\Python\ndr\ndr\spiders\central_bedfordshire2.py", line 19, in parse print(item['files']) File "c:\python27\lib\site-packages\scrapy\item.py", line 59, in __getitem__ return self._values[key] KeyError: 'files' Typically if people have a number of spiders all saving data to the same folder, how do people reference downloaded files and keep them linked to the source URL? Many thanks for any help A: You are looking to get it from the URL itself. If you use Python 3 below will work from urllib.parse import urlparse url = "http://centralbedfordshire.gov.uk/Images/business-rates-live-account-list-2017-07_tcm3-9033.csv" print(urlparse(url).path.split("/")[-1]) 'business-rates-live-account-list-2017-07_tcm3-9033.csv' Edit-1 If you need to get SHA1 hash import hashlib sha1 = hashlib.sha1() sha1.update(url.encode("utf-8")) sha1_hash = sha1.hexdigest() A: For your specific requirement, I would probably use Scrapy Files Pipeline together with custom pipeline ordered after the Files Pipeline. From the Files Pipeline documentation: When the files are downloaded, another field (files) will be populated with the results. This field will contain a list of dicts with information about the downloaded files, such as the downloaded path, the original scraped url (taken from the file_urls field) , and the file checksum. The files in the list of the files field will retain the same order of the original file_urls field. If some file failed downloading, an error will be logged and the file won’t be present in the files field. In your spider, populate the field file_urls with file locations you wish to download. Then, after processing the item with standard Files Pipeline, it will contain field files with SHA1 filenames for each of the location in file_urls, in the same order. Then write another custom pipeline, which will process items after Files Pipeline and will use this information.
doc_23535855
How do i get hold of today's 00:00 (open time) high and low as x and y so that i can be able to create a vertical line between them? I am trying to create a range for each trading day as pictured, any tips on how to achieve this? A: This was the closest thing I could do. It is not possible to do it in the only line of the sail without the line being infinite as in your example, so to make it from a certain height you must make 2 plots and fill them. You can also modify the position of the line if it does not match your time zone. //@version=5 indicator("Keiden vertical line", overlay=true) tHour = input.int(0, maxval=23, minval=0, title="Open Hour", group="Enter the open hour of the day") plotTime = hour == tHour and minute == 0 ? true : false hValuePlot = ta.valuewhen(plotTime, high, 0) lValuePlot = ta.valuewhen(plotTime, low, 0) H = plot(hValuePlot, color=color.new(color.blue, plotTime[1]?0:100)) L = plot(lValuePlot, color=color.new(color.blue, plotTime[1]?0:100)) fill(H, L, color=color.new(color.blue, plotTime[1]?0:100))
doc_23535856
A: Which camera and drone are you using? I don't believe there is a way to know and change the H.264 profile - if I hear something different I'll update this post. But in general the video and storage settings can be played with here: method loadSettingsFromProfile If this doesn't help, then email dev@dji.com describing in detail what you want to do (include which SDK you would like to use) and what DJI products you're using - we can look into making this a feature request.
doc_23535857
private static void stillAttemptToParse() { var client = new WebClient(); var response = client.DownloadString(new Uri("http://localhost:52644/api/status")); var j = JsonConvert.DeserializeObject<Status>(response); //Status is a group of classes to represent the data from jsonToC# Console.WriteLine(j.OverallSuccess); foreach (var item in j.SettingItems) { Console.WriteLine("id: {0}, : {1} : {2}" , item.SettingName, item.Source , item.SettingValue); } } So the real question would be if i know the item.SettingsName is 'basicURL' how can I get the item.SettingsValue( which would be http://www.someBasicUrl.com ) for that item 'basicUrl' without running a loop ? A: Take a look at Newtonsoft's json DeserializeObject(). Their Json.NET library is pretty good. http://www.newtonsoft.com/json/help/html/deserializeobject.htm Hope this helps!
doc_23535858
<textarea rows="4" name="issue" style="width:90%;"></textarea> The form is submitted as a POST to another php page. I capture it as: $ins_issue = nl2br($_POST['issue']); I then write it to MySQL with an insert statement. (which is not working for all special characters. Commas for example break the query) $ins_query = ("INSERT INTO data1 ( p_key_project, category, issue, proposed_resolution, action_items, owner, status, archived ) VALUES ( '$passed_key', '$cat_1', '$ins_issue', '$ins_resolution', '$ins_action', '$ins_owner', '$ins_status', 'n' )"); What I'm trying to do is capture ALL special characters that are entered (spaces, line breaks, 's, colons, semi colons, etc ....) and write them to MySQL (I choose TEXT as the datatype in MySQL when I setup the table.) When I then do a select from MySQL, and pre-populate the text area on the page, I want ALL characters to show up. Line breaks to be there, etc .... What is the best way to accomplish this so that Anything that someone might paste into the textarea remains 100% intact and exact?
doc_23535859
Dados -> HTTP/1.1 400 Bad Request Date: Thu, 16 Apr 2009 15:25:41 GMT Server: Apache/2.2.10 (Win32) PHP/5.2.8 Content-Length: 226 Connection: close Content-Type: text/html; charset=iso-8859-1 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>400 Bad Request</title> </head><body> <h1>Bad Request</h1> <p>Your browser sent a request that this server could not understand.<br /> </p> </body></html> ☺ Here is the code I have: #define WIN32_LEAN_AND_MEAN #include <stdio.h> #include <stdlib.h> #include <winsock2.h> int main() { WSADATA WsaDat; if(WSAStartup(MAKEWORD(2,0),&WsaDat)!=0) { printf("Winsock error - Winsock initialization failed\r\n"); WSACleanup(); system("PAUSE"); return 0; } SOCKET Socket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(Socket==INVALID_SOCKET) { printf("Winsock error - Socket creation Failed!\r\n"); WSACleanup(); system("PAUSE"); return 0; } struct hostent *host; if((host=gethostbyname("localhost"))==NULL) { printf("Failed to resolve hostname.\r\n"); WSACleanup(); return 0; } printf("Resolveu o hostname\r\n"); SOCKADDR_IN SockAddr; SockAddr.sin_port= htons(80); SockAddr.sin_family= AF_INET; SockAddr.sin_addr.s_addr= *((unsigned long*)host->h_addr); if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr))!=0) { printf("Failed to establish connection with server\r\n"); WSACleanup(); system("PAUSE"); return 0; } char get[] = { "GET / HTTP/1.1\n" "From: bla@ble\n" "User-Agent: HTTPTool/1.0\n" "\n" }; send(Socket,get, strlen(get),0); printf("Ligou-se\r\n"); char buffer[1000]; int nDataLength = recv(Socket,buffer,1000,0); printf("Dados -> %s",buffer); shutdown(socket,SD_SEND); closesocket(socket); WSACleanup(); return 0; } Is there something missing? I am following a tutorial and that's basically the code they have there. Thanks A: HTTP 1.1 requires a Host: localhost header - either add this or use HTTP 1.0 Also, headers are separated by \r\n, not just \n. A: As RoBorg said your get string should be: char get[] = { "GET / HTTP/1.1\r\n" "Host: localhost\r\n" "From: bla@ble\r\n" "User-Agent: HTTPTool/1.0\r\n" "\r\n" }; If you are connecting to other sites besides localhost the 'host' field will have to be updated (usually hostname, IP address, or www works). A: It might be easier to try just using HTTP/1.0, which you don't need to specify the extra values: char get[] = { "GET / HTTP/1.0\r\n" }; Should work everywhere... A: You might also want to try using WinInet for your client-side Http needs instead of just sockets. Lots of people connect to web services through proxies -- that is, their own computer can't access the web, but it can get to a nearby computer (the proxy) that will forward the request on. You socket code doesn't handle proxies, but the WinInet API will do it for you automatically. [As an old-fashioned networking person, I loath these devices -- they've essentially badly implemented routers] Similarly, you might want to switch your server to https: some day; you'll have a heck of a time updating your socket code to handle this, but again, WinInet does it for you. [Note: I work at Microsoft]
doc_23535860
I have tried using a while statement for len(list)<8, and an if/else statement for the same. Both are asking for the additional input, but neither are printing the list at the end. I tried a nested loop with while len(list)<8 and inside is an if/else loop, but that returned the same errors as the original while statement. >>>def main(): ... userinput= input("Enter a list of at least eight words separated by a comma: ") ... list= userinput.split(",") ... while len(list)<7: ... print("Please enter more words") ... more_input= input() ... more_input.split(",") ... list.append(more_input) ... print(list) OR >>> def main(): ... userinput= input("Enter a list of at least eight words separated by a comma: ") ... list= userinput.split(",") ... if len(list)<7: ... print("Please enter more words") ... more_input= input() ... more_input.split(",") ... list.append(more_input) ... else: ... print(list) Errors with while loop: It just keeps asking for more input even when the list has the minimum required input >>> main() Enter a list of at least eight words separated by a comma: This, is, a, list Please enter more words More, words Please enter more words Three, more, words Please enter more words Errors with if/else loop: It only checks once. If the length is good, it prints the list. If the length is not good, it asks for more input and then stops. It neither checks the length again nor prints the list. A: Try this if you want to merge the split sub-lists in the main list : def main(): list_= [] print("Enter a list of at least eight words separated by a comma: ") while len(list_)<7: print("Please enter more words") userinput = input() temp = userinput.split(",") list_ += temp print(list_) main() Output : Enter a list of at least eight words separated by a comma: Please enter more words This, is, a, list Please enter more words more, words Please enter more words three, more, words ['This', ' is', ' a', ' list', 'more', ' words', 'three', ' more', ' words'] Note : Avoid assigning variable name as list as it's builtin keyword in python. A: Your code seems ok but the problem is that you are splitting the input coming from user but this split input does not have a variable. I mean, you are still adding the non split input to the list. I edited the code which you can see below. def main(): userinput= input("Enter a list of at least eight words separated by a comma: ") input_list = userinput.split(",") while len(input_list)<7: print("Please enter more words") more_input= input() splitted_more_input = more_input.split(",") # problem fixed here for i in splitted_more_input: # split creates another list input_list.append(i) # add inputs individual print(input_list) A: Since you need to repeatedly execute a function till a certain condition is met, you could take the help of recursive functions as follows def main(): userinput= input("Enter a list of at least eight words separated by a comma: ") words = userinput.split(",") if len(words) == 8: print (words) else: A = reenter_words(words) print (A) def reenter_words(words): if len(words) == 8: return words else: IN = input("More words are needed:") new_words = words + IN.split(",") return reenter_words(new_words) Here I am recursively calling the reenter_words function till we get eight words from the user. SAMPLE OUTPUT Enter a list of at least eight words separated by a comma: qq,ww,ee,rr,tt More words are needed:gg,hh More words are needed:kk ['qq', 'ww', 'ee', 'rr', 'tt', 'gg', 'hh', 'kk']
doc_23535861
What is the proper way to check that whether a file is exist or not? A: BOOL isDirectory = NO; if ( [[NSFileManager defaultManager] fileExistsAtPath:path isDirectory: &isDirectory ]) { // file already exists } else { // file does not yet exist } A: To put it in more detail: NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; if ([[NSFileManager defaultManager] fileExistsAtPath:documentsDirectory]){ //Do something... } You can append the actual file name to "documentsDirectory" like this: [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg", spidermanpic]]. The isDirectory option in the answer above is used to check if the path is a directory or a file. Please keep in mind that it is a pointer. It wont work without the "&".
doc_23535862
This would be such that if a user clicks on the form, it remains below any overlapping windows. I would use this, along with having no border, to mimic an item being on the desktop, with other apps always above.
doc_23535863
In my calendar component I am setting state for two properties - startDate and endDate but endDate doesn't get set on the state. If I add breakpoints I can see it hits this and tries to set it with a value. If I add the callback function for state being updated, this never gets run, so something weird is happening that I can't resolve. Why would state not update? There are no errors in the console. Example code from my calendar component: onDatesChange = ({ startDate, endDate }) => { this.setState({ startDate, endDate }); if (startDate && endDate) { this.props.onDatesPicked(startDate.format('YYYY-MM-DD'), endDate.format('YYYY-MM-DD')); } }; onClose = () => { const { startDate, endDate } = this.state; if (!startDate || !endDate) { this.props.onCancel(); } }; render() { const { startDate, endDate, focusedInput } = this.state; return ( <div className={css.component}> <DateRangePicker displayFormat="DD MMM YYYY" isOutsideRange={this.isOutsideRange} startDate={startDate} startDateId={START_DATE} startDatePlaceholderText="Start date" endDate={endDate} endDateId={END_DATE} endDatePlaceholderText="End date" onDatesChange={this.onDatesChange} focusedInput={focusedInput} onFocusChange={this.onFocusChange} firstDayOfWeek={1} hideKeyboardShortcutsPanel minimumNights={0} withPortal onClose={this.onClose} /> </div> ); } In the onClose function never finds a value for endDate even though setState has already been called in onDatesChange and has passed in a value. There are no issues with startDate. If I comment out setting startDate then endDate does get set fine. I am so confused...
doc_23535864
name class name class month john 2nd john 2nd JAN bunny 3rd john 2nd FEB sunny 4th bunny 3rd FEB student who submits fees for a particular month gets inserted into the second table mentioning the month in the month column in the second table I want the list of students who have not submitted the fees for the month of JAN please help me. thanks in advance. A: You can use NOT EXISTS Query select * from student_mas t where not exists ( select * from receipt_mas where name = t.name and class = t.class and [month] = 'JAN' ); SQL Fiddle demo A: Ullas answer would work perfectly but you can try like the below approach. DECLARE @student_mas TABLE ( NAME VARCHAR(50) ,class VARCHAR(10) ); insert into @student_mas values ('john', '2nd'), ('bunny', '3rd'), ('sunny', '4th'); DECLARE @receipt_mas TABLE ( NAME VARCHAR(50) ,class VARCHAR(10) ,[month] VARCHAR(3) ); insert into @receipt_mas values ('john', '2nd', 'JAN'), ('john', '2nd', 'FEB'), ('bunny', '3rd', 'FEB'); SELECT sm.* FROM @student_mas sm LEFT JOIN @receipt_mas rm ON sm.NAME = rm.NAME AND sm.class = rm.class AND rm.month = 'JAN' WHERE RM.class IS NULL A: with student_mas as ( SELECT 'JOHN' NAME,'2ND' CLASS FROM DUAL union all SELECT 'BUNNY' NAME,'3RD' CLASS FROM DUAL union all SELECT 'SUNNY' NAME,'4TH' CLASS FROM DUAL ) select * from student_mas A where not exists ( with receipt_mas as ( SELECT 'JOHN' NAME,'2ND' CLASS,'JAN' MONTH FROM DUAL union all SELECT 'BUNNY' NAME,'3RD' CLASS,'FEB' MONTH FROM DUAL union all SELECT 'SUNNY' NAME,'4TH' CLASS,'FEB' MONTH FROM DUAL ) select * from receipt_mas B where A.NAME=B.NAME and A.CLASS=B.CLASS and B.MONTH='JAN' ) /
doc_23535865
Our npm test command "test:ci": "ng test --no-watch --no-progress --browsers=ChromeHeadlessNoSandbox", Our karma.config Notice we have a singleRun:true as that seemed to be the important one. // Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage'), require('@angular-devkit/build-angular/plugins/karma') ], client: { jasmine: { // you can add configuration options for Jasmine here // the possible options are listed at https://jasmine.github.io/api/edge/Configuration.html // for example, you can disable the random execution with `random: false` // or set a specific seed with `seed: 4321` }, clearContext: false // leave Jasmine Spec Runner output visible in browser }, jasmineHtmlReporter: { suppressAll: true // removes the duplicated traces }, coverageReporter: { dir: require('path').join(__dirname, './coverage/member-web'), subdir: '.', reporters: [ { type: 'html' }, { type: 'text-summary' } ] }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, // browsers: ['Chrome'], browsers: ["ChromeHeadlessNoSandbox"], customLaunchers: { ChromeHeadlessNoSandbox: { base: "ChromeHeadless", flags: [ '--headless', '--disable-gpu', "--no-sandbox", "--user-data-dir=/tmp/chrome-test-profile", "--disable-web-security", "--remote-debugging-address=0.0.0.0", "--remote-debugging-port=9222", ], debug: true, }, }, singleRun: true, restartOnFileChange: true }); }; A: Does the command line not complain about unknown command of --no-watch? Change the command to: "test:ci": "ng test --watch=false --browsers=ChromeHeadlessNoSandbox && echo 'hello'", --no-progress does not exist either. Find all flags here: https://angular.io/cli/test. A: I figured it out. It was something related to the Docker Container we were using. I tried on another image making sure to include chromium and it fixed it. The dockerfile that worked for me is below. FROM node:current-alpine3.12 RUN apk add chromium WORKDIR /usr/src/app ENV CHROME_BIN=/usr/bin/chromium-browser
doc_23535866
static int load = 100; static int greet; public void loadDeduct(int cLoad, int c){ int balance; balance = cLoad - 7; System.out.println("Your balance: " + balance); } public void loadDeduct(int tLoad){ int balance; balance = tLoad - 1; System.out.println("Your balance is: " + balance); } public static void main (String [] args){ int choice; Scanner scan = new Scanner(System.in); System.out.println("I'm a cellphone, what do you want to do?"); System.out.println("Press 1 to send SMS / Press 2 to Call"); choice = scan.nextInt(); CellphoneLoad N95 = new CellphoneLoad(); if (choice == 1){ N95.loadDeduct(load); }else if (choice == 2){ N95.loadDeduct(load, greet); }else{ System.out.println("Invalid Option!!!"); } How do I implement the exception handling with this program? I'm not quite sure how to use the catch block as we weren't taught yet about the whole exceptions thing. It was just an exercise we were asked to do. I want to replace the if else statements with a try-catch blocks... is that possible? A: One important principle to consider with exceptions in Java is that there are two types: 1. Runtime 2. Typed/explicit (for lack of a better word) Runtime exceptions should be thrown when there is a programming error and generally they should not be caught unless you are catching at the top level to report an error. Typed/Explicit exceptions are decorated on method calls and should be there so the caller can take some action on them. In the case of the code above, there isn't really a place that feels like it should use exception handling. And as Patrick pointed out, you don't generally want to use exceptions for flow control. A: It is not ideal to use Exceptions for flow control. From your code it is not clear what Exceptions might be thrown. Maybe you can elaborate a bit more. A: The only part of your code that might possibly throw an exception is the call to: scan.nextInt(); According to the JavaDocs, this can throw the following possible exceptions: * *InputMismatchException (if the next token does not match the Integer regular expression, or is out of range) *NoSuchElementException (if input is exhausted) *IllegalStateException (if this scanner is closed) So if you wanted your code to account for the possibilities of these exceptions being thrown, you should re-write it like so: try { choice = scan.nextInt(); } catch (InputMismatchException e) { System.out.println(e.getMessage()); } catch (NoSuchElementException e) { System.out.println(e.getMessage()); } catch (IllegalStateException e) { System.out.println(e.getMessage()); } Generally, you want your "catch" blocks to start out specific or very likely to happen to less likely / more general in nature. You can additionally "throw" the exceptions so that whatever method the exception occurs in doesn't handle it-- the method which called that exception-causing method would have to handle it (or throw it again, etc, until it gets to the Java runtime). In the event it's the "if" statement you wish to replace, I'd recommend the "switch" statement: switch (choice) { case 1: N95.loadDeduct(load); break; case 2: N95.loadDeduct(load, greet); break; default: System.out.println("Invalid Option!!!"); } A: The Scanner.nextInt() method can throw a few exceptions. The linked page of the API Specifications lists out the three exceptions which can be thrown. For example, if a non-integer value is entered, such as "one" instead of 1, an InputMismatchException can be thrown. In general, a try-catch is used to catch exceptions, as illustrated in the following code: try { Integer.parseInt("one"); // Statement that can cause an exception. } catch (NumberFormatException e) // Specify which exception to catch. { // Code to handle the NumberFormatException. } More information about exceptions can be found in Lessons: Exceptions of The Java Tutorials. In particular, the Catching and Handling Exceptions section may be useful. A: Adding exceptions in this piece of code does not add much value. What I can think of is something like this: public static void main (String [] args){ ..... try{ handleUserChoice(choice);//new method } catch(InvalidChoiceException e){ System.out.println("Invalid Option!!!"); } } A: It's really pretty simple. First identify where you want an exceptioon. There can be exceptinos thrown by library code or you can throw your own. Then use a try .. catch to handle it. Here's a simple "hello, world" ish example: public class TryTry { public void doIt() throws Exception { System.err.println("In the doIt method."); throw new Exception("Hello there!"); } public static void main(String[] argv){ TryTry t = new TryTry(); // here we'll catch it. try { System.err.println("About to call doIt()."); t.doIt(); } catch (Exception e) { // e now has your exception object System.err.println("In the exception handler."); System.err.println("Exception says: "+ e); } } } The effect of throw is to construct that exception object and send it up the stack until it's caught. To catch it, you surround the code that might throw it with tr { ... }, and handle the exception with catch. Here's the results: javac TryTry.java && java TryTry About to call doIt(). In the doIt method. In the exception handler. Exception says: java.lang.Exception: Hello there! A: I don't see any reason to use exceptions instead of the if-else block. you could try using a switch statement, it'd look better. you should use exceptions to handle errors that might occur inside the methods loadDeduct. then you would surround the lines calling N95.loadDeduct with a try-catch block, to write what would happen if loadDeduct went wrong.
doc_23535867
<![CDATA[<a href="http://example.com/20.0.0.1/13902/cf085cef63511989576657751aad3cda.jpg" width="3543" height="2362" />Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. ]]> More precisely this: <![CDATA[<a href="http://example.com/20.0.0.1/13902/cf085cef63511989576657751aad3cda.jpg" width="3543" height="2362" /> and this: ]]> Please note that the first part is not always the same (its from an XML-feed). A: Since you want to extract the text between CDATA tags, I suggest you to use simple Regex to do the job. function removeCDATA(str) { var pattern = new RegExp(/\<!\[CDATA\[.*?\/>(.*?)\]\]\>/); var res = pattern.exec(str)[1]; return res; } alert(removeCDATA('<![CDATA[<a href="http://example.com/20.0.0.1/13902/cf085cef63511989576657751aad3cda.jpg" width="3543" height="2362" />Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. ]]>')) jsfiddle : link
doc_23535868
/kochR { 2 copy ge {dup 0 rlineto} { 3 div 2 copy kochR 60 rotate 2 copy kochR -120 rotate 2 copy kochR 60 rotate 2 copy kochR } ifelse pop pop } def 0 0 moveto 27 81 kochR 0 27 moveto 9 81 kochR 0 54 moveto 3 81 kochR 0 81 moveto 1 81 kochR stroke My questions on above program are: * *What does 2 copy ge { dup 0 rlineto } mean here? *How does ifelse work here and what is the condition? *What does 3 div do here? *What does the 2 copy KochR statement perform here? A: You seem to be having some problems with quite basic PostScript concepts and operations, do you have a copy of the PostScript Language Reference Manual ? * *copy copies an entry on the operand stack, the preceding argument tells the interpreter how many operands on the stack to copy. ge tests for greater than or equal and that is then followed by an executable array. *ifelse works in the way you would expect, if the condition is true then the first executable array is executed, else the second executable array is executed. *3 div divides the operand on the stack by 3 and places the result on the operand stack. *2 copy does the same as in point 1, 'KochR' is a named object, in this case it is an executable array. It must have been previously defined or an 'undefined'' error will occur. A: What does 2 copy ge { dup 0 rlineto } mean here? As the THEN clause of an if or ifelse operator, it means "if (stack(top-1) > stack(top)) draw_horizontal_line((current_x, current_y) -> (current_x + stack(top), current_y). The procedure-body { dup 0 rlineto } is the closure of the recursion: the part the decides when to stop and what to do instead of recursing. rlineto draws a relative line. Relative to the currentpoint, that is. The currentpoint is whereever the last path-construction operator (like moveto, lineto, but not rotate, and not stroke) left it. How does ifelse work here and what is the condition? ifelse always works the same way: booleantype procedure-body procedure-body ifelse: execute the first procedure body if the boolean is true, otherwise execute the second. The condition is the boolean-valued result of the gt operator applied to 2 numbers on the stack. Since gt consumes its arguments, prepending 2 copy means the data is not lost when gt does this. What does 3 div do here? Since the second argument (top-of-stack) controls the overall size of the figure, it also controls the "size" of the partial figure represented by the combined drawing commands of all child calls. 3 div means that at each recursion level, the "size" of the figure is smaller than the "size" of its parent, 1/3 smaller. At the leaf calls, where the condition a >= b holds, b is used as the length of the individual line-segments that compose the image. This means that a is not the line length per se, but a threshold value. As soon as b, in its descent to b/3, b/9, b/27, b/81, meets or crosses the threshold a, then its time to turn-off the cloning machine and have everybody pick up their pencils. What does the 2 copy KochR statement perform here? This line performs the recursive call to the kochR procedure, using the same threshold and a reduced size from two arguments that were passed to the current invocation. Using 2 copy means the two values persist on the stack until the pop pop further down. Here's a rough translation to C, assuming an available graphics library that implements the Adobe Image Model (also called Stencil-Mask, or Path-Paint model). The parameters appear to be the size of the line segments and the overall size of the figure, respectively. So the maximum recursion-level is indirectly controlled by the equation a >= b * (1/3)^R. void kochR(double a, double b) { if (a >= b) { // line from currentpoint to currentpoint+(b,0) // ie. line of length b along current x-axis rlineto(b, 0); } else { b /= 3; kochR(a, b); // recurse with reduced length rotate(60); // rotate x-axis CCW by 60 degrees kochR(a, b); rotate(-120); // rotate x-axis CW by 120 degrees kochR(a, b); rotate(60); kochR(a, b); } } int main(void) { moveto(0,0); kochR(27, 81); moveto(0, 27); kochR(9, 81); moveto(0, 54); kochR(3, 81); moveto(0, 81); kochR(1, 81); stroke(); } So you should be able to see from this that all the 2 copy stuff is a means postscript has to "keep alive" 2 unnamed variables. Each line corresponds to a procedure call which consumes 2 variables from the stack. You should be able to see that the final pop pop would be unnecessary if you also omitted the final 2 copy from the last "procedure call". From the perspective of postscript programming this is all quite basic stuff. But the way the recursion is bounded is quite sophisticated. By the way, if you like these kinds of fractals (I do), you absolutely must see http://en.wikipedia.org/wiki/L-system . It's amazing. One popular C library that implements the Adobe Image Model is Cairo Graphics, but I'll leave the task of creating a working program as an exercise for the reader. :) A: The 2 copy ge copies KochR's 2 arguments (I am assuming it is a coordinate pair) and compares its components, getting a truth value. The ifelse then decides, based on that truth value, whether to do { dup 0 rlineto } or the statements in the other block. 3 div divides the y-value of the coord pair in three, making it that point that much closer to the origin along that axis. 2 copy KochR creates a copy of the coordinate pair (which have either had y cut in thirds, or its location rotated), which are then used recursively to perform the same thing on them. My best estimate of what the function does is that it draws an atenuating zig-zag from the current point in the direction of the point passed to KochR, leaving the list of pointson the operand stack. The program appends several such zig-zags to the current path, each in is own subpath, and then strokes them all, leaving the entire list of points on the stack (a possible problem).
doc_23535869
Note : * *there will be multiple expressions hence the -e option *There may be multiple lines before the next * I've tried sed such as sed -i.bak -e '/*FOO/,/*/d' -e '/*BAR/,/*/d $FILE but this deletes the *KEEP line . **START *FOO This wants to be deleted *KEEP *BAR this also wants to be deleted *KEEP **END should become **START *KEEP *KEEP **END Thanks in advance for looking at this question A: It is easier to do this using awk: awk '/^*/{d = 0} /^*(FOO|BAR)/{d = 1} !d' file *START *KEEP *KEEP **END If you're using gnu awk then use -i inplace to save changes inline: awk -i inplace '/^*/{d = 0} /\*(FOO|BAR)/{d = 1} !d' file If not using gnu awk then use: awk '/^*/{d = 0} /^*(FOO|BAR)/{d = 1} !d' file > $$.tmp && mv file $$.tmp A: This might work for you (GNU sed): sed '/^*/h;G;/^*\(FOO\|BAR\)/M!P;d' file Store each key as it presents itself, in the hold space and append it to the current line. Print the first of the two lines in the pattern space if either does not contain a line beginning *FOO or *BAR.
doc_23535870
function template($val) { $Qry11=Database::Read("SELECT subcategory.*,C_Name,description FROM subcategory JOIN category ON subcategory.C_id=category.C_id JOIN product_description ON subcategory.S_id = product_description.S_id WHERE S_Name LIKE '%$val%' OR C_Name LIKE '%$val%' group by subcategory.S_id"); $List11 = Array(); $thisObjectName11 = get_class($this); while($arr = Database::Reader($Qry11)) { $data = new $thisObjectName11(); $data->temp_Id = $arr[S_id]; $data->C_Name = $arr[description]; $data->Nm = $arr[C_Name]; $data->S_Name = $arr[S_Name]; $List11[] = $data; } return $List11; } A: Use a variable in your query. $var = '"this is text"'; $var = mysql_real_escape_string($var); A: If i got that right use backslash to escape quotes: WHERE S_Name LIKE '%\"$val\"%' A: If your condition is in single quoted like this... WHERE S_Name LIKE '%$val%' then if you want to search single quote (') like in $val. $val = "some'some"; then replace single time single quote to double time (' to '') and search that will work proper. WHERE S_Name LIKE '%some''some%' otherwise in all search you can directly search value like... WHERE S_Name LIKE '%some"some%' So in this you don't required any slashes in php... A: You can use json with some variable like $var = json_encode("this is text"); and pass this variable to your query.
doc_23535871
At the moment, I do not understand how to generate the link itself correctly. Out from the box on the Sign-In page, links for Forgotten Password and Sign-Up are generated using the getRedirectLink function, but I can’t generate a link for Sign-in using it. As an alternative, it is suggested here to use history.back(), but unfortunately this is not covered all cases. A: The getRedirectLink cannot be used to generate a link to the Sign-in user flow. You can it as a hard link though. A: If we hard code the link (sign-in flow link) that won't work properly. A workaround is, place a link that points to your application itself. Eg: Say "https://something.com", is your application URL and it is a page requires authentication. When you place link to this URL, MSAL will redirect automatically to sign in page.
doc_23535872
I've been programming for a couple of years but am new to iOS app dev and am not sure how to go about this. Cheers for any help!
doc_23535873
pandas.parser.CParserError: Error tokenizing data. C error: Expected 2 fields in line 3, saw 12 This is my code: df = pd.read_csv('ZCS006A_16_23AUG_ALL_20220804020843.csv', delimiter = ',') df.head(10) Should I modify my code or modify the csv file? This is part of the .cvs file: AIRLINE_CODE,FLIGHT_NO,AIRCRAFT_TYPE_CODE,DEP_PORT_CODE,ARR_PORT_CODE,DEP_DATE,ARR_DATE,STD,STA,BLOCK_TIME,LEG,PART_NO,PART_NAME,PART_DESC,PART_SECTOR_USAGE_CODE,PART_SECTOR_USAGE_NAME,PART_CATEGORY_CODE,PAX_CLASS,EXCHANGE_TYPE_CODE,PART_QTY,PART_WEIGHT,IS_DEADHEAD LA,0800,789,AKL,SCL,16-AUG-22,16-AUG-22,1840,1340,660,2,10002993,MANTEQUILLA YC,10002993: MANTEQUILLA YC,D,Disposable,,Y,CY,143,35.75,0 LA,0800,789,AKL,SCL,16-AUG-22,16-AUG-22,1840,1340,660,2,10003049,BEBIDA BLANCA 1500CC YC,10003049: BEBIDA BLANCA 1500CC YC,D,Disposable,,Y,BX,4,6.5332,0 LA,0800,789,AKL,SCL,16-AUG-22,16-AUG-22,1840,1340,660,2,10003049,BEBIDA BLANCA 1500CC YC,10003049: BEBIDA BLANCA 1500CC YC,D,Disposable,,Y,EX,6,9.7998,0 LA,0800,789,AKL,SCL,16-AUG-22,16-AUG-22,1840,1340,660,2,10003153,COCA COLA 1500CC YC,10003153: COCA COLA 1500CC YC,D,Disposable,,Y,BX,4,6.4,0 LA,0800,789,AKL,SCL,16-AUG-22,16-AUG-22,1840,1340,660,2,10003153,COCA COLA 1500CC YC,10003153: COCA COLA 1500CC YC,D,Disposable,,Y,EX,8,12.8,0 A: In the pandas documentation, pd.read_csv says: error_bad_lines bool, optional, default None Lines with too many fields (e.g. a csv line with too many commas) will by default cause an exception to be raised, and no DataFrame will be returned. If False, then these “bad lines” will be dropped from the DataFrame that is returned. So, you may pass parameter error_bad_lines=False to pd.read_csv: df = pd.read_csv('ZCS006A_16_23AUG_ALL_20220804020843.csv', delimiter = ',', error_bad_lines=False)
doc_23535874
EDITED: NOW SOLVED BUT why app create always empty appointment? Routes.rb: ZOZ::Application.routes.draw do resources :refferals do collection do get 'new51' end member do get 'show' end end resources :appointments do collection do get 'search' #17 get 'search_result' #17 get 'to_confirm' #17 get 'search_not' #57 get 'search_result_not' #57 get 'add_or_edit_not' #57 get 'searchdate' get 'searchd' get 'move' get 'new51' post :create51 end member do put :confirm #17 put :update_not #57 get 'show51' end end resources :clinics do collection do get 'index51' end member do get 'show51s' end end resources :doctors do collection do get 'index51a' get 'index51' get 'search54' get 'search_result54' get 'show_harmonogram' end member do get 'show51s' get 'show51ss' end end resources :patients do collection do get 'select51' get 'index51' end member do get 'show51s' get 'show51ss' end end get "welcome/index2" get "welcome/index" get 'appointments/create' get 'appointments/move' => 'appointments#move' post 'appointments/move' => 'appointments#doctors_list' get 'appointments/move/:id' => 'appointments#doctor_appointments', as: :doctor_appointments get 'appointments/change_appointment/:id' => 'appointments#change_appointment', as: :change_appointment get 'appointments/change_doctor_and_appointment/:id' => 'appointments#change_doctor_and_appointment', as: :change_doctor_and_appointment get 'appointments/success' => 'appointments#success' # The priority is based upon order of creation: # first created -> highest priority. # Sample of regular route: # match 'products/:id' => 'catalog#view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # Sample resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Sample resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Sample resource route with more complex sub-resources # resources :products do # resources :comments # resources :sales do # get 'recent', :on => :collection # end # end # Sample resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end # You can have the root of your site routed with "root" # just remember to delete public/index.html. root :to => 'welcome#index' # See how all your routes lay out with "rake routes" # This is a legacy wild controller route that's not recommended for RESTful applications. # Note: This route will make all actions in every controller accessible via GET requests. # match ':controller(/:action(/:id))(.:format)' end _form51.html.erb: <%= form_for(@appointment) do |f| %> <% if @appointment.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@appointment.errors.count, "error") %> prohibited this appointment from being saved:</h2> <ul> <% @appointment.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= f.label :data_godzina_wizyty %><br /> <%= options = { start_year: 2.year.from_now.year, end_year: 2013, include_blank: true, default: nil } f.datetime_select :data_godzina_wizyty, options %> <!--<input type="text" data-behaviour='datepicker' :data_wizyty > --> </div> <div class="field"> <%= f.hidden_field :doctor_id, :value => Doctor.find(session[:current_doctor_id2]).id %> </div> <div class="field"> <%= f.hidden_field :patient_id, :value => Patient.find(session[:current_patient_id]).id %> </div> <div class="actions"> <%= submit_tag "Utworz wizyte" %> </div> <% end %> New51.html.erb: <div id="container"> <center> <h1>Nowa wizyta:</h1> <p>Sprawdz poprawnosc ponizszych danych a nastepnie uzupelnij formularz.</p> <h3>Dane lekarza:</h3> <p> <strong>Imię lekarza:</strong> <%= Doctor.find(session[:current_doctor_id2]).imie_lekarza %> </p> <p> <strong>Nazwisko lekarza:</strong> <%= Doctor.find(session[:current_doctor_id2]).nazwisko_lekarza %> </p> <p> <strong>Specjalizacja lekarza:</strong> <%= Doctor.find(session[:current_doctor_id2]).specjalizacja %> </p> <h3>Dane pacjenta:</h3> <p> <strong>Imie:</strong> <%= Patient.find(session[:current_patient_id]).imie %> </p> <p> <strong>Nazwisko:</strong> <%= Patient.find(session[:current_patient_id]).nazwisko %> </p> <p> <strong>Pesel:</strong> <%= Patient.find(session[:current_patient_id]).pesel %> </p> <%= render 'form51' %> <%= link_to 'Wybierz innego lekarza', index51_doctors_path %> </br> </center> </div> Appointments_Controller: class AppointmentsController < ApplicationController before_filter :load_appointment, only: [:show, :update, :edit, :destroy] before_filter :load_wizard, only: [:new, :edit, :create] def searchd end def move end def doctors_list @doctors = Doctor.where("imie_lekarza like ? or nazwisko_lekarza LIKE ? or specjalizacja LIKE ?", "%#{params[:search]}%", "%#{params[:search]}%", "%#{params[:search]}%") end def doctor_appointments @doctor = Doctor.find(params[:id]) @appointments = @doctor.appointments end def change_appointment @appointment = Appointment.find(params[:id]) end def change_doctor_and_appointment @doctors = Doctor.all @appointment = Appointment.find(params[:id]) end def success @notice = flash[:notice] end def searchdate d = params[:date] data = Date.new(d["(1i)"].to_i, d["(2i)"].to_i, d["(3i)"].to_i) @appointments = Appointment.scoped @appointments = @appointments.where(:data_godzina_wizyty => data.beginning_of_day..data.end_of_day) end def search_not end def search_result_not #pacjent @patients = Patient.scoped @patients = @patients.where(pesel: params[:pesel]) d = params[:date] if d["(1i)"] != "" and d["(2i)"]. != "" and d["(3i)"] != "" data = Date.new(d["(1i)"].to_i, d["(2i)"].to_i, d["(3i)"].to_i) @appointments = @patients.first.appointments.where(:data_godzina_wizyty => data.beginning_of_day..data.end_of_day) else @appointments = @patients.first.appointments end end def add_or_edit_not session['last_search_not'] = request.env["HTTP_REFERER"] @appointment = Appointment.find(params[:id]) @patient = Patient.find(@appointment.patient_id) if @appointment.doctor_id != nil @doctor = Doctor.find(@appointment.doctor_id) end if @appointment.refferal_id != nil @refferal = Refferal.find(@appointment.refferal_id) end end def update_not @appointment = Appointment.find(params[:id]) @appointment.notatka = params[:notatka] if @appointment.save redirect_to session[:last_search_not], notice: 'Notatka zostala zapisana.' else redirect_to :back, notice: 'Niestety wystapil blad. Prosze sprubowac pozniej' end end def search end def new51 @appointment = Appointment.new respond_to do |format| format.html # new.html.erb format.json { render json: @appointment } end end def create51 @appointment = Appointment.new(params[:patient]) respond_to do |format| if @appointment.save format.html { redirect_to @appointment, notice: 'Szczegoy wizyty pomyslnie zmodyfikowane!' } format.json { render json: @appointment, status: :created, location: @appointment } else format.html { render action: "new" } format.json { render json: @appointment.errors, status: :unprocessable_entity } end end end def search_result d = params[:date] data = Date.new(d["(1i)"].to_i, d["(2i)"].to_i, d["(3i)"].to_i) #szukanie pacjenta @patients = Patient.scoped @patients = @patients.where(pesel: params[:pesel]) if params[:imie] != "" @patients = @patients.where(imie: params[:imie]) end if params[:nazwisko] != "" @patients = @patients.where(nazwisko: params[:nazwisko]) end #szukanie doctora opcja = 0 @doctors = Doctor.scoped if params[:imie_lekarza] != "" @doctors = @doctors.where(imie_lekarza: params[:imie_lekarza]) opcja = 1 end if params[:nazwisko_lekarza] != "" @doctors = @doctors.where(nazwisko_lekarza: params[:nazwisko_lekarza]) opcja = 1 end #zlaczenie @patient_appo = @patients.first.appointments.where(:data_godzina_wizyty => data.beginning_of_day..data.end_of_day, potwierdzona: false) if opcja == 1 @doctors_appo = @doctors.first.appointments.where(:data_godzina_wizyty => data.beginning_of_day..data.end_of_day, potwierdzona: false) @appointments = @patient_appo & @doctors_appo else @appointments = @patient_appo end end def to_confirm session['last_search'] = request.env["HTTP_REFERER"] @appointment = Appointment.find(params[:id]) @patient = Patient.find(@appointment.patient_id) if @appointment.doctor_id != nil @doctor = Doctor.find(@appointment.doctor_id) end if @appointment.refferal_id != nil @refferal = Refferal.find(@appointment.refferal_id) end end def confirm @appointment = Appointment.find(params[:id]) @appointment.potwierdzona = true if @appointment.save #redirect_to :back, notice: 'Rejestracja zostala pomyslnie potwierdzona.' redirect_to session[:last_search], notice: 'Rejestracja zostala pomyslnie potwierdzona.' else redirect_to :back, notice: 'Niestety wystapil blad. Prosze sprubowac pozniej' end end def index @appointments = Appointment.all end def show end def new @appointment = @wizard.object @clinics = Clinic.all @doctors = Doctor.all end public def findDoctorViaClinic( clinic ) return( (Clinic.find( clinic )).doctors.uniq ) end helper_method :findDoctorViaClinic def findScheduleViaDoctor(d) s = Schedule.includes(:doctors_workplace).where(doctors_workplace_id: (DoctorsWorkplace.includes(:doctor).where(doctor_id: d)) ).where(taken: 0) return s end helper_method :findScheduleViaDoctor def edit end def create @appointment = @wizard.object if @wizard.save s = ( Schedule.find( @appointment.schedule.id ) ) s.taken = true s.save redirect_to @appointment, notice: "Appointment saved!" else render :new end end def update # if @wizard.save # redirect_to @appointment, notice: 'Appointment was successfully updated.' # else # render action: 'edit' # end @appointment = Appointment.find(params[:id]) @old_appointment = @appointment.dup respond_to do |format| if @appointment.update_attributes(params[:appointment]) DefaultMailer.move_appointment(@appointment, @old_appointment).deliver format.html { redirect_to appointments_success_path, notice: 'Pomyslnie zmieniono termin.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @appointment.errors, status: :unprocessable_entity } end end end def destroy @appointment.destroy redirect_to appointments_url end private def load_appointment @appointment = Appointment.find(params[:id]) end def load_wizard @wizard = ModelWizard.new(@appointment || Appointment, session, params) if self.action_name.in? %w[new edit] @wizard.start elsif self.action_name.in? %w[create update] @wizard.process end end end Logs: Started POST "/appointments/create51" for 127.0.0.1 at 2014-06-22 08:22:53 +0200 Processing by AppointmentsController#create51 as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"kMxnErrH13opSkUPbg9hRM0Sy5JVwDCAbGRDNP5BSfc=", "appointment"=>{"data_godzina_wizyty(1i)"=>"2015", "data_godzina_wizyty(2i)"=>"1", "data_godzina_wizyty(3i)"=>"17", "data_godzina_wizyty(4i)"=>"16", "data_godzina_wizyty(5i)"=>"15", "doctor_id"=>"1", "patient_id"=>"1"}, "commit"=>"Utworz wizyte"} [1m[35m (0.0ms)[0m begin transaction [1m[36mSQL (2.0ms)[0m [1mINSERT INTO "appointments" ("clinic_id", "created_at", "data_godzina_wizyty", "data_wizyty", "doctor_id", "godzina_wizyty", "notatka", "objawy_choroby", "patient_id", "potwierdzona", "refferal_id", "schedule_id", "updated_at", "wymaga_Potwierdzenia") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)[0m [["clinic_id", nil], ["created_at", Sun, 22 Jun 2014 06:22:53 UTC +00:00], ["data_godzina_wizyty", nil], ["data_wizyty", nil], ["doctor_id", nil], ["godzina_wizyty", nil], ["notatka", nil], ["objawy_choroby", nil], ["patient_id", nil], ["potwierdzona", nil], ["refferal_id", nil], ["schedule_id", nil], ["updated_at", Sun, 22 Jun 2014 06:22:53 UTC +00:00], ["wymaga_Potwierdzenia", nil]] [1m[35m (13.0ms)[0m commit transaction Redirected to http://localhost:3000/appointments/30 Completed 302 Found in 23.0ms (ActiveRecord: 15.0ms) Started GET "/appointments/new51" for 127.0.0.1 at 2014-06-22 08:22:42 +0200 Processing by AppointmentsController#new51 as HTML [1m[35mDoctor Load (1.0ms)[0m SELECT "doctors".* FROM "doctors" WHERE "doctors"."id" = ? LIMIT 1 [["id", 1]] [1m[36mCACHE (0.0ms)[0m [1mSELECT "doctors".* FROM "doctors" WHERE "doctors"."id" = ? LIMIT 1[0m [["id", 1]] [1m[35mCACHE (0.0ms)[0m SELECT "doctors".* FROM "doctors" WHERE "doctors"."id" = ? LIMIT 1 [["id", 1]] [1m[36mPatient Load (0.0ms)[0m [1mSELECT "patients".* FROM "patients" WHERE "patients"."id" = ? LIMIT 1[0m [["id", 1]] [1m[35mCACHE (0.0ms)[0m SELECT "patients".* FROM "patients" WHERE "patients"."id" = ? LIMIT 1 [["id", 1]] [1m[36mCACHE (0.0ms)[0m [1mSELECT "patients".* FROM "patients" WHERE "patients"."id" = ? LIMIT 1[0m [["id", 1]] [1m[35mCACHE (0.0ms)[0m SELECT "doctors".* FROM "doctors" WHERE "doctors"."id" = ? LIMIT 1 [["id", 1]] [1m[36mCACHE (0.0ms)[0m [1mSELECT "patients".* FROM "patients" WHERE "patients"."id" = ? LIMIT 1[0m [["id", 1]] Rendered appointments/_form51.html.erb (13.0ms) Rendered appointments/new51.html.erb within layouts/application (22.0ms) Rendered welcome/_form.html.erb (1.0ms) Completed 200 OK in 103.0ms (Views: 100.9ms | ActiveRecord: 1.0ms) Started GET "/appointments/30" for 127.0.0.1 at 2014-06-22 08:22:53 +0200 Processing by AppointmentsController#show as HTML Parameters: {"id"=>"30"} [1m[36mAppointment Load (0.0ms)[0m [1mSELECT "appointments".* FROM "appointments" WHERE "appointments"."id" = ? LIMIT 1[0m [["id", "30"]] Rendered appointments/show.html.erb within layouts/application (2.0ms) Rendered welcome/_form.html.erb (1.0ms) Completed 200 OK in 80.0ms (Views: 77.0ms | ActiveRecord: 0.0ms) A: You problem comes from the url you use on your form. You should try like this on your _form51.html.erb: form_for @appointment, :url => url_for(:action => "create51") do |f| If you do rake routes | grep 'create51' you'll have the rails path. Then you can also do like this: form_for @appointment, :url => create51_path do |f| (here I suppose the command gave you create51 as path). A: Routes Wow your routes are really WET You really need to read up on resourceful routing - every route you have in your routes file really needs to be associated to a particular controller (apart from root to and other wildcards) Whoever wrote your routes file has laden it with massive numbers of specific actions. Frankly, it's a mess and I would highly recommend you go through & remove any custom actions you've got in there. Resourceful routing is described in the Rails docs as thus: Bottom line is you shouldn't be creating routes for specific records; you need to create a system to handle the different processes your application will have -- Form If you're not seeing any object created in your db, there could be a number of problems. The biggest, though, is your use of an @instance variable in your partial. To the best of my knowledge, partials don't carry @instance variables through to their render process. You have to pass local variables: #new.html.erb <%= render "form51", locals: { appointment: @appointment } %> #_form51.html.erb <%= form_for appointment do |f| %> ... <% end %> -- Being honest, there's so much to fix with this, it will be best if you ask for help in the comments here - so I can pinpoint exactly what needs to be fixed
doc_23535875
MySessionObject object = Session.getObject(); //then object is passed to Runnable task. private class MyTask implements Runnable { private final MySessionObject object; public SaveVisitorTask(MySessionObject object) { this.object = object; } @Override public void run() { MyDao dao = new MyDao(); MySessionObject savedObject = dao.save(object); this.object.setId(savedObject.getId()); } } Description: * *The object retrived from session, e.g. thread local variable. *Then it is passed to Runnable task where it persisted asynchronously *And then new id is set from saved object to object from thread local variable. The question is pretty simple - is that code thread safe? It obvious that thread local variable (session) can not be shared to threads, but what about references that it holds? Does the statement this.object.setId(savedObject.getId()); affects original object or not? P.S. If this code is not threadsafe (personally I believe to) could somebody explain why? A: It obvious that thread local variable (session) can not be shared to threads, but what about references that it holds? ThreadLocal variables are put in a special map in Thread class behind the scene and this map maintains the values set. The key of the entry in map is the calling thread itself and value is the value set by "set" method of ThreadLocal. public class Thread implements Runnable { .................. .................. /* ThreadLocal values pertaining to this thread. This map is maintained * by the ThreadLocal class. */ ThreadLocal.ThreadLocalMap threadLocals = null; } Now the reason they ended up here is because at some point a piece of code ( inside a method) ran which called "set" on the Threadlocal which created an entry in to the threadlocals map with key as the thread and value as the object set. public class ThreadLocal<T> { ......... ......... /** * Sets the current thread's copy of this thread-local variable * to the specified value. Most subclasses will have no need to * override this method, relying solely on the {@link #initialValue} * method to set the values of thread-locals. * * @param value the value to be stored in the current thread's copy of * this thread-local. */ public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); } } So as long as the variable which was set did not escape from the thread method stack, it would be unique to each thread and hence would be thread safe. However if it pointed to some shared variable such as instance variable of class, then there are chances that multiple threads point to same object in the threadlocal map. In that case - it is definitely not thread safe. Also the docs of Threadlocal mentions this: Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist). A: Have a look at Java Atomic Variables. An atomic operation will either be completed or not done at all. Other threads will not be able to see the operation "in progress". it will never be viewed in a partially complete state. A: Statement this.object.setId(savedObject.getId()); actually affects original object.Because object is not retrieved from thread local in other thread but you pass it directly to other thread. If you call Session.getObject(); in your second thread then it will return you a thread specific copy of object.
doc_23535876
html code: <!DOCTYPE html> <!-- @license Copyright 2019 Google LLC. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 --> <html> <head> <title>Simple Map</title> <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script> <!-- jsFiddle will insert css and js --> </head> <body> <dialog id="dialog"> <form method="dialog"> <input type="text" id="google"> </form> </dialog> <!-- The `defer` attribute causes the callback to execute after the full HTML document has been parsed. For non-blocking uses, avoiding race conditions, and consistent behavior across browsers, consider loading using Promises with https://www.npmjs.com/package/@googlemaps/js-api-loader. --> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&libraries=places" defer ></script> </body> </html> and in js file, I created the google autocomplete and focus on the input field in the dialog. js code: let autocomplete; const addressDialog = document.querySelector("#dialog"); const addressGoogleField = document.querySelector("#google"); addressDialog.showModal(); function fillInAddress() { const place = autocomplete.getPlace(); console.log(place); } function initMap() { autocomplete = new google.maps.places.Autocomplete(addressGoogleField, { fields:["geometry"], types:["geocode"] }); addressGoogleField.focus(); autocomplete.addListener("place_changed", fillInAddress); } window.initMap = initMap; results: Google Places Autocomplete Box is behind the modal dialog. I want to put autocomplete box in front of the dialog. What should I do? A: This may be a z-index issue. The Google Place Autocomplete box ("pac-container" css class) is appended at the end of the body element, and not within your modal dialog. To ensure the autocomplete box is above your modal dialog div. You can try and update your css with : .pac-container { z-index: 10000; } The 10000 z-index is just a value high enough to be above the modal z-index.
doc_23535877
Well basically I want to extract info from a website, and get it in a textbox. <a href="/player/11111">what I want to be extracted</a> So as you can see, the part what says 11111 must be enabled to also extract letters instead of only numbers. I use this code: Dim mcol As MatchCollection = Regex.Matches(source, "/player/\d+"">(.+)</a>") How can I make it to extract not only numbers, but both. So it will be enable to extract a MD5 hash? Kind regards A: /\w+/i it will match any alphanumeric character with case insensitive modifier. As we know that MD5 is 32 digit hexadecimal number so the above regex may be useful in your case.
doc_23535878
<form type="upload" name="myForm" target="rgUsrStory"> <field name="st_title" title="${uiLabelMap.uStoryTitle}"><text/></field> <field name="upload_file" title="${uiLabelMap.UploadFile}"><file/></field> <field name="submitButton" title="${uiLabelMap.submit}"><submit/></field> </form> request map: <request-map uri="rgUsrStory"> <security https="true" auth="true"/> <event type="java" path="org.ofbiz.webapp.control.usrStory" invoke="rgUsrStory" /> <response name="success" type="view" value="main"/> <response name="error" type="view" value="login"/> </request-map> The event function is working properly, but i need to upload the file also to the server and details of that file to the table named as 'documents', but i don't know how to do that, i searched throw the web but only i found using ftl, also want to control the file type of defined file that i want to display those file types as allowed file in form during adding user story. For any guide and help thanks. A: Please have a look at the image upload functionality in the OFBiz content manager. There's a form <form name="ImageUpload" target="uploadImage" title="" type="upload" default-map-name="currentValue" header-row-style="header-row" default-table-style="basic-table"> <field name="dataResourceId" title="${uiLabelMap.ContentDataResourceId}"><display/></field> <field name="dataResourceTypeId" ><hidden/></field> <field name="objectInfo" title="${uiLabelMap.ContentUploadedFile}"><display /></field> <field name="imageData" entity-name="ImageDataResource" title="${uiLabelMap.ContentFile}"><file/></field> <field name="submitButton" title="${uiLabelMap.CommonUpload}" widget-style="smallSubmit"><submit button-type="button"/></field> </form> The corresponding request in the controller.xml <request-map uri="uploadImage"> <security auth="true" https="true"/> <event invoke="persistContentAndAssoc" path="" type="service"/> <response name="success" type="request" value="UploadImage"/> <response name="error" type="view" value="UploadImage"/> </request-map> The service name in services.xml lead you to the service method <service name="persistContentAndAssoc" engine="java" transaction-timeout="7200" location="org.ofbiz.content.ContentManagementServices" invoke="persistContentAndAssoc" auth="true"> <description>Create a Content, DataResource and/or ContentAssoc</description> <permission-service service-name="genericContentPermission" main-action="CREATE"/> ... </service> In org.ofbiz.content.ContentManagementServices#persistContentAndAssoc the uploaded file is read by ByteBuffer imageDataBytes = (ByteBuffer) context.get("imageData"); (the corresponding form field). You will find some other functionality like dealing with the mime type there.
doc_23535879
* *On day1 records from 1 to 100 are moved to HDFS. *On day2 new records 101 to 150 are added and 10 to 30 are removed in the database. *Now the HDFS should contain the partitions with records of 1 to 10, 31-150 records.(10 - 30 records should be removed from HDFS). I would like to know is it possible with the current behavior of sqoop, or a custom map-reduce is required to accomplish this. Any help appreciated. Thanks in advance. A: If your table is not too big, the best thing you can do through sqoop is a full import every day, overwriting the previous state. Removing deleted data is an hard task to be accomplished, since you don't know which of them are deleted... A: This is not impossible. I have implemented the same scenarios using Sqoop and pig scripts. You get your data incrementally everyday using sqoop. if some data is deleted at source, the source should send some flag for those records. This can be implemented on the source side. Once you get the records with flag you can write a pig/hive (I prefer pig) for filtering out those records from the data that you have in hdfs. Please read about SCD Type 2(Slowly Changing Dimensions ) in the following link : https://en.wikipedia.org/wiki/Slowly_changing_dimension This should clear all your doubts. Snapshot load from sqoop is also an option but it doesn't help if your data is huge in size. Hope this helps
doc_23535880
I tried to EXPLAIN my query on both my old DB and new DB and it explained different result. Since it using dump, i am assuming that no changes with the table indexes. This is the query that i wanted to run SELECT * FROM detitem where exists (select 1 from detlayanan where detitem.iddetlayanan = detlayanan.id and detlayanan.layanan_idlayanan='LYN15176176101503') the EXPLAIN from old DB +------+-------------+------------+------+------------------------------------+----------------------------+---------+--------------------------------+-------+--------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +------+-------------+------------+------+------------------------------------+----------------------------+---------+--------------------------------+-------+--------------------------+ | 1 | PRIMARY | detlayanan | ref | PRIMARY,fk_detlayanan_layanan1_idx | fk_detlayanan_layanan1_idx | 22 | const | 11030 | Using where; Using index | | 1 | PRIMARY | detitem | ref | FK_detitem_detlayanan | FK_detitem_detlayanan | 52 | citridia_sinadme.detlayanan.id | 1 | | +------+-------------+------------+------+------------------------------------+----------------------------+---------+--------------------------------+-------+--------------------------+ and the EXPLAIN from new DB +----+--------------------+------------+------------+--------+------------------------------------+---------+---------+---------------------------------------+---------+----------+-------------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+--------------------+------------+------------+--------+------------------------------------+---------+---------+---------------------------------------+---------+----------+-------------+ | 1 | PRIMARY | detitem | NULL | ALL | NULL | NULL | NULL | NULL | 2079094 | 100.00 | Using where | | 2 | DEPENDENT SUBQUERY | detlayanan | NULL | eq_ref | PRIMARY,fk_detlayanan_layanan1_idx | PRIMARY | 52 | citridia_sinadme.detitem.iddetlayanan | 1 | 5.00 | Using where | +----+--------------------+------------+------------+--------+------------------------------------+---------+---------+---------------------------------------+---------+----------+-------------+ The new one is doing Full-table scan even there is index exist. Am i missing something here? Here is the "detlayanan" table CREATE TABLE `detlayanan` ( `transaksi_idtransaksi` varchar(40) NOT NULL, `layanan_idlayanan` varchar(20) NOT NULL, `nama_layanan` varchar(255) DEFAULT NULL, `jumlah_beli` float DEFAULT NULL, `id` varchar(50) NOT NULL, `harga` decimal(20,2) DEFAULT '0.00', `hargatotal` decimal(20,2) DEFAULT '0.00', `luas_p` double(255,2) DEFAULT '0.00', `luas_l` double(255,2) DEFAULT '0.00', `luas_q` double(255,2) DEFAULT '0.00', `keterangan` varchar(255) DEFAULT '', `iddeposit` varchar(255) DEFAULT NULL, `posisi` tinyint(4) DEFAULT '1', `idworkshop` varchar(60) DEFAULT NULL, `is_wsot` tinyint(4) DEFAULT '0', `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP, `total_bersih` varchar(20) DEFAULT '0', `total_min_order` decimal(20,2) DEFAULT '0.00', `kondisi_barang` text, PRIMARY KEY (`id`), KEY `fk_detlayanan_layanan1_idx` (`layanan_idlayanan`), KEY `fk_detlayanan_deposit` (`iddeposit`), KEY `transaksi_idtransaksi` (`transaksi_idtransaksi`), CONSTRAINT `detlayanan_ibfk_1` FOREIGN KEY (`transaksi_idtransaksi`) REFERENCES `transaksi` (`idtransaksi`), CONSTRAINT `fk_detlayanan_layanan1` FOREIGN KEY (`layanan_idlayanan`) REFERENCES `layanan` (`idlayanan`) ON DELETE NO ACTION ON UPDATE NO ACTION ) And here is the "detitem" table CREATE TABLE `detitem` ( `item_iditem` varchar(20) NOT NULL, `layanan_idlayanan` varchar(255) NOT NULL, `jumlah_item` int(255) DEFAULT NULL, `transaksi_idtransaksi` varchar(255) NOT NULL, `id` varchar(50) NOT NULL, `iddetlayanan` varchar(50) NOT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP, `hapus` tinyint(4) DEFAULT '0', PRIMARY KEY (`id`), KEY `FK_detitem_item` (`item_iditem`), KEY `FK_detitem_layanan` (`layanan_idlayanan`), KEY `FK_detitem_transaksi` (`transaksi_idtransaksi`), KEY `FK_detitem_detlayanan` (`iddetlayanan`), CONSTRAINT `FK_detitem_detlayanan` FOREIGN KEY (`iddetlayanan`) REFERENCES `detlayanan` (`id`), CONSTRAINT `FK_detitem_item` FOREIGN KEY (`item_iditem`) REFERENCES `item` (`iditem`), CONSTRAINT `FK_detitem_layanan` FOREIGN KEY (`layanan_idlayanan`) REFERENCES `layanan` (`idlayanan`), CONSTRAINT `FK_detitem_transaksi` FOREIGN KEY (`transaksi_idtransaksi`) REFERENCES `transaksi` (`idtransaksi`) ) I expect the "rows" on explain stay small, in the old DB, "rows" stays at very low even in another table. but in the new DB it can shows up to million. UPDATE After some research, actually i must explicitly add some indexed column in the where statement to accompany EXISTS statement. so the query would be like this SELECT * FROM detitem WHERE <indexed column> in (<some id's>) AND EXISTS ( SELECT 1 FROM detlayanan WHERE detitem.iddetlayanan = detlayanan.id AND detlayanan.layanan_idlayanan = 'LYN15176176101503' ) apparently MySQL doing full scan on detitem table to check the subquery values is exists or not, when some indexed column are declared, sql does not need to did that. Also this case were found in MySQL. some references: https://mariadb.com/kb/en/library/exists-to-in-optimization/ A: This looks like a case where MariaDB's Optimizer is a step or two ahead of MySQL's. See if this works well: SELECT i.* FROM ( SELECT id FROM detlayanan WHERE layanan_idlayanan = 'LYN15176176101503' ) AS x JOIN detitem AS i ON x.id = i.iddetlayanan I think it will work well in both servers. Simpler yet: SELECT i.* FROM detlayanan AS lay JOIN detitem AS i ON lay.id = i.iddetlayanan WHERE lay.layanan_idlayanan = 'LYN15176176101503'
doc_23535881
Create a class that extends the SherlockFragment. In that class I have an instance of another Helper class: public class Fragment extends SherlockFragment { private Helper helper = new Helper(this.getActivity()); // More code ... } Here is an extract of the other Helper class: public class Helper { public Helper(Context context) { this.context = context; } // More code ... } Everytime I call context.someMethod (e.g. context.getResources() ) I get a NullPointerException. Why is that? A: When are you instantiating your Helper class? Make sure it's after onActivityCreated() in the lifecycle of the Fragment. http://developer.android.com/images/fragment_lifecycle.png The following code should work: @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); helper = new Helper(getActivity()); } A: You're attempting to get a Context when the Fragment is first instantiated. At that time, it is NOT attached to an Activity, so there is no valid Context. Have a look at the Fragment Lifecycle. Everything between onAttach() to onDetach() contain a reference to a valid Context instance. This Context instance is usually retrieved via getActivity() Code example: private Helper mHelper; @Override public void onAttach(Activity activity){ super.onAttach (activity); mHelper = new Helper (activity); } I used onAttach() in my example, @LaurenceDawson used onActivityCreated(). Note the differences. Since onAttach() gets an Activity passed to it already, I didn't use getActivity(). Instead I used the argument passed. For all other methods in the lifecycle, you will have to use getActivity(). A: getActivity() can return null if it gets called before onAttach() gets called. I would recommend something like this: public class Fragment extends SherlockFragment { private Helper helper; // Other code @Override public void onAttach(Activity activity) { super.onAttach(activity); helper = new Helper(activity); } } A: Hi the question has answered, but generally if you want to get context in fragment or dialogFragment use this protected lateinit var baseActivity: BaseActivity protected lateinit var contextFragment: Context override fun onAttach(context: Context) { super.onAttach(context) if (context is BaseActivity) { this.baseActivity = context } this.contextFragment = context } and in java protected BaseActivity baseActivity; protected Context context; @Override public void onAttach(@NonNull Context context) { super.onAttach(context); this.context = context; if (context instanceof BaseActivity) { this.baseActivity = (BaseActivity) context; } }
doc_23535882
Anyone know of the top of their head what is wrong w/ this? Thanks. $ curl http://localhost:8983/solr/collection1/update/csv --data-binary @books.csv -H 'Content-type:text/csv; charset=utf-8' Warning: Couldn't read data from file "books.csv", this makes an empty POST. <?xml version="1.0" encoding="UTF-8"?> <response> <lst name="responseHeader"> <int name="status">400</int> <int name="QTime">0</int></lst> <lst name="error"><str name="msg">Expected fieldnames in CSV input</str><int name="code">400</int></lst> </response> books.csv first four lines. id,cat,name,price,inStock,author,series_t,sequence_i,genre_s 0553573403,book,A Game of Thrones,7.99,true,George R.R. Martin,"A Song of Ice and Fire",1,fantasy 0553579908,book,A Clash of Kings,7.99,true,George R.R. Martin,"A Song of Ice and Fire",2,fantasy 055357342X,book,A Storm of Swords,7.99,true,George R.R. Martin,"A Song of Ice and Fire",3,fantasy A: Found it. File was in wrong directory.
doc_23535883
It should look like the green boxes below, but it looks like the red boxes. Box nr 3 is not aligned properly. Any CSS3 or even js way to fix this? A: There is a plug-in for jQuery called Masonry that is designed to do this.
doc_23535884
*[cloudstack] name=cloudstack baseurl=http://cloudstack.apt-get.eu/centos/6/4.9/ enabled=1 gpgcheck=0* Now when I'm going to install management server with command; *yum install cloudstack-management* I get the message; *Loaded plugins: fastestmirror, refresh-packagekit, security Setting up Install Process Loading mirror speeds from cached hostfile * base: mirrors.btte.net * extras: mirrors.zju.edu.cn * updates: mirror.bit.edu.cn base | 3.7 kB 00:00 cloudstack | 3.2 kB 00:00 extras | 3.3 kB 00:00 updates | 3.4 kB 00:00 **No package cloudstack-management available. Error: Nothing to do*** I'm so new with cloudstack and i'm almost stacked with this problem. Please advice how resolve this. Thanks. A: Please try to clean repository first: # yum clean all Then try installing it again: # yum install cloudstack-management If it still does not work, download the rpms cloudstack-management and cloudstack-common # wget http://cloudstack.apt-get.eu/centos/6/4.9/cloudstack-management-4.9.2.0-1.el6.x86_64.rpm # wget http://cloudstack.apt-get.eu/centos/6/4.9/cloudstack-common-4.9.2.0-1.el6.x86_64.rpm Now install the packages manually: # rpm -ivh cloudstack-* Once it is installed, you may proceed with next steps on management server installation page. A: There maybe some problem in your system or network. I suggest you to download all files and dirs to your centos, and modify your repo file set url as "baseurl=file:///DIRPATH_YOU_SOTRE_RPMS"
doc_23535885
Dictionary<string, object> person = new Dictionary<string, object>(); person.Add("ID", 1); person.Add("Name", "Alex"); to object: public class Person { public int ID{get;set;} public string Name{get;set;} } ? A: Here is my suggestion: var newPerson = new Person { ID = (int)person["ID"], Name = person["Name"].ToString() }; This has no error handling and is assuming that the fields exists in the dictionary and are filled with valid values! A: If you want to be able to do this for any object in general, you could use reflection. Assuming the values in the dictionary are the appropriate type and requires no conversion: static T GetObject<T>(Dictionary<string, object> dict) where T : new() { var obj = new T(); foreach (var property in typeof(T).GetProperties()) { var args = new object[1]; var setter = property.GetSetMethod(); // property has a public setter if (setter != null && dict.TryGetValue(property.Name, out args[0])) setter.Invoke(obj, args); } return obj; } Then to use it: var alexDict = new Dictionary<string, object> { { "ID", 1 }, { "Name", "Alex" }, }; var alexPerson = GetObject<Person>(alexDict); A: Person myPerson = new Person(); myPerson.ID = (int)person["ID"]; myPerson.Name = (string)person["Name"]; Provides no error checking with the int cast. A: The easy way: var person = new Person { Id = (int)dict["ID"], Name = (string)dict["Name"] } The generic way: use reflection.
doc_23535886
The following returns access denied: <?php $url = 'http://s3-us-west-2.amazonaws.com/alertwildfire-data-public/Axis-CupertinoHills/latest_full.jpg'; $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($ch, CURLOPT_URL, $url); $data = curl_exec($ch); header('Content-type: image/jpeg'); echo $data; The URL comes from this link: http://www.alertwildfire.org/index.html Select region then view webcam and right-click to view image. A: You need to set the appropriate "Referer" header Example: curl_setopt($ch, CURLOPT_REFERER, "http://www.alertwildfire.org/blmnv/index.html?camera=Axis-Angel&v=81e002f"); or curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Referer: http://www.alertwildfire.org/blmnv/index.html?camera=Axis-Angel&v=81e002f' ));
doc_23535887
Ive created a depository on GitHub, and I am managed to clone my git hub repository in my terminal and create a file, now I need to use a text editor (ATOM) to create a web page. Where do I go from here? I want to link my terminal, ATOM and GitHub. A: i think you don't have atom installed on your system. to install it press the download button from the https://atom.io. Once you have that file, you can click on it to extract the application and then drag the new Atom application into your "Applications" folder. full guide here
doc_23535888
Consider the following table: Value1 | Value2 | Value3 ------------------------------------ Peter | Blue | Red Peter | Null | Null Martin | Blue | Null Martin | Null | Null Boris | Null | Null Sergej | Null | Green Sergej | Null | Null You see this is a peculiar case. There are Cases where Value2 and Value3 are both set in one entry, there are cases where either Value2 and Value3 are set and there are cases where none of them are set (which don't have a duplicate). So the question is: How do I remove the duplicates (via Value1) and get the entries with the most information? I.e. if Value2 and/or Value3 are set, then the entries with those. Clearly I can't just use "not null" as there are cases (the ones not duplicated to begin with) I need to cover which have both on Null. The second problem is that I only have reading access, so it has to happen within a Select statement. Thank you very much. A: OK for MS SQL this will do it DECLARE @T TABLE (V1 VARCHAR(50), V2 VARCHAR(50), V3 VARCHAR(50)) INSERT INTO @T VALUES ('Peter', 'Blue', 'Red'), ('Peter', Null, Null), ('Martin', 'Blue',Null), ('Martin', Null, Null), ('Boris', Null, Null), ('Sergej', Null, 'Green'), ('Sergej', Null, Null) SElECT V1, V2, V3 FROM (SELECT V1, V2, V3, ROW_NUMBER () OVER (PARTITION BY V1 ORDER BY CASE WHEN V2 IS NULL THEN 1 ELSE 0 END + CASE WHEN V3 IS NULL THEN 1 ELSE 0 END) as Quality FROM @T) as T WHERE Quality = 1 RESULT V1 V2 V3 Boris NULL NULL Martin Blue NULL Peter Blue Red Sergej NULL Green EDIT: Note: this will give a single entry per name, even if there are multiple rows that contain the same amount of information. That is, if Peter has 2 rows that both have non-null values in V2 and V3, the system will pick one at random. If you want all rows with the maximum amount of information, you could replace ROW_NUMBER with RANK. This also considers V2 and V3 to be of equal weight, so a row with just V2 NULL and a row with just V3 NULL are equal. You could change that behavior by changing the CASE statements to return different values for the 2 fields. i.e. for both make NULL worth 3 and the NON-NULL for one worth 0 and the other worth 1, so NON-NULL NON-NULL is Q=1, NULL NON-NULL is Q = 3, NON-NULL NULL is Q=4, and NULL NULL is Q=6. EDIT 2: Incorrectly had NULL NULL twice in the explanation immediately above :-( EDIT 3: Extended explanation as requested in comments Sure, no problem. The "ROW_NUMBER" (and the RANK) function normally generates a sequence of numbers for your dataset. To know what the order should be based on, you have to tell it. So both functions require a "OVER (ORDER BY Col1[,Col2 ...])" clause. The ORDER BY inside the OVER() works just like an ORDER BY clause at the end of a query. In this case, I'm not using a real column in your data, I'm deriving a column (which is anonymous, I'd like to give it an alias for clarity but SQL-Server 2008 R2 doesn't support that). For reference, let's call that derived column Q even though SQL won't let us actually name it. My derived column is the sum of the 2 CASE statements, so it's an integer value that represents the number of NULLs in that row. Since the ORDER BY instruction defaults to ASCENDING order, the rows with the most data (the fewest NULLs) will have the lowest "Q" and sort to the top. And I give the whole ROW_NUMBER function output an Alias - "Quality". It's not the same as the "Q" I described above, but it's related to it. Quality will be an integer sequence starting at 1 and increasing by 1 for each row, whereas Q will be 0, 1, or 2 depending on how many NULLs there are in the row. The lowest Q rows will get the lowest Quality numbers, but for rows with identical Q values SQL will randomly order them. The last bit of the solution is the PARTITION BY clause, it tells the ROW_NUMBER (or RANK) function to break the data into sets (just like a GROUP BY clause in a query, and it too can take 1 or more columns) and re-start its numbering with each group. This way, Peter gets his his own 1,2,3,4,... Quality values, Martin gets his own 1,2,3,4,... values, etc. So when I put the "WHERE Quality = 1" clause at the end of my query, I'm saying "For each person, pick the row that has the fewest NULLs" I hope that's the question you were asking, I'm not sure I understand your "if I simply ORDER BY 1" bit.
doc_23535889
The problem is when I click on a stackpanel, the selection is unreadable because the line become dark-blue whereas the letters stay black so black on blue, you see nothing. How can I dynamically change the forecolor of the selected elements in the stackpanel? I say dynamically and not in the xml file, because all those elements are dynamically created from a database. I have code similar to this: foreach (var utilis in item.user) { StackPanelWithID ligne = new StackPanelWithID(); ligne.Orientation = Orientation.Horizontal; ligne.ID = utilis.TRIGRAMME; ligne.Height = 21; Label l = new Label(); l.Width = 120; Label l2 = new Label(); l2.Width = 145; CheckBox cbEntretien = new CheckBox(); } contentpresenter won't work... I tried several way to position it... So, I found a way to circle the problem ... in the app.xaml : <Application.Resources> <Style TargetType="{x:Type ListBoxItem}"> <Style.Resources> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="LightBlue"/> </Style.Resources> </Style> </Application.Resources> Thus the background of selected items is clearer so that the user can still read text of the selected listboxitems. and every listboxitem is concerned. and yet... I would love to know how on earth it's possible to change the selected item's text color in list box.. if I manage to get the answer I'll keep you in touch... I did this... <ControlTemplate TargetType="ListBoxItem"> <ContentPresenter> <ControlTemplate.Triggers> <Trigger Property="IsSelected" Value="true"> <Setter Property="Background" Value="Red"/> </Trigger> </ControlTemplate.Triggers> </ContentPresenter> </ControlTemplate> but stll not working, it says the trigger property can't be found in ControlTemplate... I tried to add it after the trigger property, but not working either... I tried something like this in the App.xaml : " <Style x:Key="SimpleListBoxItem" TargetType="ListBoxItem"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListBoxItem"> <ControlTemplate.Triggers> <Trigger Property="IsSelected" Value="true"> <Setter Property="Background" <!--can't find the text property so try to act on the Background color to set it to a different color than dark blue--> Value="Red"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style>" and in the particular xaml file where my listbox is : <ListBox Margin="9,64,8,313" Loaded="lstUtilisateurs_Loaded" Name="lstUtilisateurs" ItemContainerStyle="{StaticResource SimpleListBoxItem}"/> but when executing, nothing appears anymore in the listbox, nothing... I don't get it... A: Dunno if it still matters (last answer was on Mar 25 2010), but for the people who are still wondering how to accomplish this I did it this way: In the Style part: <Style x:Key="myLBStyle" TargetType="{x:Type ListBoxItem}"> <Style.Resources> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/> <!-- makes the background color transparent, removes backcolor border--> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Red"/> <!-- Sets the textcolor of the selected text to red --> </Style.Resources> </Style> In the Listbox I use then the ItemContainerStyle property like this: ItemContainerStyle="{StaticResource myLBStyle} Took me a while to find, but here it is. Hope that someone can use it! Also handy: http://msdn.microsoft.com/en-us/library/ms603164.aspx Best Regards, Sam
doc_23535890
if (window.clipboardData && window.clipboardData.getData) { // IE pastedText = window.clipboardData.getData('Text'); } else if (e.clipboardData && e.clipboardData.getData) { //non-IE pastedText = e.clipboardData.getData('text/plain'); } Non of the if/elseif block is executed in Edge. I tried using e.originalEvent.clipboardData.getData('text/plain'); But I am getting 'Access is denied.' error. Let me know, if anybody know how to fix this issue. A: Edge does not currently support the clipboard api, but it is under consideration and likely to be added in near future. A: I do not have edge, but it seems that you are not authorized to access the clipboard data. Is this on a website or are you calling this from within a JavaScript script executed locally? Make sure the website is in the trusted sites. See https://w3c.github.io/clipboard-apis/#clipboard-event-interfaces, or more precisely: 12.1 Privacy concerns Untrusted scripts should not get uncontrolled access to a user's clipboard data. This specification assumes that granting access to the current clipboard data when a user explicitly initiates a paste operation from the user agent's trusted chrome is acceptable. However, implementors must proceed carefully, and as a minimum implement the precautions below: Objects implementing the DataTransfer interface to return clipboard data must not be available outside the ClipboardEvent event handler. If a script stores a reference to an object implementing the DataTransfer interface to use from outside the ClipboardEvent event handler, all methods must be no-ops when called outside the expected context. Implementations must not let scripts create synthetic clipboard events to get access to real clipboard data except if configured to do so. Implementations should not let scripts call document.execCommand('paste') unless the user has explicitly allowed it. Implementations may choose to further limit the functionality provided by the DataTransfer interface. For example, an implementation may allow the user to disable this API, or configure which web sites should be granted access to it.
doc_23535891
I would like to understand why it always responds error. Thank you! try { HttpClient client = new DefaultHttpClient(); String getURL = "http://www.google.com"; HttpGet get = new HttpGet(getURL); HttpResponse responseGet = client.execute(get); HttpEntity resEntityGet = responseGet.getEntity(); if (resEntityGet != null) { Toast.makeText(getApplicationContext(), "ok", Toast.LENGTH_LONG).show(); } } catch (Exception e) { //e.printStackTrace(); Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show(); } Import import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; and yes and I entered permission internet <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.testhttp" android:versionCode="1" android:versionName="1.0" > <uses-permission android:name="android.permission.INTERNET" /> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> A: seems to be like you are trying to make an http request in the UI thread. put your request in another thread. A: You can also use this code to make an HTTP Request: public class RequestClient extends AsyncTask<String, Void, String>{ Context context; public RequestClient(Context c) { context = c; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... aurl){ String responseString=""; HttpClient client = null; try { client = new DefaultHttpClient(); HttpGet get = new HttpGet(LoginActivity.url); HttpResponse responseGet = client.execute(get); HttpEntity resEntityGet = responseGet.getEntity(); if (resEntityGet != null) { responseString = EntityUtils.toString(resEntityGet); Log.i("GET RESPONSE", responseString.trim()); } } catch (Exception e) { Log.d("ANDRO_ASYNC_ERROR", "Error is "+e.toString()); } Log.d("ANDRO_ASYNC_RESPONSE", responseString.trim()); client.getConnectionManager().shutdown(); return responseString.trim(); } @Override protected void onPostExecute(String response) { super.onPostExecute(response); } }
doc_23535892
pom.xml cargo portion: <!-- cargo plugin --> <dependency> <groupId>org.codehaus.cargo</groupId> <artifactId>cargo-core-uberjar</artifactId> <version>1.4.3</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <!-- cargo plugin --> <plugin> <groupId>org.codehaus.cargo</groupId> <artifactId>cargo-maven2-plugin</artifactId> <version>1.4.3</version> <configuration> <container> <containerId>glassfish4x</containerId> <type>installed</type> </container> <configuration> <type>existing</type> <home>C:\glassFishV4\glassfish4\glassfish\domains</home> <properties> <cargo.hostname>localhost</cargo.hostname> <cargo.servlet.port>4848</cargo.servlet.port> <!-- if no username/password don't use these, it will fail --> <cargo.remote.username>admin</cargo.remote.username> <cargo.remote.passwordFile>C:\glassfish\glassfish4\glassfish\domains\domain1\config\admin-keyfile</cargo.remote.passwordFile> <cargo.glassfish.domain.name>domain1</cargo.glassfish.domain.name> </properties> </configuration> <deployables> <deployable> <groupId>com.project</groupId> <artifactId>projectID</artifactId> <location>${project.build.directory}/${project.build.finalName}.war</location> <type>war</type> </deployable> </deployables> </configuration> </plugin> Error Log: C:\Users\kev\projectID\com.project.projectID-1.0>mvn -e cargo:start [INFO] Error stacktraces are turned on. [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building projectID 1.0 [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- cargo-maven2-plugin:1.4.3:start (default-cli) @ projectID --- [INFO] [2.ContainerStartMojo] Resolved container artifact org.codehaus.cargo:car go-core-container-glassfish:jar:1.4.3 for container glassfish4x [INFO] [talledLocalContainer] GlassFish 4.x starting... [INFO] [talledLocalContainer] Attempting to start domain1.... Please look at the server log for more details..... [INFO] [talledLocalContainer] Authentication failed for user: admin [INFO] [talledLocalContainer] with password from password file: C:/glassFishV4/g lassfish4/glassfish/domains/password.properties [INFO] [talledLocalContainer] (Usually, this means invalid user name and/or pass word) [INFO] [talledLocalContainer] Command deploy failed. [INFO] [talledLocalContainer] GlassFish 4.x is stopping... [INFO] [talledLocalContainer] Waiting for the domain to stop . [INFO] [talledLocalContainer] Command stop-domain executed successfully. [INFO] [talledLocalContainer] GlassFish 4.x is stopped [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 22.139s [INFO] Finished at: Fri Aug 16 16:19:33 EDT 2013 [INFO] Final Memory: 12M/304M [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal org.codehaus.cargo:cargo-maven2-plugin:1.4.3:star t (default-cli) on project projectID: Execution default-cli of goal org.codehaus.c argo:cargo-maven2-plugin:1.4.3:start failed: Failed to start the GlassFish 4.x c ontainer. At least one GlassFish deployment has failed: org.codehaus.cargo.util. CargoException: GlassFish admin command failed: asadmin exited 1 -> [Help 1] org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal o rg.codehaus.cargo:cargo-maven2-plugin:1.4.3:start (default-cli) on project projectID : Execution default-cli of goal org.codehaus.cargo:cargo-maven2-plugin:1.4.3:s tart failed: Failed to start the GlassFish 4.x container. at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor .java:224) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor .java:153) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor .java:145) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProje ct(LifecycleModuleBuilder.java:84) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProje ct(LifecycleModuleBuilder.java:59) at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBu ild(LifecycleStarter.java:183) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(Lifecycl eStarter.java:161) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:318) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:153) at org.apache.maven.cli.MavenCli.execute(MavenCli.java:555) at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:214) at org.apache.maven.cli.MavenCli.main(MavenCli.java:158) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl. java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces sorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Laun cher.java:290) at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.jav a:230) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(La uncher.java:414) at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java: 357) Caused by: org.apache.maven.plugin.PluginExecutionException: Execution default-c li of goal org.codehaus.cargo:cargo-maven2-plugin:1.4.3:start failed: Failed to start the GlassFish 4.x container. at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(Default BuildPluginManager.java:115) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor .java:208) ... 19 more Caused by: org.codehaus.cargo.container.ContainerException: Failed to start the GlassFish 4.x container. at org.codehaus.cargo.container.spi.AbstractLocalContainer.start(Abstrac tLocalContainer.java:230) at org.codehaus.cargo.maven2.ContainerStartMojo.executeLocalContainerAct ion(ContainerStartMojo.java:96) at org.codehaus.cargo.maven2.ContainerStartMojo.doExecute(ContainerStart Mojo.java:63) at org.codehaus.cargo.maven2.AbstractCargoMojo.execute(AbstractCargoMojo .java:432) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(Default BuildPluginManager.java:106) ... 20 more Caused by: org.codehaus.cargo.util.CargoException: At least one GlassFish deploy ment has failed: org.codehaus.cargo.util.CargoException: GlassFish admin command failed: asadmin exited 1 at org.codehaus.cargo.container.glassfish.internal.AbstractGlassFishInst alledLocalContainer.doStart(AbstractGlassFishInstalledLocalContainer.java:193) at org.codehaus.cargo.container.spi.AbstractInstalledLocalContainer.star tInternal(AbstractInstalledLocalContainer.java:313) at org.codehaus.cargo.container.spi.AbstractLocalContainer.start(Abstrac tLocalContainer.java:211) ... 24 more Caused by: org.codehaus.cargo.util.CargoException: GlassFish admin command faile d: asadmin exited 1 at org.codehaus.cargo.container.glassfish.internal.GlassFish3xAsAdmin.in vokeAsAdmin(GlassFish3xAsAdmin.java:88) at org.codehaus.cargo.container.glassfish.internal.AbstractGlassFishInst alledLocalContainer.invokeAsAdmin(AbstractGlassFishInstalledLocalContainer.java: 96) at org.codehaus.cargo.container.glassfish.internal.AbstractGlassFishInst alledLocalContainer.invokeAsAdmin(AbstractGlassFishInstalledLocalContainer.java: 69) at org.codehaus.cargo.container.glassfish.GlassFish3xInstalledLocalDeplo yer.doDeploy(GlassFish3xInstalledLocalDeployer.java:89) at org.codehaus.cargo.container.glassfish.internal.AbstractGlassFishInst alledLocalDeployer.redeploy(AbstractGlassFishInstalledLocalDeployer.java:97) at org.codehaus.cargo.container.glassfish.internal.AbstractGlassFishInst alledLocalContainer.doStart(AbstractGlassFishInstalledLocalContainer.java:174) ... 26 more [ERROR] [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please rea d the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutio nException The weird thing is, is that I can see it start the glassfish server through eclipse and then stop it. I also tried with no password and user name for defaults because that's what they are, and as you see in this configuration I use a username and password file as described on the cargo site. I receive the same error both times. A: Just grab your editor, open C:/glassFishV4/g lassfish4/glassfish/domains/password.properties Change: AS_ADMIN_PASSWORD=adminadmin To: AS_ADMIN_PASSWORD=
doc_23535893
<soapenv:Envelope xmlns:end="http://endpoint.soap.esb.steg.com.tn/" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Header> <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"> <wsse:UsernameToken wsu:Id="UsernameToken-633D8322A7C327A0D5153295320052614"> <wsse:Username>website</wsse:Username> <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">7MyXmdbbBuyiHQwGCAY2+NxYRH8=</wsse:Password> <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">sdc+Kcgj/aghCxpUCACCxQ==</wsse:Nonce> <wsu:Created>2018-07-30T12:20:00.526Z</wsu:Created> </wsse:UsernameToken></wsse:Security> </soapenv:Header> <soapenv:Body> <end:consultInfoAboBT> <reference>00095013</reference> </end:consultInfoAboBT> </soapenv:Body> </soapenv:Envelope> This is my code request = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:end='http://endpoint.soap.esb.steg.com.tn/'>"+ "<soapenv:Header/>"+"<soapenv:Body>" + "<end:consultInfoAboBT>" + "<reference>"+reference+"</reference>" + "</end:consultInfoAboBT>" + "</soapenv:Body>"+ "</soapenv:Envelope>"; StringEntity param = new StringEntity(request); response = json.makeHttpRequestSteg(URLSWSTEG1, "POST", param, message); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(response))); A: getHeader will return you complete header with usernametoken, You need to pass UserName,Password and created(date and time) in string format. Like below request = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:end='http://endpoint.soap.esb.steg.com.tn/'>" + getHeader("website", "7MyXmdbbBuyiHQwGCAY2+NxYRH8=", "2018-07-30T12:20:00.526Z") + "<soapenv:Body>" + "<end:consultInfoAboBT>" + "<reference>"+reference+"</reference>" + "</end:consultInfoAboBT>" + "</soapenv:Body>"+ "</soapenv:Envelope>"; StringEntity param = new StringEntity(request); response = json.makeHttpRequestSteg(URLSWSTEG1, "POST", param, message); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(response))); GetHeader() Function which will return Header token. public String getHeader(String Username, String Password, String Created) { String Nonce; String authID = ""; String nonceLocal = ""; Random randGen = new Random(); nonceLocal = "" + randGen.nextInt(); authID = nonceLocal + Created + Password; MessageDigest mDigest = null; try { mDigest = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } mDigest.reset(); byte[] digestResult = mDigest.digest(authID.getBytes()); Password = Base64.getEncoder().encodeToString(digestResult); Nonce = Base64.getEncoder().encodeToString(nonceLocal.getBytes()); return "<soapenv:Header>\n" + "<wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">\n" + "<wsse:UsernameToken wsu:Id=\"UsernameToken-633D8322A7C327A0D5153295320052614\">\n" + "<wsse:Username> + Username + </wsse:Username>\n" + "<wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest\">" + Password + "</wsse:Password>\n" + "<wsse:Nonce EncodingType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary\">"+Nonce +"</wsse:Nonce>\n" + "<wsu:Created>" + Created +"</wsu:Created>\n" + "</wsse:UsernameToken></wsse:Security>\n" + "</soapenv:Header>"; } A: Please refer following example. HeaderHandlerResolver header class : public class HeaderHandlerResolver implements HandlerResolver { @Override public List<Handler> getHandlerChain(PortInfo portInfo) { List handlerChain = new ArrayList(); HeaderHandler hh = new HeaderHandler(); handlerChain.add(hh); return handlerChain; } } HeaderHandler class : public class HeaderHandler implements SOAPHandler<SOAPMessageContext> { public Set<QName> getHeaders() { return null; } public boolean handleMessage(SOAPMessageContext smc) { Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); if (outboundProperty.booleanValue()) { SOAPMessage message = smc.getMessage(); try { SOAPEnvelope envelope = smc.getMessage().getSOAPPart().getEnvelope(); SOAPHeader header = envelope.getHeader(); if (header == null) { header = envelope.addHeader(); } SOAPElement security = header.addChildElement("Security", "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); SOAPElement usernameToken = security.addChildElement("UsernameToken", "wsse"); usernameToken.addAttribute(new QName("xmlns:wsu"), "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"); usernameToken.addAttribute(QName.valueOf("wsu:Id"), "UsernameToken-1"); SOAPElement username = usernameToken.addChildElement("Username", "wsse"); username.addTextNode("username"); SOAPElement password = usernameToken.addChildElement("Password", "wsse"); password.setAttribute("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"); password.addTextNode("password"); SOAPFactory soapFactory = SOAPFactory.newInstance(); security.addAttribute(soapFactory.createName("SOAP-ENV:mustUnderstand"), "1"); message.saveChanges(); message.writeTo(System.out); System.out.println(""); } catch (Exception e) { e.printStackTrace(); } } else { try { SOAPMessage message = smc.getMessage(); message.writeTo(System.out); System.out.println(""); } catch (Exception ex) { ex.printStackTrace(); } } return outboundProperty; } public boolean handleFault(SOAPMessageContext context) { return true; } public void close(MessageContext context) { } } Implement following under SOAP web service client method. HeaderHandlerResolver handlerResolver = new HeaderHandlerResolver(); service.setHandlerResolver(handlerResolver);
doc_23535894
var tryArray = [{ name: 'name1', subname: 'subname1', symbolname: 'symbol1' }, { name: 'name1', subname: 'subname11', symbolname: 'symbol11' }, { name: 'name2', subname: 'subname2', symbolname: 'symbol2' }, { name: 'name2', subname: 'subname22', symbolname: 'symbol22' }, { name: 'name3', subname: 'subname3', symbolname: 'symbol3' }, { name: 'name3', subname: 'subname33', symbolname: 'symbol33' }]; I want to convert this array into a nested object, where the name will be parent of subname, and subname will be parent of symbolname. For example: result = { name1: { subname1: [symbolname1], subname11: [symbolname11] }, name2: { subname2: [symbolname2], subname22: [symbolname22] }, name3: { subname3: [symbolname3], subname33: [symbolname33] } } I have tried using reduce like this tryArray.reduce((object, item) => { object[item.name] = {[item.subname]: [item.symbolname]} },{}) but it returned only one subname. any ideas how to resolved this, thank you so much A: reduce expects a return value like: var tryArray = [{"name":"name1","subname":"subname1","symbolname":"symbol1"},{"name":"name1","subname":"subname11","symbolname":"symbol11"},{"name":"name2","subname":"subname2","symbolname":"symbol2"},{"name":"name2","subname":"subname22","symbolname":"symbol22"},{"name":"name3","subname":"subname3","symbolname":"symbol3"},{"name":"name3","subname":"subname33","symbolname":"symbol33"}] var result = tryArray.reduce((object, item) => { object[item.name] = object[item.name] || {}; //Need to init name if not exst object[item.name][item.subname] = [item.symbolname]; return object; }, {}) console.log( result ); If you have multiple symbolnames in a subname, you can: var tryArray = [{"name":"name1","subname":"subname1","symbolname":"symbol1"},{"name":"name1","subname":"subname11","symbolname":"symbol11"},{"name":"name2","subname":"subname2","symbolname":"symbol2"},{"name":"name2","subname":"subname22","symbolname":"symbol22"},{"name":"name3","subname":"subname3","symbolname":"symbol3"},{"name":"name3","subname":"subname33","symbolname":"symbol33"}]; var result = tryArray.reduce((object, item) => { object[item.name] = object[item.name] || {}; //Need to init name if not exist object[item.name][item.subname] = object[item.name][item.subname] || []; //Need to subname name if not exist object[item.name][item.subname].push(item.symbolname); //Push the symbolname return object; }, {}); console.log(result);
doc_23535895
I have this boost spirit parser for string literal. It works. Now I would like to start handle errors when it fail. I copied the on_error handle 1-1 from the mini xml example and it compiles, but it is never triggered (no errors are outputted). This is the parser: #define BOOST_SPIRIT_USE_PHOENIX_V3 #define BOOST_SPIRIT_DEBUG #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix.hpp> #include <boost/spirit/home/support/iterators/line_pos_iterator.hpp> #include <boost/spirit/include/phoenix_fusion.hpp> #include <boost/spirit/include/phoenix_stl.hpp> #include <boost/fusion/include/adapt_struct.hpp> namespace qi = boost::spirit::qi; struct my_handler_f { template <typename...> struct result { typedef void type; }; template <typename... T> void operator()(T&&...) const { std::cout << "\nmy_handler_f() invoked with " << sizeof...(T) << " arguments\n"; } }; struct append_utf8_f { template <typename, typename> struct result { typedef void type; }; template <typename INT> void operator()(INT in, std::string& to) const { auto out = std::back_inserter(to); boost::utf8_output_iterator<decltype(out)> convert(out); *convert++ = in; } }; struct get_line_f { template <typename> struct result { typedef size_t type; }; template <typename It> size_t operator()(It const& pos_iter) const { return get_line(pos_iter); } }; struct RangePosition { size_t beginLine, endLine; }; struct String : public RangePosition { String() : RangePosition() , value() , source() { } std::string value; std::string source; }; BOOST_FUSION_ADAPT_STRUCT(String, (std::string, value) (std::string, source) (size_t, beginLine) (size_t, endLine) ) template <typename Iterator> struct source_string : qi::grammar<Iterator, String(), qi::space_type> { struct escape_symbols : qi::symbols<char, char> { escape_symbols() { add ("\'" , '\'') ("\"" , '\"') ("\?" , '\?') ("\\" , '\\') ("0" , '\0') ("a" , '\a') ("b" , '\b') ("f" , '\f') ("n" , '\n') ("r" , '\r') ("t" , '\t') ("v" , '\v') ; } } escape_symbol; source_string() : source_string::base_type(start) { using qi::raw; using qi::_val; using qi::_1; using qi::_2; using qi::_3; using qi::_4; using qi::space; using qi::omit; using qi::no_case; using qi::print; using qi::eps; using qi::on_error; using qi::fail; using qi::lit; namespace phx = boost::phoenix; using phx::at_c; using phx::begin; using phx::end; using phx::construct; using phx::ref; using phx::val; escape %= escape_symbol; character %= (no_case["\\x"] > hex12) | ("\\" > (oct123 | escape)) | (print - (lit('"') | '\\')); unicode = ("\\u" > hex4[append_utf8(_1, _val)]) | ("\\U" > hex8[append_utf8(_1, _val)]); string_section %= '"' > *(unicode | character) > '"'; string %= string_section % omit[*space]; main = raw [ string[at_c<0>(_val) = _1] ] [ at_c<1>(_val) = construct<std::string>(begin(_1), end(_1)), at_c<2>(_val) = get_line_(begin(_1)), at_c<3>(_val) = get_line_(end(_1)) ]; start %= eps > main; on_error<fail>(start, my_handler); } boost::phoenix::function<my_handler_f> my_handler; qi::rule<Iterator, std::string()> escape; qi::uint_parser<char, 16, 1, 2> hex12; qi::uint_parser<char, 8, 1, 3> oct123; qi::rule<Iterator, std::string()> character; qi::uint_parser<uint16_t, 16, 4, 4> hex4; qi::uint_parser<uint32_t, 16, 8, 8> hex8; boost::phoenix::function<append_utf8_f> append_utf8; qi::rule<Iterator, std::string()> unicode; qi::rule<Iterator, std::string()> string_section; qi::rule<Iterator, std::string()> string; boost::phoenix::function<get_line_f> get_line_; qi::rule<Iterator, String(), qi::space_type> main; qi::rule<Iterator, String(), qi::space_type> start; }; and this is the test code int main() { std::string str[] = { "\"\\u1234\\U0002345\"", //"\"te\"\"st\"", //"\"te\" \"st\"", //"\"te\" \n \"st\"", //"\"\"", //"\"\\\"\"", //"\"test\"", //"\"test\" something", //"\"\\\'\\\"\\\?\\\\\\a\\b\\f\\n\\r\\t\\v\"", //"\"\\x61cd\\X3012\\x7z\"", //"\"\\141cd\\06012\\78\\778\"", "\"te", //"\"te\nst\"", //"\"test\\\"", //"\"te\\st\"", // }; typedef boost::spirit::line_pos_iterator<std::string::const_iterator> Iterator; for (size_t i = 0; i < sizeof(str) / sizeof(str[0]); ++i) { source_string<Iterator> g; Iterator iter(str[i].begin()); Iterator end(str[i].end()); String string; bool r = phrase_parse(iter, end, g, qi::space, string); if (r) std::cout << string.beginLine << "-" << string.endLine << ": " << string.value << " === " << string.source << "\n"; else std::cout << "Parsing failed\n"; } }
doc_23535896
This issue arises under load testing for even a small amount (< 10) users. I have configured the messageConverters in my configuration class. @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(new MappingJackson2HttpMessageConverter( new Jackson2ObjectMapperBuilder().dateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ")).mixIn(LiquidAssignment.class, InventoryProviderAssignmentMixin.class) .deserializerByType(ActionData.class, new ActionDataDeserializer()).build())); converters.add(new MappingJackson2XmlHttpMessageConverter()); } I am using Spring Boot 1.5.4 Java 1.8 Jackson 2.9.7 Tomcat 8.5.33 A: Looking at the source code of UTF8JsonGenerator._flushBuffer(), there is no indication of LockSupport.parkNanos(). So it has probably been inlined by the JIT compiler from OutputStream.write(). My guess is it's the place where – for your application – Tomcat typically waits until the client has accepted all the output (expect for the last piece that fits into the typical connection buffer size) before it can close the connection. We have had bad experience with slow clients in the past. Until they have retrieved all the output, they block a thread in Tomcat. And blocking a few dozens threads in Tomcat seriously reduces the throughput of a busy web app. Increasing the number of threads isn't the best option as the blocked threads also occupy a considerable amount of memory. So what you want is that Tomcat can handle a request as quickly as possible and then move on to the next request. We have solved the problem by configuring our reverse proxy, which we always had in front of Tomcat, to immediately consume all output from Tomcat and deliver it to the client at the client's speed. The reverse proxy is very efficient at handling slow clients. In our case, we have used nginx. We also looked at Apache httpd. But at the time, it wasn't capable of doing it. Additional Note Clients that unexpectedly disconnect also look like slow clients to the server as it takes some time until it has been fully established that the connection is broken.
doc_23535897
For tables I would use the range field but this is not available for fields. Is there a way how to do that? A: If you want the page number to display as part of the QR Code, you could embed a page field in the text of the code. Something like: * *{ DisplayBarCode "{ Date } { Time } Page { Page }" QR \s 100 \r 0 \q 3 } Note the quotation marks. They are necessary. The DATE and TIME fields are the date and time when the document is printed or those fields are updated. They are not fixed timestamps. I am working on the code for you to enter a field like the one shown. * *Is that what you want? *Do you want to have the page, date, and time appear inside the DisplayBarCode field so that they show up when the bar code is read? *Do you instead of the current date and time want a time stamp for when the code is run? *What else goes in the field? The current content? Before or after the date, time and page? Take a look at the second answer in this thread (from WillWillPower): Setting up a nested field in Word using VBA It uses the range of the field code.
doc_23535898
I've tried looking at the page source but all it tells me is http:/localhost/.... which is not what I need. My Xampp directory (where I load Xampp control) is located in my desktop but there is no change when I alter stuff inside its htdocs. A: The default root for XAMPP, assuming you installed in the default location, is c:\xampp\htdocs. You can change this by modifying the Apache configuration in c:\xampp\apache\conf\httpd.conf. A: You can always check it through PHP: echo $_SERVER["DOCUMENT_ROOT"]; Or if you want to use WordPress functions: echo get_stylesheet_directory(); Include these codes in your page.php or header.php for example.
doc_23535899
Its response is gzip encoded. I am not able to parse correctly a particular field, though the decompression is successful. I am also using htmlagilitypack to parse it, the parsed value of the field is only a part of the original value as an example : I am getting only /wEWAwKc04vTCQKb86mzBwKln/PuCg== whereas the firebug shows the actual value as much longer: /wEWBgKj7IuJCgKb86mzBwKln/PuCgLT250qAtC0+8cMAvimiNYD what does the '==' at the end means? I am assuming it that its a error on decompressors behalf? A: The character = is added by the Base64 encoding. Encoding the following sentence Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure. you would get TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4= The = character can only be present at the end of the Base64 string. If you obtain it, it means you are probably getting all the characters; vice versa is not true, as that character is used as padding character, and it is not always mandatory in all the Base64 implementations. A: You don't have a problem with decompression. The page has obviously been correctly decompressed. Otherwise your software would likely throw an error or you'd see just a bunch of strange characters. However, what you get is an ASCII string that's obviously in Base 64 encoding. The equal signs at the end appear if the original binary data is not a multiple of 3 bytes. So that's all perfect Base 64 data. As to why your crawler gets different data than Firefox with Firebug: I don't know but can image many reasons. These are two separate browsing sessions and the web site might just assign them different session IDs or somehow record some history of the session. Anyhow, at the end of the day I don't understand your problem. What exactly are you unable to parse? Do you get some kind of error? What do you mean by field? Are you talking about a field of an HTML form?