title
stringlengths
13
150
body
stringlengths
749
64.2k
label
int64
0
3
token_count
int64
1.02k
28.5k
UIPickerView won't display the data loaded from NSUserDefaults - App is crashing while loading data
<p><em>I made a first try to use NSUserDefaults in an App with UIPickerViews. But the App is crashing while testing / the data isn't displayed in the PickerView. I still try to fix it myself but some help would be great.</em></p> <p><strong>ViewController3:</strong> <em>Where the user should save data to the NSUserDefault. Therefore there is an textField to write down something and a "Savebutton"</em> </p> <pre><code>class ViewController3: UIViewController, UITextFieldDelegate { @IBOutlet weak var textField: UITextField! </code></pre> <p>...</p> <pre><code> @IBAction func tappedAddButton(sender: AnyObject) { var userDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults() var exercisesList:NSMutableArray? = userDefaults.objectForKey("exercisesList") as? NSMutableArray var dataSet:NSMutableDictionary = NSMutableDictionary() dataSet.setObject(textField.text, forKey: "exercises") if ((exercisesList) != nil){ var newMutableList:NSMutableArray = NSMutableArray(); for dict:AnyObject in exercisesList!{ newMutableList.addObject(dict as NSDictionary) } userDefaults.removeObjectForKey("exercisesList") newMutableList.addObject(dataSet) userDefaults.setObject(newMutableList, forKey: "exercisesList") }else{ userDefaults.removeObjectForKey("exercisesList") exercisesList = NSMutableArray() exercisesList!.addObject(dataSet) userDefaults.setObject(exercisesList, forKey: "exercisesList") } userDefaults.synchronize() self.view.endEditing(true) textField.text = "" } </code></pre> <p><strong>ViewController 1:</strong> <em>Where the saved data should be loaded from NSUserDefaults and displayed in pickerView1</em></p> <pre><code>class ViewController: UIViewController,UIPickerViewDelegate { @IBOutlet weak var pickerView1: UIPickerView! @IBOutlet weak var pickerView2: UIPickerView! @IBOutlet weak var pickerView3: UIPickerView! var reps = [["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25"],["x"]] var weight = [["0","1","2","3","4","5"],["0","1","2","3","4","5","6","7","8","9"],["0","1","2","3","4","5","6","7","8","9"],[","],["0","25","5","75"],["kg","lbs"]] var exercises:NSMutableArray = NSMutableArray(); override func viewDidLoad() { super.viewDidLoad() var userDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults() var exercisesListFromUserDefaults:NSMutableArray? = userDefaults.objectForKey("exercisesList") as? NSMutableArray if ((exercisesListFromUserDefaults) != nil){ exercises = exercisesListFromUserDefaults! } self.pickerView1.reloadAllComponents() } func numberOfComponentsInPickerView(pickerView: UIPickerView) -&gt; Int { switch pickerView { case pickerView1: return 1 case pickerView2: return reps.count case pickerView3: return weight.count default: assertionFailure("Unknown pickerView") } } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -&gt; Int { switch pickerView { case pickerView1: return exercises.count case pickerView2: return reps[component].count case pickerView3: return weight[component].count default: assertionFailure("Unknown pickerView") } } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -&gt; String! { switch pickerView { case pickerView1: return exercises[row] as String case pickerView2: return reps[component][row] case pickerView3: return weight[component][row] default: assertionFailure("Unknown pickerView") } } } </code></pre>
3
1,456
How do I reindex a pandas DataFrame while also resampling it and aggregating its data according to the new index?
<p><strong>1) I have the following 1-minute-frequency-data in a pandas DataFrame:</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">0</th> <th style="text-align: left;">Open</th> <th style="text-align: left;">High</th> <th style="text-align: left;">Low</th> <th style="text-align: left;">Close</th> <th style="text-align: left;">Volume</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">2010-10-19 06:31:00</td> <td style="text-align: left;">58.75</td> <td style="text-align: left;">58.81</td> <td style="text-align: left;">58.58</td> <td style="text-align: left;">58.59</td> <td style="text-align: left;">228125</td> </tr> <tr> <td style="text-align: left;">2010-10-19 06:32:00</td> <td style="text-align: left;">58.59</td> <td style="text-align: left;">58.68</td> <td style="text-align: left;">58.55</td> <td style="text-align: left;">58.57</td> <td style="text-align: left;">153303</td> </tr> <tr> <td style="text-align: left;">2010-10-19 06:33:00</td> <td style="text-align: left;">58.57</td> <td style="text-align: left;">58.6</td> <td style="text-align: left;">58.5</td> <td style="text-align: left;">58.52</td> <td style="text-align: left;">115647</td> </tr> <tr> <td style="text-align: left;">2010-10-19 06:34:00</td> <td style="text-align: left;">58.52</td> <td style="text-align: left;">58.58</td> <td style="text-align: left;">58.48</td> <td style="text-align: left;">58.58</td> <td style="text-align: left;">63577</td> </tr> <tr> <td style="text-align: left;">2010-10-19 06:35:00</td> <td style="text-align: left;">58.57</td> <td style="text-align: left;">58.59</td> <td style="text-align: left;">58.51</td> <td style="text-align: left;">58.53</td> <td style="text-align: left;">111770</td> </tr> </tbody> </table> </div> <p><strong>2) I also have the following index array:</strong></p> <p>[2010-10-19 06:32:00, 2010-10-19 06:35:00]</p> <p><strong>3) I want to reindex the DataFrame according to the index array</strong> such that the new DataFrame will only have the 2 rows of the index array, while managing to resample it so that the high of the first row of the new dataframe is the higher of the highs from the first 2 rows of the original dataframe, the low of the second row of the new dataframe is the lower of the 3 lows in the original dataframe, etc.</p> <p>Normally, one would aggregate one's data via .resample() and .agg(), but that's once you already have the dataframe in the state that you want. I can't use reindex() in such a way that I could follow it up with .resample() and accomplish this.</p> <p>I suppose I'm looking for a way to reindex and resample in one move. How do I best do this?</p>
3
1,073
Vertical alignment for two inline-block elements not working as expected
<p>In the code below, why do I need to set <code>vertical-align: top</code> to both elements to close the gap between them? If the gap occurs on the first element only, can't I just set that to <code>vertical-align: top</code> to close the gap?</p> <p>Here is what occurred if I assign vertical-align property to only <code>.test</code> :</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;title&gt;&lt;/title&gt; &lt;style&gt; body{ width: 100vw; height: 100vh; margin: 0; background-color: black; } .test { vertical-align: top; display: inline-block; width: 10%; height: 100px; background-color: lightblue; } hr{ display: inline-block; width: 100%; border: thick solid lightgreen; margin: 0; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class = "test"&gt;&lt;/div&gt;&lt;hr/&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>This is what happened when I assign vertical-align to <em>both</em> elements:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;title&gt;&lt;/title&gt; &lt;style&gt; body{ width: 100vw; height: 100vh; margin: 0; background-color: black; } .test { vertical-align: top; display: inline-block; width: 10%; height: 100px; background-color: lightblue; } hr{ display: inline-block; width: 100%; border: thick solid lightgreen; margin: 0; vertical-align: top; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class = "test"&gt;&lt;/div&gt;&lt;hr/&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
3
1,205
How to make columns editable in special abstract model JTable
<p>Hey guys i doing my assignment and now i have the problem with non editable cells, actually it became editable, but the result of editing didn't set at arraylist, I tried many solution from internet, but it doesn't work. So my work like registration system which get information about guest, and then stored it into csv file. In additional function the program must let display, update, delete and searching function.</p> <p>I finished all, without update,delete and searching. Can you please looking my code and help me or give the advice, link or something useful.</p> <p>this is my abstract model:</p> <pre><code>public class ddispmodel extends AbstractTableModel { private final String[] columnNames = { "FirstName", "SecondName", "Date of birth", "Gender", "Email", "Address", "Number", "Attending","ID" }; private ArrayList&lt;String[]&gt; Data = new ArrayList&lt;String[]&gt;(); private boolean editable; public void AddCSVData(ArrayList&lt;String[]&gt; DataIn) { this.Data = DataIn; this.fireTableDataChanged(); } @Override public int getColumnCount() { return columnNames.length;// length; } @Override public int getRowCount() { return Data.size(); } @Override public String getColumnName(int col) { return columnNames[col]; } @Override public Object getValueAt(int row, int col) { return Data.get(row)[col]; } public boolean isCellEditable(int row, int col) { setValueAt(Data, row, col); this.fireTableCellUpdated(row, col); return true; } } </code></pre> <p>This is part of my main class It is action Listener of menu item witch activate displaying function (I didn't copy all class, because it nearly 1000 lines, but if it necessary, i can submit all code )</p> <pre><code> dlog.addActionListener(new ActionListener (){ public void actionPerformed(ActionEvent e){ CSVFileDomestic Rd = new CSVFileDomestic(); ddispmodel ddispm = new ddispmodel(); ddisp.setModel(ddispm); File DataFile = new File("D:\\cdne4\\WorkPlace\\Domestic.csv"); ArrayList&lt;String[]&gt; Rs2 = Rd.ReadCSVfile(DataFile); ddispm.AddCSVData(Rs2); System.out.println("Rows: " + ddispm.getRowCount()); System.out.println("Cols: " + ddispm.getColumnCount()); cl.show(cp, "dispDomPanel"); } }); </code></pre> <p>and File class which convert date from csv to arraylist</p> <pre><code> import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.Arrays; public class CSVFileDomestic { private final ArrayList&lt;String[]&gt; Rs = new ArrayList&lt;String[]&gt;(); private String[] OneRow; public ArrayList&lt;String[]&gt; ReadCSVfile(File DataFile) { try { BufferedReader brd = new BufferedReader(new FileReader(DataFile)); while (brd.ready()) { String st = brd.readLine(); OneRow = st.split(","); Rs.add(OneRow); System.out.println(Arrays.toString(OneRow)); } } catch (Exception e) { String errmsg = e.getMessage(); System.out.println("File not found:" + errmsg); } return Rs; </code></pre> <p>I am new at Java and this is my first program , please can you explain more easily</p>
3
1,395
how to arrange multidimensional array - Group by value in php?
<p>I want to arrange same date items to single index, I have following array -</p> <pre><code>Array( [0] =&gt; Array ( [date] =&gt; 30 Dec 2015 [record] =&gt; Array ( [id] =&gt; 84675 [name] =&gt; Item1 ) ) [1] =&gt; Array ( [date] =&gt; 28 Dec 2015 [record] =&gt; Array ( [id] =&gt; 84675 [name] =&gt; item2 ) ) [2] =&gt; Array ( [date] =&gt; 22 Nov 2015 [record] =&gt; Array ( [id] =&gt; 2011 [name] =&gt; item3 ) ) [3] =&gt; Array ( [date] =&gt; 22 Nov 2015 [record] =&gt; Array ( [id] =&gt; 86649 [name] =&gt; item4 ) )) </code></pre> <p>I want to arrange this array like -</p> <pre><code>Array( [0] =&gt; Array ( [date] =&gt; 30 Dec 2015 [record] =&gt; Array ( [id] =&gt; 84675 [name] =&gt; Item1 ) ) [1] =&gt; Array ( [date] =&gt; 28 Dec 2015 [record] =&gt; Array ( [id] =&gt; 84675 [name] =&gt; item2 ) ) [2] =&gt; Array ( [date] =&gt; 22 Nov 2015 [record] =&gt; Array ( [id] =&gt; 2011 [name] =&gt; item3 ),Array ( [id] =&gt; 86649 [name] =&gt; item4 ) ) ) </code></pre> <p>I want to arrange same date items into single index, can anybody please help me.I tried to arrange it using loops but couldn't get success.Any help would be really appreciated. </p> <p>Thanks!</p>
3
1,121
Table overflowing after adding more headers
<p>I am having issues with a table that is overflowing after adding a few headers. For some reason, after I add more than one header, my table shifts to the right.</p> <p>This is how the original table looks like: <a href="https://i.stack.imgur.com/xxn02.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xxn02.jpg" alt="table" /></a> You can see everything fits. However, after adding three more headers, the table shifted.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table class="table table-bordered" style="font-weight: bolder;color: black;width:100%;"&gt; &lt;thead&gt; &lt;tr style="border: 1px solid black;"&gt; &lt;th style="border: 1px solid black; font-size:11px;width:20px;text-align:center;font-weight: bolder;color: black;vertical-align: bottom;"&gt;SUBJECTS&lt;/th&gt; &lt;th style="border: 1px solid black; font-size:11px;width:5px;font-weight: bolder;color: black;writing-mode: vertical-lr;transform: rotate(180deg);vertical-align: middle;"&gt;CA1 10%&lt;/th&gt; &lt;th style="border: 1px solid black; font-size:11px;width:5px;font-weight: bolder;color: black;writing-mode: vertical-lr;transform: rotate(180deg);vertical-align: middle;"&gt;CA2 10%&lt;/th&gt; &lt;th style="border: 1px solid black; font-size:11px;width:5px;font-weight: bolder;color: black;writing-mode: vertical-lr;transform: rotate(180deg);vertical-align: middle;"&gt;CA3 10%&lt;/th&gt; &lt;th style="border: 1px solid black; font-size:11px;width:5px;font-weight: bolder;color: black;writing-mode: vertical-lr;transform: rotate(180deg);vertical-align: middle;"&gt;CA4 10%&lt;/th&gt; &lt;th style="border: 1px solid black; font-size:11px;width:5px;font-weight: bolder;color: black;writing-mode: vertical-lr;transform: rotate(180deg);vertical-align: middle;"&gt;CA5 10%&lt;/th&gt; &lt;th style="border: 1px solid black; font-size:11px;width:5px;font-weight: bolder;color: black;writing-mode: vertical-lr;transform: rotate(180deg);vertical-align: middle;"&gt;CA6 10%&lt;/th&gt; &lt;th style="border: 1px solid black; font-size:11px;width:5px;font-weight: bolder;color: black;writing-mode: vertical-lr;transform: rotate(180deg);vertical-align: middle;"&gt;EXAM 40%&lt;/th&gt; &lt;th style="border: 1px solid black; font-size:11px;width:5px;font-weight: bolder;color: black;writing-mode: vertical-lr;transform: rotate(180deg);vertical-align: middle;"&gt;TOTAL 100%&lt;/th&gt; &lt;th style="border: 1px solid black; font-size:11px;width:5px;font-weight: bolder;color: black;writing-mode: vertical-lr;transform: rotate(180deg);vertical-align: middle;"&gt;GRADE&lt;/th&gt; &lt;th style="border: 1px solid black; font-size:11px;width:5px;font-weight: bolder;color: black;writing-mode: vertical-lr;transform: rotate(180deg);vertical-align: middle;"&gt;HIGHEST IN CLASS&lt;/th&gt; &lt;th style="border: 1px solid black; font-size:11px;width:5px;font-weight: bolder;color: black;writing-mode: vertical-lr;transform: rotate(180deg);vertical-align: middle;"&gt;LOWEST IN CLASS&lt;/th&gt; &lt;th style="border: 1px solid black; font-size:11px;width:5px;font-weight: bolder;color: black;writing-mode: vertical-lr;transform: rotate(180deg);vertical-align: middle;"&gt;POSITION&lt;/th&gt; &lt;th style="border: 1px solid black; font-size:11px;width:2px;font-weight: bolder;color: black;writing-mode: vertical-lr;transform: rotate(180deg);vertical-align: middle;"&gt;REMARK&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody style="white-space: nowrap;"&gt; &lt;tr style="border: 1px solid black;height:30px;"&gt; &lt;td style="border: 1px solid black;font-size:11px;"&gt;MATHEMATICS&lt;/td&gt; &lt;td style="border: 1px solid black;font-size:11px;text-align:center;"&gt;9&lt;/td&gt; &lt;td style="border: 1px solid black;font-size:11px;text-align:center;"&gt;6&lt;/td&gt; &lt;td style="border: 1px solid black;font-size:11px;text-align:center;"&gt;5&lt;/td&gt; &lt;td style="border: 1px solid black;font-size:11px;text-align:center;"&gt;8&lt;/td&gt; &lt;td style="border: 1px solid black;font-size:11px;text-align:center;"&gt;2&lt;/td&gt; &lt;td style="border: 1px solid black;font-size:11px;text-align:center;"&gt;7&lt;/td&gt; &lt;td style="border: 1px solid black;font-size:11px;text-align:center;"&gt;6&lt;/td&gt; &lt;td style="border: 1px solid black;font-size:11px;text-align:center;"&gt;43&lt;/td&gt; &lt;td style="border: 1px solid black;font-size:11px;text-align:center;"&gt;C+&lt;/td&gt; &lt;td style="border: 1px solid black;font-size:11px;text-align:center;"&gt;7&lt;/td&gt; &lt;td style="border: 1px solid black;font-size:11px;text-align:center;"&gt;6&lt;/td&gt; &lt;td style="border: 1px solid black;font-size:11px;text-align:center;"&gt;14TH&lt;/td&gt; &lt;td style="border: 1px solid black;font-size:11px;text-align:left;"&gt;VERY GOOD&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3" style="border: 1px solid black;"&gt;&lt;/td&gt; &lt;td colspan="3" style="border: 1px solid black; text-align:justify;"&gt;&lt;b&gt;C.A KEYS&lt;/b&gt;&lt;/td&gt; &lt;td colspan="5" style="border: 1px solid black; text-align:justify;"&gt;&lt;b&gt;GRADE KEY&lt;/b&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3" style="border: 1px solid black; text-align:center;"&gt;&lt;/td&gt; &lt;td colspan="3" style="border: 1px solid black;text-align:justify;"&gt;CA1 - 1ST TEST &lt;/td&gt; &lt;td colspan="5" style="border: 1px solid black;text-align:justify;"&gt;FL GRADE - FINAL LETTER GRADE&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3" style="border: 1px solid black;"&gt;&lt;/td&gt; &lt;td colspan="3" style="border: 1px solid black;text-align:justify;"&gt;CA2 - 2ND TEST&lt;/td&gt; &lt;td colspan="5" style="border: 1px solid black;text-align:justify;"&gt;80 AND ABOVE= A - EXCELLENT&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3" style="border: 1px solid black; text-align:center;"&gt;&lt;/td&gt; &lt;td colspan="3" style="border: 1px solid black;text-align:justify;"&gt;CA3 - ASSIGNMENT&lt;/td&gt; &lt;td colspan="5" style="border: 1px solid black;text-align:justify;"&gt;70 - 79 = B -VERY GOOD&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3" style="border: 1px solid black;"&gt;&lt;/td&gt; &lt;td colspan="3" style="border: 1px solid black;text-align:justify;"&gt;CA4 - CLASS EXERCISE&lt;/td&gt; &lt;td colspan="5" style="border: 1px solid black;text-align:justify;"&gt;60 - 69 = C - GOOD&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3" style="border: 1px solid black;"&gt;&lt;/td&gt; &lt;td colspan="3" style="border: 1px solid black;text-align:justify;"&gt;CA5 - AFFECTIVE&lt;/td&gt; &lt;td colspan="5" style="border: 1px solid black;text-align:justify;"&gt;50 - 59 = D - PASS&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3" style="border: 1px solid black;"&gt;&lt;/td&gt; &lt;td colspan="3" style="border: 1px solid black;text-align:justify;"&gt;CA6 - PSYCHOMOTOR&lt;/td&gt; &lt;td colspan="5" style="border: 1px solid black;text-align:justify;"&gt;00 - 49 = E - FAIR&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="9" style="border: 1px solid black;"&gt;&lt;color style="color:blue;"&gt; TEACHER'S REMARKS:&lt;/color&gt;&lt;b style="text-transform: uppercase;"&gt;&lt;/b&gt;&lt;/td&gt; &lt;td colspan="2" style="border: 1px solid black;"&gt;RESULT:&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="9" style="border: 1px solid black;"&gt;&lt;color style="color:blue;"&gt; PRINCIPAL'S REMARKS:&lt;/color&gt; &lt;b style="text-transform: uppercase;"&gt;&lt;/b&gt;&lt;/td&gt; &lt;td colspan="2" style="border: 1px solid black;"&gt;SIGN: &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt;</code></pre> </div> </div> </p> <p><a href="https://jsfiddle.net/missjargo/3p5ku1zh/41/" rel="nofollow noreferrer">https://jsfiddle.net/missjargo/3p5ku1zh/41/</a></p> <p>How can I force both the header and the table cell below to fit as one table?</p>
3
3,331
Are there better alternatives to g.drawString() / g2D.drawString()? (solved)
<p>I have been trying to put text onto an already existing window for a while now. I want to be able to add, remove, arrange and rearrange paragraphs across the screen.</p> <p>At first I tried to add text components - which had a delay of several seconds. Next I experimented with geometry in the paint component of JPanel-derivate, was delighted at how everything appeared instantly, and fell for a delusion that text would behave the same. But when I tried the drawString() method, I was met with a similar delay as before. Maybe this is a problem with my computer specifically and doesn't happen elsewhere. I would still like to remedy it though.</p> <p>Eventually I wrote this monstrosity:</p> <pre><code>import java.awt.geom.Area; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.QuadCurve2D; import java.awt.geom.CubicCurve2D; import java.awt.geom.AffineTransform; import java.awt.Toolkit; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Color; import java.awt.RenderingHints; import javax.swing.JFrame; import javax.swing.JPanel; class MainClass { public static void main(String[] args) { Schrift arabic = new Schrift(1368, 680, new Letter[] { new Letter('0', new int[][][] {{{361, 1385, 134, 1385, 52, 1145, 52, 915}, {52, 915, 52, 702, 134, 443, 361, 443}, {361, 443}, {363, 443, 588, 443, 669, 689, 669, 914}, {669, 914, 669, 1126, 588, 1385, 361, 1385}}}, new int [][][] {{{363, 1334, 236, 1334, 197, 1113, 197, 912}, {197, 912, 197, 710, 230, 494, 360, 494}, {360, 494}, {361, 494, 489, 494, 524, 707, 524, 912}, {524, 912, 524, 1116, 491, 1334, 363, 1334}}}, 722, new int[][] {}), new Letter('1', new int[][][] {{{580, 1368, 162, 1368}, {162, 1368, 162, 1326}, {162, 1326, 294, 1317, 303, 1302, 303, 1196}, {303, 1196, 303, 644}, {303, 644, 303, 568, 297, 561, 235, 557}, {235, 557, 157, 554}, {157, 554, 157, 519}, {157, 519, 225, 503, 347, 475, 437, 443}, {437, 443, 437, 1196}, {437, 1196, 437, 1302, 447, 1317, 580, 1326}, {580, 1326, 580, 1368}}}, new int[][][] {}, 722, new int[][] {}), new Letter('2', new int[][][] {{{612, 1368, 48, 1368}, {48, 1368, 48, 1333}, {48, 1333, 130, 1253, 216, 1171, 288, 1087}, {288, 1087, 380, 981, 472, 863, 472, 739}, {472, 739, 472, 619, 408, 548, 300, 548}, {300, 548, 198, 548, 135, 627, 95, 686}, {95, 686, 60, 654}, {60, 654, 149, 530}, {149, 530, 197, 481, 267, 443, 352, 443}, {352, 443, 488, 443, 607, 538, 607, 692}, {607, 692, 607, 817, 552, 900, 409, 1045}, {409, 1045, 204, 1251}, {204, 1251, 475, 1251}, {475, 1251, 558, 1251, 575, 1247, 622, 1152}, {622, 1152, 666, 1166}, {666, 1166, 645, 1233, 629, 1302, 612, 1368}}}, new int[][][] {}, 722, new int[][] {}), new Letter('3', new int[][][] {{{248, 1385, 178, 1385, 115, 1355, 93, 1334}, {93, 1334, 71, 1316, 66, 1298, 68, 1279}, {68, 1279, 70, 1260, 90, 1238, 105, 1228}, {105, 1228, 117, 1218, 130, 1218, 143, 1228}, {143, 1228, 179, 1260, 245, 1308, 331, 1308}, {331, 1308, 431, 1308, 503, 1233, 503, 1090}, {503, 1090, 503, 956, 399, 903, 316, 903}, {316, 903, 283, 903, 246, 911, 223, 918}, {223, 918, 214, 874}, {214, 874, 347, 832, 446, 777, 446, 672}, {446, 672, 446, 581, 383, 536, 306, 536}, {306, 536, 224, 536, 165, 596, 127, 653}, {127, 653, 95, 622}, {95, 622, 162, 528}, {162, 528, 204, 481, 272, 443, 354, 443}, {354, 443, 355, 443}, {355, 443, 492, 443, 580, 526, 580, 637}, {580, 637, 580, 678, 565, 710, 536, 739}, {536, 739, 511, 761, 476, 788, 434, 816}, {434, 816, 434, 819}, {434, 819, 567, 842, 642, 934, 641, 1042}, {641, 1042, 641, 1284, 345, 1385, 248, 1385}}}, new int[][][] {}, 722, new int[][] {}), new Letter('4', new int[][][] {{{673, 1368, 278, 1368}, {278, 1368, 278, 1327}, {278, 1327, 411, 1316, 417, 1304, 417, 1208}, {417, 1208, 417, 1110}, {417, 1110, 29, 1110}, {29, 1110, 29, 1064}, {29, 1064, 178, 851, 328, 643, 479, 447}, {479, 447, 546, 447}, {546, 447, 546, 1037}, {546, 1037, 689, 1037}, {689, 1037, 689, 1110}, {689, 1110, 546, 1110}, {546, 1110, 546, 1209}, {546, 1209, 546, 1307, 554, 1316, 673, 1327}, {673, 1327, 673, 1368}}}, new int[][][] {{{417, 1037, 125, 1037}, {125, 1037, 226, 876, 322, 737, 414, 616}, {414, 616, 417, 616}, {417, 616, 417, 1037}}}, 722, new int[][] {}), new Letter('5', new int[][][] {{{252, 1385, 185, 1385, 122, 1356, 98, 1334}, {98, 1334, 76, 1313, 68, 1301, 71, 1282}, {71, 1282, 71, 1266, 86, 1243, 105, 1228}, {105, 1228, 119, 1218, 131, 1218, 146, 1230}, {146, 1230, 179, 1259, 242, 1310, 335, 1310}, {335, 1310, 456, 1310, 514, 1206, 514, 1100}, {514, 1100, 514, 970, 433, 880, 274, 880}, {274, 880, 210, 880, 153, 898, 118, 909}, {118, 909, 178, 461}, {178, 461, 613, 461}, {613, 461, 622, 472}, {622, 472, 581, 577}, {581, 577, 227, 577}, {227, 577, 188, 839}, {188, 839, 249, 816, 322, 793, 361, 793}, {361, 793, 551, 793, 650, 918, 650, 1039}, {650, 1039, 650, 1128, 607, 1209, 514, 1284}, {514, 1284, 433, 1346, 332, 1385, 252, 1385}}}, new int[][][] {}, 722, new int[][] {}), new Letter('6', new int[][][] {{{366, 1385, 188, 1385, 52, 1244, 52, 1020}, {52, 1020, 52, 701, 281, 536, 441, 481}, {441, 481, 501, 461, 580, 443, 638, 434}, {638, 434, 648, 482}, {648, 482, 600, 491, 540, 509, 487, 533}, {487, 533, 398, 574, 259, 666, 214, 867}, {214, 867, 313, 819}, {313, 819, 347, 804, 376, 794, 405, 794}, {405, 794, 568, 794, 677, 912, 677, 1064}, {677, 1064, 677, 1238, 546, 1385, 366, 1385}}}, new int[][][] {{{390, 1333, 274, 1333, 198, 1193, 198, 1017}, {198, 1017, 198, 983, 200, 943, 207, 916}, {207, 916, 242, 899, 288, 880, 342, 880}, {342, 880, 344, 880}, {344, 880, 473, 880, 539, 995, 539, 1117}, {539, 1117, 539, 1212, 503, 1333, 390, 1333}}}, 722, new int[][] {}), new Letter('7', new int[][][] {{{264, 1369, 146, 1385}, {146, 1385, 135, 1368}, {135, 1368, 296, 1123, 463, 823, 583, 577}, {583, 577, 259, 577}, {259, 577, 160, 577, 150, 590, 112, 686}, {112, 686, 68, 686}, {68, 686, 83, 597, 90, 523, 98, 461}, {98, 461, 677, 461}, {677, 461, 689, 478}, {689, 478, 548, 774, 406, 1069, 264, 1369}}}, new int[][][] {}, 722, new int[][] {}), new Letter('8', new int[][][] {{{357, 1385, 191, 1385, 66, 1294, 66, 1139}, {66, 1139, 66, 1072, 101, 1032, 133, 1002}, {133, 1002, 157, 979, 214, 941, 264, 912}, {264, 912, 169, 860, 102, 788, 102, 685}, {102, 685, 102, 560, 211, 443, 374, 443}, {374, 443, 376, 443}, {376, 443, 519, 443, 622, 541, 622, 660}, {622, 660, 622, 702, 607, 745, 578, 777}, {578, 777, 565, 791, 527, 823, 463, 865}, {463, 865, 568, 924, 660, 992, 660, 1120}, {660, 1120, 660, 1292, 488, 1385, 357, 1385}}}, new int[][][] {{{374, 1336, 373, 1336}, {373, 1336, 283, 1336, 194, 1265, 194, 1129}, {194, 1129, 194, 1049, 242, 978, 309, 935}, {309, 935, 430, 995, 530, 1053, 530, 1161}, {530, 1161, 530, 1270, 460, 1336, 374, 1336}}, {{418, 844, 310, 791, 224, 745, 224, 638}, {224, 638, 224, 565, 274, 493, 357, 493}, {357, 493, 358, 493}, {358, 493, 425, 493, 504, 544, 504, 669}, {504, 669, 504, 755, 465, 807, 418, 844}}}, 722, new int[][] {}), new Letter('9', new int[][][] {{{93, 1391, 84, 1346}, {84, 1346, 300, 1311, 462, 1161, 510, 948}, {510, 948, 414, 999}, {414, 999, 380, 1017, 352, 1023, 325, 1023}, {325, 1023, 163, 1023, 54, 908, 54, 755}, {54, 755, 54, 615, 168, 443, 364, 443}, {364, 443, 366, 443}, {366, 443, 556, 443, 666, 611, 666, 809}, {666, 809, 666, 1078, 511, 1265, 310, 1345}, {310, 1345, 233, 1374, 135, 1390, 93, 1391}}}, new int[][][] {{{390, 937, 267, 937, 192, 828, 192, 702}, {192, 702, 192, 615, 235, 494, 342, 494}, {342, 494, 344, 494}, {344, 494, 484, 494, 521, 669, 521, 801}, {521, 801, 521, 831, 520, 865, 516, 899}, {516, 899, 487, 919, 440, 937, 390, 937}}}, 722, new int[][] {}), new Letter(' ', new int[][][] {}, new int[][][] {}, 400, new int[][] {})}); JFrame frame = new JFrame(); PaintPanel canvas = new PaintPanel(); canvas.setBackground(Color.WHITE); frame.setSize(Toolkit.getDefaultToolkit().getScreenSize()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(canvas); frame.setBackground(Color.WHITE); frame.setVisible(true); canvas.painting = new Area[] {arabic.print(&quot; 0123456789&quot;,73.).ink}; canvas.colours = new Color[] {Color.BLACK}; canvas.freshup(); } } class PaintPanel extends JPanel { Area[] painting = new Area[] {}; Color[] colours = new Color[] {}; public void paint(Graphics g) { Graphics2D g2D = (Graphics2D)g; g2D.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON)); int jobs = painting.length; int task = 0; while (task &lt; jobs) { g2D.setColor(colours[task]); g2D.fill(painting[task]); task ++; } } public void freshup() {this.repaint();} } class Schrift { int ascent = 0; int descent = 0; Letter[] symbols = null; Schrift(int chosenAscent, int chosenDescent, Letter[] chosenSymbols) { ascent = chosenAscent; descent = chosenDescent; int cells = 0; int sample = 0; int fullset = chosenSymbols.length; while (sample &lt; fullset) { int id = (int)(chosenSymbols[sample].name); if (id &gt; cells) {cells = id;} sample ++; } cells ++; symbols = new Letter[cells]; sample = 0; while (sample &lt; fullset) { symbols[(int)(chosenSymbols[sample].name)] = chosenSymbols[sample]; sample ++; } } Double measure(String line, Double size) { Double dimension = 0.; int letters = line.length(); int beispiel = (int)(line.charAt(0)); int num = 1; while (num &lt;= letters) { if (beispiel &lt; symbols.length) { Letter zeichen = symbols[beispiel]; if (zeichen != null) {dimension += Double.valueOf(zeichen.width);} if (num &lt; letters) { beispiel = (int)(line.charAt(num)); if (zeichen != null &amp;&amp; beispiel &lt; zeichen.kerning.length) {dimension += Double.valueOf(zeichen.kerning[beispiel]);} } } num ++; } dimension *= (size / (ascent + descent)); return dimension; } Schnipsel print(String line, Double size) { Area ink = new Area(); Double dimension = 0.; AffineTransform placing = new AffineTransform(); int letters = line.length(); int beispiel = (int)(line.charAt(0)); int num = 1; while (num &lt;= letters) { if (beispiel &lt; symbols.length) { Letter zeichen = symbols[beispiel]; if (zeichen != null) { ink.add(new Area(placing.createTransformedShape(zeichen.form))); dimension += Double.valueOf(zeichen.width); placing.translate(zeichen.width, 0); } if (num &lt; letters) { beispiel = (int)(line.charAt(num)); if (zeichen != null &amp;&amp; beispiel &lt; zeichen.kerning.length) { Double kern = Double.valueOf(zeichen.kerning[beispiel]); dimension += kern; placing.translate(kern, 0); } } } num ++; } AffineTransform shrink = new AffineTransform(); Double scale = (size / (ascent + descent)); shrink.scale(scale, scale); return new Schnipsel(ascent/scale, descent/scale, dimension/scale, new Area(shrink.createTransformedShape(ink))); } } class Letter { char name = ' '; Area form = null; int width = 0; int[] kerning = null; Letter(char chosenName, int[][][] outlines, int[][][] clearings, int chosenWidth, int[][] kerningChoice) { name = chosenName; form = new Area(); AutoPath painter = new AutoPath(); int toAdd = outlines.length; int spot = 0; while (spot &lt; toAdd) { form.add(new Area(painter.trace(outlines[spot]))); spot ++; } int toRemove = clearings.length; spot = 0; while (spot &lt; toRemove) { form.subtract(new Area(painter.trace(clearings[spot]))); spot ++; } width = chosenWidth; int partners = 0; int zeichen = 0; int fullset = kerningChoice.length; while (zeichen &lt; fullset) { if (kerningChoice[zeichen][0] &gt; partners) {partners = kerningChoice[zeichen][0];} zeichen ++; } partners ++; kerning = new int[partners]; zeichen = 0; while (zeichen &lt; fullset) { kerning[kerningChoice[zeichen][0]] = kerningChoice[zeichen][1]; zeichen ++; } } } class Schnipsel { Double ascent = null; Double descent = null; Double width = null; Area ink = null; Schnipsel(Double chosenAscent, Double chosenDescent, Double widthFound, Area shapes) { ascent = chosenAscent; descent = chosenDescent; width = widthFound; ink = shapes; } } class AutoPath { GeneralPath trace(int[][] line) { GeneralPath form = new GeneralPath(); int arcs = line.length; int step = 0; while (step &lt; arcs) { int points = line[step].length / 2; if (points == 2) {form.append(new Line2D.Float( line[step][0],line[step][1] , line[step][2],line[step][3]),true);} else if (points == 3) {form.append(new QuadCurve2D.Float( line[step][0],line[step][1] , line[step][2],line[step][3] , line[step][4],line[step][5]),true);} else if (points == 4) {form.append(new CubicCurve2D.Float( line[step][0],line[step][1] , line[step][2],line[step][3] , line[step][4],line[step][5] , line[step][6],line[step][7]),true);} step ++; } int end = arcs - 1; int last = line[end].length - 1; if (line[0][0] == line[end][last-1] &amp;&amp; line[0][1] == line[end][last]) {form.closePath();} return form; } } </code></pre> <p>… which works fine, but has the problem that I will need to transcribe all the geometric information from any font that I would want to use - thus I am not quite sure if I should keep building on it or if that would just be a waste of time.</p> <p>Update: Under a different Question I found the info that drawString() only needs a few seconds to load the font you are using when you draw your very first words. After that it apparently works (for practical purposes) instantly - I don't know why I never thought to check what would happen with the seconds line of text that I would ask the computer to draw.</p>
3
7,338
Procedure entry point gzdirect could not be located in the dynamic link library
<p>I tried to run the below command</p> <blockquote> <p>conda create --name tf_gpu tensorflow-gpu</p> </blockquote> <p>and it throws the error</p> <blockquote> <p>Traceback (most recent call last): File "C:\Users\alexk\Anaconda3\lib\site-packages\conda\exceptions.py", line 1062, in <strong>call</strong> <br>return func(*args, **kwargs)<br> File "C:\Users\alexk\Anaconda3\lib\site-packages\conda\cli\main.py", line 84, in _main <br> exit_code = do_call(args, p)<br> File "C:\Users\alexk\Anaconda3\lib\site-packages\conda\cli\conda_argparse.py", line 82, in do_call <br> exit_code = getattr(module, func_name)(args, parser)<br> File "C:\Users\alexk\Anaconda3\lib\site-packages\conda\cli\main_create.py", line 37, in execute <br> install(args, parser, 'create')<br> File "C:\Users\alexk\Anaconda3\lib\site-packages\conda\cli\install.py", line 116, in install <br> if context.use_only_tar_bz2:<br> File "C:\Users\alexk\Anaconda3\lib\site-packages\conda\base\context.py", line 664, in use_only_tar_bz2 <br> import conda_package_handling.api<br> File "C:\Users\alexk\Anaconda3\lib\site-packages\conda_package_handling\api.py", line 12, in <br> from .tarball import CondaTarBZ2 as _CondaTarBZ2, <br>libarchive_enabled File "C:\Users\alexk\Anaconda3\lib\site-packages\conda_package_handling\tarball.py", line 11, in <br> import libarchive<br> File "C:\Users\alexk\Anaconda3\lib\site-packages\libarchive__init__.py", line 1, in <br> from .entry import ArchiveEntry<br> File "C:\Users\alexk\Anaconda3\lib\site-packages\libarchive\entry.py", line 6, in <br> from . import ffi<br> File "C:\Users\alexk\Anaconda3\lib\site-packages\libarchive\ffi.py", line 27, in <br> libarchive = ctypes.cdll.LoadLibrary(libarchive_path)<br> File "C:\Users\alexk\Anaconda3\lib\ctypes__init__.py", line 434, in LoadLibrary <br> return self._dlltype(name)<br> File "C:\Users\alexk\Anaconda3\lib\ctypes__init__.py", line 356, in <strong>init</strong> <br> self._handle = _dlopen(self._name, mode)<br> OSError: [WinError 127] The specified procedure could not be found</p> </blockquote> <p>and also a error window pops up saying:</p> <blockquote> <p>The procedure entry point gzdirect could not be located in the dynamic link library C:\User\\Anaconda3\Library\bin\libxml2.dll</p> </blockquote>
3
1,117
Making a Leaderboard in R Shiny
<p>I am attempting to make a leaderboard in R Shiny for my school where users could submit their name, teacher's name, and their score in textInputs by clicking an actionButton. I am having trouble with the following:</p> <p>a) Making the textInputs submit on the push of the actionButton (I know I should use the isolate function, but have no idea where/when/how)</p> <p>b) Storing the info the user inputs with the data frame so that when the app opens on a second device it still shows the info the first person uses</p> <p>My code is below:</p> <pre><code>### Libraries library('tidyverse') library('readxl') library('shiny') library('DT') # Define UI ui &lt;- fluidPage( # Application title titlePanel(&quot;Scoreboard&quot;), # Sidebar sidebarLayout( sidebarPanel( h5(&quot;Sidebar Text&quot;), ), # Main Panel mainPanel( tabsetPanel(type = &quot;tabs&quot;, tabPanel(&quot;Add Score&quot;, textInput(&quot;name_input&quot;, &quot;Insert Your Name Below&quot;), textInput(&quot;teacher_input&quot;, &quot;Insert Your Teacher's Last Name Below&quot;), textInput(&quot;score_input&quot;, &quot;Insert Your Score Below&quot;), actionButton(&quot;sumbit_button&quot;, &quot;Click Button to Submit!&quot;) ), tabPanel(&quot;ScoreBoard&quot;, dataTableOutput(&quot;score_table&quot;)) ) ) ) ) # Define server logic server &lt;- function(input, output) { # Read In Sample Scores as a base dataframe to add user inputs to. scores &lt;- read_excel(&quot;Sample_Scores.xlsx&quot;) scores &lt;- scores[order(scores$Scores, decreasing = FALSE),] names(scores) &lt;- c(&quot;Score&quot;, &quot;Name&quot;, &quot;Teacher&quot;) output$score_table &lt;- renderDataTable({ new_score &lt;- input$score_input new_name &lt;- input$name_input new_teacher &lt;- input$teacher_input new_student &lt;- c(new_score, new_name, new_teacher) scores &lt;- rbind(scores, new_student) }) } # Run the application shinyApp(ui = ui, server = server) </code></pre>
3
1,097
Database row is not deleting, AJAX, PHP error
<p>I want to remove DB row data from HTML table. I have an HTML table where I have called all the database table values. I want to give a delete order option to the user. I have used a delete button for that. To do this, I am trying to use ajax and jquery with php delete query. But the issue is When I click on delete it just deletes the HTML row data. It should delete that particular id row from DB as well. I need your help. Please let me know what I have done wrong? I am very much new to ajax and jquery.</p> <p>remove.php</p> <pre><code>&lt;?php include "config.php"; $id = $_REQUEST['id']; // Delete record $query = "DELETE FROM mi_home_tv WHERE id='$id'"; mysqli_query($link,$query); echo 1; jquery+ajax code &lt;script src='jquery-3.0.0.js' type='text/javascript'&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function(){ // Delete $('.delete').click(function(){ var el = this; var id = this.id; var splitid = id.split("_"); // Delete id var deleteid = splitid[1]; // AJAX Request $.ajax({ url: 'remove.php', type: 'POST', data: { id:deleteid }, success: function(response){ // Removing row from HTML Table $(el).closest('tr').css('background','tomato'); $(el).closest('tr').fadeOut(800, function(){ $(this).remove(); }); } }); }); }); &lt;/script&gt; </code></pre> <p>Button Code:</p> <pre><code>echo "&lt;td&gt; &lt;span id='del_&lt;?php echo $id; ?&gt;' type='submit' class=' delete btn c-theme-btn c-btn-uppercase btn-xs c-btn-square c-font-sm'&gt;Delete&lt;/span&gt; &lt;/td&gt;"; </code></pre> <p>php code:</p> <pre><code> &lt;form method="post" action="remove.php"&gt; &lt;?php echo " &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Order ID&lt;/th&gt; &lt;th&gt;Date&lt;/th&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Store Name&lt;/th&gt; &lt;th&gt;Zip&lt;/th&gt; &lt;th&gt;City&lt;/th&gt; &lt;th&gt;Address&lt;/th&gt; &lt;th&gt;Contact&lt;/th&gt; &lt;th&gt;Tv Varient&lt;/th&gt; &lt;th&gt;Total&lt;/th&gt; &lt;th&gt;Delivery&lt;/th&gt; &lt;th&gt;Action&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt;"; while($row = mysqli_fetch_array($result)) { $id = $row['id']; echo"&lt;tr&gt;"; echo "&lt;td&gt;" . $row['id'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['rdate'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['rname'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['rstore'] . "&lt;/td&gt;"; echo " &lt;td&gt;" . $row['rzip'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['rcity'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['raddress'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['rphone'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['rtv_varient'] . "&lt;/td&gt;"; echo"&lt;td&gt;" . $row['ramount'] . "&lt;/td&gt;"; echo"&lt;td&gt;" . $row['rdelivery'] . "&lt;/td&gt;"; echo "&lt;td&gt; &lt;input type='submit' value='delete' id='del_&lt;?php echo $id; ?&gt;' type='submit' class=' delete btn c-theme-btn c-btn-uppercase btn-xs c-btn-square c-font-sm'&gt;Delete&lt;/button&gt; &lt;/td&gt;"; echo"&lt;/tr&gt;"; } ?&gt; &lt;/form&gt; </code></pre>
3
3,312
Convert C# Array type web builder to F#
<p>I am new to F# and trying to convert the following Service Fabric Asp.Net core code from C# into F# and failing terribly. Can anyone help?</p> <pre><code>protected override IEnumerable&lt;ServiceInstanceListener&gt; CreateServiceInstanceListeners() { return new[] { new ServiceInstanceListener(serviceContext =&gt; new KestrelCommunicationListener(serviceContext, "ServiceEndpoint", (url, listener) =&gt; { ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting Kestrel on {url}"); return Microsoft.AspNetCore.WebHost.CreateDefaultBuilder() .ConfigureAppConfiguration((builderContext, config) =&gt; { config.SetBasePath(builderContext.HostingEnvironment.ContentRootPath); config.AddJsonFile("appsettings.json", false); config.AddJsonFile($"appsettings.{builderContext.HostingEnvironment.EnvironmentName}.json", true); config.AddJsonFile("PackageRoot/Config/eventFlowConfig.json", optional: true, reloadOnChange: true); config.AddEnvironmentVariables(); }) .ConfigureServices( services =&gt; { services.AddSingleton&lt;StatelessServiceContext&gt;(serviceContext); }) .UseStartup&lt;Startup&gt;() .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None) .UseUrls(url) .Build(); })) }; } </code></pre> <p>F#</p> <pre><code>module Service open Microsoft.ServiceFabric.Services.Runtime open Microsoft.ServiceFabric.Services.Communication.Runtime open Microsoft.ServiceFabric.Services.Communication.AspNetCore open Microsoft.AspNetCore.Hosting type Service(context) = inherit StatelessService(context) let builder = (fun url listener -&gt; Microsoft.AspNetCore.WebHost.CreateDefaultBuilder().UseUrls(url).Build()) let kestrelCommunicationListener ctx builder = new KestrelCommunicationListener(ctx, "ServiceEndPoint", builder) let serviceInstanceListener context () = new ServiceInstanceListener(context kestrelCommunicationListener); override __.CreateServiceInstanceListeners() = seq { yield serviceInstanceListener(fun context -&gt; kestrelCommunicationListener builder) } </code></pre>
3
1,343
Images is not shown in my Full screen Activity from my json response..? while swiping also
<p><strong>How to swipe my full screen images from gridview...and that images should Loading from JSON response...?</strong></p> <p>i'm new to android...please help me friends...</p> <p>But i want to use only <strong>One url</strong> in my program(<strong>JSON URL</strong>)...from that i need <strong>Gridview--->FullScreenImage(zooming and swiping)</strong></p> <p>This is my gridView Activity...</p> <pre><code>package com.example.admin.loadingimagefromwebgridandswipe; import android.app.Activity; import android.app.ProgressDialog; import android.content.res.Resources; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.util.TypedValue; import android.widget.GridView; import android.widget.ListView; import com.example.admin.adapter.GridViewImageAdapter; import com.example.admin.helper.AppConstant; import com.example.admin.helper.JSONfunctions; import com.example.admin.helper.Utils; import com.example.admin.ndimageslider.R; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; public class GridViewActivity extends Activity { private Utils utils; private ArrayList&lt;String&gt; imagePaths = new ArrayList&lt;String&gt;(); private GridViewImageAdapter adapter; private GridView gridView; private int columnWidth; JSONObject jsonobject; JSONArray jsonarray; ProgressDialog mProgressDialog; // ArrayList&lt;HashMap&lt;String, String&gt;&gt; imagePaths; static String RANK = "rank"; static String COUNTRY = "country"; static String POPULATION = "population"; static String FLAG = "flag"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_grid_view); gridView = (GridView) findViewById(R.id.grid_view); utils = new Utils(this); // Initilizing Grid View InitilizeGridLayout(); new DownloadJSON().execute(); } private void InitilizeGridLayout() { Resources r = getResources(); float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, AppConstant.GRID_PADDING, r.getDisplayMetrics()); columnWidth = (int) ((utils.getScreenWidth() - ((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS); gridView.setNumColumns(AppConstant.NUM_OF_COLUMNS); gridView.setColumnWidth(columnWidth); gridView.setStretchMode(GridView.NO_STRETCH); gridView.setPadding((int) padding, (int) padding, (int) padding, (int) padding); gridView.setHorizontalSpacing((int) padding); gridView.setVerticalSpacing((int) padding); } private class DownloadJSON extends AsyncTask&lt;Void, Void, Void&gt; { @Override protected void onPreExecute() { super.onPreExecute(); // Create a progressdialog mProgressDialog = new ProgressDialog(GridViewActivity.this); // Set progressdialog title mProgressDialog.setTitle("Android JSON Parse Tutorial"); // Set progressdialog message mProgressDialog.setMessage("Loading..."); mProgressDialog.setIndeterminate(false); // Show progressdialog mProgressDialog.show(); } @Override protected Void doInBackground(Void... params) { // Create an array imagePaths = new ArrayList&lt;&gt;(); // Retrieve JSON Objects from the given URL address jsonobject = JSONfunctions .getJSONfromURL("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors"); try { // Locate the array name in JSON jsonarray = jsonobject.getJSONArray("actors"); for (int i = 0; i &lt; jsonarray.length(); i++) { HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); jsonobject = jsonarray.getJSONObject(i); // Retrive JSON Objects imagePaths.add( jsonobject.getString("name")); imagePaths.add(jsonobject.getString("country")); imagePaths.add( jsonobject.getString("spouse")); imagePaths.add(jsonobject.getString("image")); // Set the JSON Objects into the array // imagePaths.add(map); } } catch (JSONException e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void args) { // Locate the listview in listview_main.xml gridView = (GridView) findViewById(R.id.grid_view); // Pass the results into ListViewAdapter.java adapter = new GridViewImageAdapter(GridViewActivity.this, imagePaths,columnWidth); // Set the adapter to the ListView gridView.setAdapter(adapter); // Close the progressdialog mProgressDialog.dismiss(); } } } </code></pre> <p>this is my Gridview Adapter...</p> <pre><code> package com.example.admin.adapter; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.Toast; import com.example.admin.loadingimagefromwebgridandswipe.FullScreenViewActivity; import com.squareup.picasso.Picasso; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; public class GridViewImageAdapter extends BaseAdapter { private Activity activity; private ArrayList&lt;String&gt; filePaths = new ArrayList&lt;String&gt;(); private int imageWidth; public GridViewImageAdapter(Activity activity, ArrayList&lt;String&gt; filePaths, int imageWidth) { this.activity = activity; this.filePaths = filePaths; this.imageWidth = imageWidth; } @Override public int getCount() { return this.filePaths.size(); } @Override public Object getItem(int position) { return this.filePaths.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { imageView = new ImageView(activity); } else { imageView = (ImageView) convertView; } String designationUrl = filePaths.get(position); // Log.d("designationUrl",""+designationUrl); // URL url = null; // try { // url = new URL(designationUrl); // } catch (MalformedURLException e) { // e.printStackTrace(); // } // Bitmap bmp = null; // try { // bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream()); // } catch (IOException e) { // e.printStackTrace(); // } Picasso.with(activity) .load(designationUrl) .resize(imageWidth, imageWidth).into(imageView); // image view click listener imageView.setOnClickListener(new OnImageClickListener(position)); //Toast.makeText(GridViewImageAdapter.this,"url: "+designationUrl,Toast.LENGTH_LONG).show(); return imageView; } class OnImageClickListener implements OnClickListener { int _postion; // constructor public OnImageClickListener(int position) { this._postion = position; } @Override public void onClick(View v) { // on selecting grid view image // launch full screen activity // Toast.makeText(GridViewImageAdapter.this,"url: "+,Toast.LENGTH_LONG).show(); Intent i = new Intent(activity, FullScreenViewActivity.class); i.putExtra("position", _postion); activity.startActivity(i); } } /* * Resizing image size */ public static Bitmap decodeFile(String filePath, int WIDTH, int HIGHT) { try { File f = new File(filePath); BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeStream(new FileInputStream(f), null, o); final int REQUIRED_WIDTH = WIDTH; final int REQUIRED_HIGHT = HIGHT; int scale = 1; while (o.outWidth / scale / 2 &gt;= REQUIRED_WIDTH &amp;&amp; o.outHeight / scale / 2 &gt;= REQUIRED_HIGHT) scale *= 2; BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; return BitmapFactory.decodeStream(new FileInputStream(f), null, o2); } catch (FileNotFoundException e) { e.printStackTrace(); } return null; } } </code></pre> <p>Fullscreen imageViewActivity....</p> <pre><code> package com.example.admin.loadingimagefromwebgridandswipe; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.widget.ImageView; import com.example.admin.Application; import com.example.admin.adapter.FullScreenImageAdapter; import com.example.admin.helper.JSONfunctions; import com.example.admin.helper.Utils; import com.example.admin.ndimageslider.R; public class FullScreenViewActivity extends Activity{ private Utils utils; private FullScreenImageAdapter adapter; private ViewPager viewPager; private ImageView flag; private ImageView image; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fullscreen_view); viewPager = (ViewPager) findViewById(R.id.pager); utils = new Utils(getApplicationContext()); //flag=(ImageView)findViewById(R.id.flag); image=(ImageView)findViewById(R.id.image); Intent i = getIntent(); int position = i.getIntExtra("position", 0); adapter = new FullScreenImageAdapter(FullScreenViewActivity.this, Application.url()); viewPager.setAdapter(adapter); // displaying selected image first viewPager.setCurrentItem(position); } } </code></pre> <p>FullScreenImageAdapter:</p> <pre><code> package com.example.admin.adapter; import android.app.Activity; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.RelativeLayout; import com.example.admin.helper.TouchImageView; import com.example.admin.ndimageslider.R; import com.squareup.picasso.Picasso; import org.json.JSONObject; import java.util.ArrayList; public class FullScreenImageAdapter extends PagerAdapter { private Activity activity; private ArrayList&lt;String&gt; imagePaths; private LayoutInflater inflater; // constructor public FullScreenImageAdapter(Activity activity, ArrayList&lt;String&gt; imagePaths) { this.activity = activity; this.imagePaths = imagePaths; } @Override public int getCount() { return this.imagePaths.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view == ((RelativeLayout) object); } @Override public Object instantiateItem(ViewGroup container, int position) { TouchImageView imgDisplay; Button btnClose; inflater = (LayoutInflater) activity .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View viewLayout = inflater.inflate(R.layout.layout_fullscreen_image, container, false); imgDisplay = (TouchImageView) viewLayout.findViewById(R.id.imgDisplay); btnClose = (Button) viewLayout.findViewById(R.id.btnClose); // BitmapFactory.Options options = new BitmapFactory.Options(); // options.inPreferredConfig = Bitmap.Config.ARGB_8888; // Bitmap bitmap = BitmapFactory.decodeFile(_imagePaths.get(position), options); // imgDisplay.setImageBitmap(bitmap); Picasso.with(activity) .load(imagePaths.get(position)).into(imgDisplay); // close button click event btnClose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { activity.finish(); } }); ((ViewPager) container).addView(viewLayout,0); return viewLayout; } @Override public void destroyItem(ViewGroup container, int position, Object object) { ((ViewPager) container).removeView((RelativeLayout) object); } } </code></pre> <p>Application:</p> <pre><code> package com.example.admin; import android.widget.Toast; import com.example.admin.helper.FileCache; import java.util.ArrayList; public class Application extends android.app.Application { public static ArrayList&lt;String&gt; url(){ ArrayList&lt;String&gt; filePaths = new ArrayList&lt;String&gt;(); filePaths.add("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors"); return filePaths; } } </code></pre> <p>JSONfunctions:</p> <pre><code>package com.example.admin.helper; /** * Created by Admin on 14-03-2016. */ import android.util.Log; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; public class JSONfunctions { public static JSONObject getJSONfromURL(String url) { InputStream is = null; String result = ""; JSONObject jArray = null; // Download JSON data from URL try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } // Convert response to string try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { jArray = new JSONObject(result); } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } return jArray; } } </code></pre>
3
6,543
R FlexDashboard ggiraph chart not showing on second page of dashboard when using IE 11
<p>I have a multi-page R FlexdashBoard and I am trying to use ggiraph to create some interactive charts. They show up fine on the first page of the dashboard, however on the second page the SVG graphics do not show up until I hit refresh then the charts on the first page disappear. Also the text in the SVG graphics seems to only display intermittently. I only have this error in Internet Explorer - everything works fine in Chrome. The following code should recreate this error.</p> <p>Any help would be greatly appreciated event a hint on which package or piece of java script to look at.</p> <pre><code>--- title: "Please Help Me!" output: flexdashboard::flex_dashboard: orientation: columns vertical_layout: fill --- ```{r setup, include=FALSE} library(flexdashboard) library(ggplot2) library(ggiraph) ``` Works {data-orientation=rows} ===================================== Column {data-width=650} ----------------------------------------------------------------------- ### Chart A ```{r} myIris &lt;- iris myIris$DataId&lt;- row.names(iris) g2 &lt;- ggplot(data=myIris, aes(x=Sepal.Length, y=Sepal.Width, data_id=DataId)) + geom_point_interactive(fill = "green", alpha=.5) ggiraph(code = print(g2), width_svg = 8, height_svg=4, hover_css="fill-opacity:1",flexdashboard =TRUE) ``` Column {data-width=350} ----------------------------------------------------------------------- ### Chart B ```{r} myIris &lt;- iris myIris$DataId&lt;- row.names(iris) g2 &lt;- ggplot(data=myIris, aes(x=Sepal.Length, y=Sepal.Width, data_id=DataId)) + geom_point_interactive(fill = "green", alpha=.5) ggiraph(code = print(g2), width_svg = 8, height_svg=4, hover_css="fill-opacity:1",flexdashboard =TRUE) ``` ### Chart C ```{r} myIris &lt;- iris myIris$DataId&lt;- row.names(iris) g2 &lt;- ggplot(data=myIris, aes(x=Sepal.Length, y=Sepal.Width, data_id=DataId)) + geom_point_interactive(fill = "green", alpha=.5) ggiraph(code = print(g2), width_svg = 8, height_svg=4, hover_css="fill-opacity:1",flexdashboard =TRUE) ``` Does Not Work {data-orientation=rows} ===================================== ### Chart C ```{r} myIris &lt;- iris myIris$DataId&lt;- row.names(iris) g2 &lt;- ggplot(data=myIris, aes(x=Sepal.Length, y=Sepal.Width, data_id=DataId)) + geom_point_interactive(fill = "green", alpha=.5) ggiraph(code = print(g2), width_svg = 8, height_svg=4, hover_css="fill-opacity:1",flexdashboard =TRUE) ``` ### Chart D ```{r} myIris &lt;- iris myIris$DataId&lt;- row.names(iris) g2 &lt;- ggplot(data=myIris, aes(x=Sepal.Length, y=Sepal.Width, data_id=DataId)) + geom_point_interactive(fill = "green", alpha=.5) ggiraph(code = print(g2), width_svg = 8, height_svg=4, hover_css="fill-opacity:1",flexdashboard =TRUE) ``` ### Chart E ```{r} myIris &lt;- iris myIris$DataId&lt;- row.names(iris) g2 &lt;- ggplot(data=myIris, aes(x=Sepal.Length, y=Sepal.Width, data_id=DataId)) + geom_point_interactive(fill = "green", alpha=.5) ggiraph(code = print(g2), width_svg = 8, height_svg=4, hover_css="fill-opacity:1",flexdashboard =TRUE) ``` </code></pre>
3
1,238
Deserialize XML to list of lists
<p>Given the following code used to serialize:</p> <pre><code>[XmlRoot(Namespace = "", IsNullable = true, ElementName = "ReportSpec")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] public partial class ReportSpec{ [System.Xml.Serialization.XmlElementAttribute("Reports")] public ReportsHolder MyHolder { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()] public decimal Version { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()] public string Username { get; set; } } public partial class ReportsHolder{ [System.Xml.Serialization.XmlElement(IsNullable = true)] public List&lt;AlertsReport&gt; AlertsReportList { get; set; } [System.Xml.Serialization.XmlElement(IsNullable = true)] public List&lt;DeviceHistoryReport&gt; DeviceHistoryReportList { get; set; } public ReportsHolder(){ this.AlertsReportList = new List&lt;AlertsReport&gt;(); this.DeviceHistoryReport = new List&lt;DeviceHistoryReport&gt;(); } } public abstract class BaseReport{ [System.Xml.Serialization.XmlAttributeAttribute()] public string ReportName { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()] public string FilterMode { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()] public string Destination { get; set; } [System.Xml.Serialization.XmlAttributeAttribute()] public string Format { get; set; } } [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] public partial class AlertsReport : BaseReport{ public AlertsReportFilters Filters { get; set; } public AlertsReport(){ Filters = new AlertsReportFilters(); } } [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] public partial class AlertsReportFilters{ public string AlertSource { get; set; } public byte? Scope { get; set; } public bool ShouldSerializeScope(){ return Scope != null; } public ushort? DeviceID { get; set; } public bool ShouldSerializeDeviceID(){ return DeviceID != null; } public string DeviceType { get; set; } public byte? DeviceGroup { get; set; } public bool ShouldSerializeDeviceGroup(){ return DeviceGroup != null; } public uint? DeviceFacility { get; set; } public bool ShouldSerializeDeviceFacility(){ return DeviceFacility != null; } public uint? DeviceRegion { get; set; } public bool ShouldSerializeDeviceRegion(){ return DeviceRegion != null; } } [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] public partial class DeviceHistoryReport : BaseReport{ public ushort? DeviceID { get; set; } public bool ShouldSerializeDeviceID(){ return DeviceID != null; } } </code></pre> <p>Which ends up serializing like this:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;ReportSpec Version="4.5" Username="My Name"&gt; &lt;Reports&gt; &lt;AlertsReportList FilterMode="Container" Destination="someone@somewhere.com" Format="PDF"&gt; &lt;Filters&gt; &lt;AlertSource&gt;Frankenstein&lt;/AlertSource&gt; &lt;Scope&gt;0&lt;/Scope&gt; &lt;/Filters&gt; &lt;/AlertsReportList&gt; &lt;AlertsReportList FilterMode="Container" Destination="someone.else@somewhere.com" Format="XLS"&gt; &lt;Filters&gt; &lt;DeviceGroup&gt;12&lt;/DeviceGroup&gt; &lt;/Filters&gt; &lt;/AlertsReportList&gt; &lt;DeviceHistoryReportList FilterMode="Container" Destination="\\path\on\my\network" Format="DOC"&gt; &lt;Filters&gt; &lt;DeviceID&gt;255&lt;/DeviceID&gt; &lt;/Filters&gt; &lt;/DeviceHistoryReportList&gt; &lt;DeviceHistoryReportList FilterMode="Container" Destination="mr.executive@somewhere.com" Format="TXT"&gt; &lt;Filters&gt; &lt;DeviceID&gt;44&lt;/DeviceID&gt; &lt;/Filters&gt; &lt;/DeviceHistoryReportList&gt; &lt;/Reports&gt; &lt;/ReportSpec&gt; </code></pre> <p>I am wanting to get a list of each ReportList object to process later in my application, but I am getting a "Type 'ReportSpec' is not enumerable" error in my foreach loop:</p> <pre><code>var streamReader = new StreamReader(@"C:\temp\TestFile.xml"); TextReader reader = streamReader; var xmlSerializer = new XmlSerializer(typeof(ReportSpec)); var list = (ReportSpec)xmlSerializer.Deserialize(reader); foreach (var report in list){ // &lt;-- error is here //re-direct the report (AlertsReportList, DeviceHistoryReportList) for processing } </code></pre> <p>Is what I want even possible, and if so, where am I screwing up?</p>
3
1,703
How to Remove TextView BackGround from listview if value is null?
<p>I am making simple offline chat app, till now every thing is working fine but i want to remove the background of textview if value is null. Chat is having simple left right combination.</p> <p><a href="https://i.stack.imgur.com/2n6jg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2n6jg.png" alt="enter image description here"></a></p> <pre><code> protected void showList(){ try { JSONObject jsonObj = new JSONObject(myJSON); peoples = jsonObj.getJSONArray(TAG_RESULTS); for(int i=0;i&lt;peoples.length();i++){ JSONObject c = peoples.getJSONObject(i); HashMap&lt;String,String&gt; persons = new HashMap&lt;String,String&gt;(); id = c.getString("sender_id"); ids = c.getString("rec_id"); if(id.equals(session_id)&amp;&amp;ids.equals("admin")) { ss = c.getString("messages"); persons.put(TAG_MESSAGE, ss); persons.put("usern", username + ":"); personList.add(persons); } if(id.equals("admin")&amp;&amp;ids.equals(session_id)) { tt = c.getString("messages"); persons.put(TAG_ID, tt); persons.put("admin","Admin:"); personList.add(persons); } adapter = new SimpleAdapter( Messages.this, personList, R.layout.activity_message, new String[]{"admin",TAG_ID, "usern", TAG_MESSAGE }, new int[]{R.id.admin, R.id.id,R.id.name, R.id.messag}); list.setAdapter(adapter); } } catch (JSONException e) { e.printStackTrace(); } } public void getData(){ class GetDataJSON extends AsyncTask&lt;String, Void, String&gt; { @Override protected String doInBackground(String... params) { InputStream inputStream = null; String result = null; try { String postReceiverUrl = "http://piresearch.in/gpsapp/emp_message.php"; //"http://progresscard.progresscard.in/progress_card/messages/get_messages.php"; // HttpClient HttpClient httpClient = new DefaultHttpClient(); // post header HttpPost httpPost = new HttpPost(postReceiverUrl); // add your data List&lt;NameValuePair&gt; nameValuePairs = new ArrayList&lt;NameValuePair&gt;(2); nameValuePairs.add(new BasicNameValuePair("user_id", session_id)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); HttpEntity resEntity = response.getEntity(); inputStream = resEntity.getContent(); // json is UTF-8 by default BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } result = sb.toString(); } catch (Exception e) { Log.i("tagconvertstr", "[" + result + "]"); System.out.println(e); } finally { try{if(inputStream != null)inputStream.close();}catch(Exception squish){} } return result; } @Override protected void onPostExecute(String result){ myJSON = result; showList(); } } GetDataJSON g = new GetDataJSON(); g.execute(); } </code></pre> <p>activity_message.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="10dp" android:paddingLeft="10dp" android:paddingRight="10dp" &gt; &lt;TextView android:textSize="20dp" android:gravity="start" android:textAlignment="textStart" android:id="@+id/admin" android:text="admin" android:textColor="#fff" android:layout_gravity="left" android:layout_width="wrap_content" android:layout_height="30dp" android:paddingBottom="2dip" android:paddingTop="6dip" /&gt; &lt;TextView android:layout_below="@id/admin" android:textSize="20dp" android:gravity="start" android:textAlignment="textStart" android:id="@+id/id" android:background="@drawable/mystyle" android:textColor="#000" android:layout_gravity="left" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="2dip" android:paddingTop="6dip" /&gt; &lt;TextView android:id="@+id/name" android:textSize="20dp" android:textColor="#fff" android:layout_gravity="right" android:layout_width="wrap_content" android:layout_height="30dp" android:paddingBottom="2dip" android:paddingTop="6dip"/&gt; &lt;TextView android:background="@drawable/mystyle" android:layout_below="@id/name" android:id="@+id/messag" android:textSize="20dp" android:textColor="#000" android:layout_gravity="right" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="2dip" android:paddingTop="6dip"/&gt; &lt;/LinearLayout&gt; </code></pre> <p>activity_list.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/main_background" android:orientation="vertical"&gt; &lt;TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="30dp" android:text="Your Messages" android:textAlignment="center" android:background="#dedb36"/&gt; &lt;ListView android:id="@+id/listView" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1" android:background="@null" android:divider="@null" android:transcriptMode="alwaysScroll" android:stackFromBottom="true"/&gt; &lt;LinearLayout android:gravity="bottom" android:id="@+id/llMsgCompose" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@color/white" android:orientation="horizontal" android:weightSum="3"&gt; &lt;EditText android:id="@+id/inputMsg" android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="2" android:background="@color/bg_msg_input" android:textColor="@color/text_msg_input" android:paddingLeft="6dp" android:paddingRight="6dp"/&gt; &lt;Button android:id="@+id/btnSend" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:background="@color/bg_btn_join" android:textColor="#fff" android:text="Send" /&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; </code></pre>
3
4,029
React-router undefined after concatenation
<p><strong>I've set up an app with <a href="http://facebook.github.io/react/" rel="nofollow">react</a> using <a href="https://github.com/rackt/react-router" rel="nofollow">react-router</a> for routing and are having issues bundling it all.</strong></p> <p>I'm trying to build/bundle all the js files using <a href="https://www.npmjs.com/package/gulp-requirejs" rel="nofollow">gulp-requirejs</a>. But somehow the shim is not included, or the react-router is just ignored. Whatever the problem is, I just end up with an error in the browser console saying <code>Uncaught Error: app missing react-router</code></p> <p>I'm including the most important code, feel free to ask if something doesn't make sense.</p> <h1>gulpfile.js</h1> <p><em><a href="https://github.com/jrburke/almond" rel="nofollow">Almond.js</a> is there to replace requirejs</em></p> <pre><code>var gulp = require('gulp'), uglify = require('gulp-uglify'), rjs = require('gulp-requirejs'), gulp.task('requirejsBuild', function() { rjs({ baseUrl: './app/resources/js/', out: 'app.min.js', paths: { 'react': '../bower_components/react/react-with-addons', 'react-router': '../bower_components/react-router/dist/react-router', 'react-shim': 'react-shim', 'jquery': '../bower_components/jquery/dist/jquery' }, shim: { 'react-shim': { exports: 'React' }, 'react-router': { deps: ['react-shim'] } }, deps: ['jquery', 'react-router'], include: ['init'], name: '../bower_components/almond/almond' }) .pipe(uglify()).pipe(gulp.dest('./app/resources/js/')); }); </code></pre> <h1>init.js</h1> <pre><code>require.config({ baseUrl: '/resources/js/', deps: ['jquery'], paths: { 'react': '../bower_components/react/react-with-addons', 'react-router': '../bower_components/react-router/dist/react-router', 'react-shim': 'react-shim', 'jquery': '../bower_components/jquery/dist/jquery' }, shim: { 'react-shim': { exports: 'React' }, 'react-router': { deps: ['react-shim'] } } }); require(['react', 'app'], function(React, App) { var app = new App(); app.init(); }); </code></pre> <h1>app.js</h1> <pre><code>define([ 'react', 'react-router', ], function( React, Router, ){ var Route = Router.Route; var RouteHandler = Router.RouteHandler; var DefaultRoute = Router.DefaultRoute; /** * Wrapper for it all * * @type {*|Function} */ var Wrapper = React.createClass({displayName: "Wrapper", mixins: [Router.State], render: function() { return ( React.createElement(RouteHandler, null) ); } }); var routes = ( React.createElement(Route, {handler: Wrapper, path: "/"}, null) ); var App = function(){}; App.prototype.init = function () { Router.run(routes, Router.HistoryLocation, function (Handler) { React.render(React.createElement(Handler, null), document.getElementById('content')); }); }; return App; } ); </code></pre> <h1>index.html</h1> <p><em>Mainly containing a script tag</em></p> <p>After build you have to manually swap the src with app.min.js </p> <pre><code>&lt;script data-main="/resources/js/init" src="/resources/bower_components/requirejs/require.js"&gt;&lt;/script&gt; </code></pre>
3
1,744
How can I change questions from text fields to radiobuttons?
<p>the quiz should give +2 marks for right answer and -1 for wrong then display the final mark with the submit button and a clear or reset button.</p> <p>I need to change the questions from text fields to radiobuttons(if possible with getradiovalue() ). (I added the earlier one because i thought this was more harder to correct, i am not really sure on how to go ahead with the marks and the radio buttons )</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var myVar; function startTimer() { myVar = setInterval(function () { myTimer() }, 1000); timelimit = maxtimelimit; } function myTimer() { if (timelimit &gt; 0) { curmin = Math.floor(timelimit / 60); cursec = timelimit % 60; if (curmin != 0) { curtime = curmin + " minutes and " + cursec + " seconds left"; } else { curtime = cursec + " seconds left"; } $_('timeleft').innerHTML = curtime; } else { $_('timeleft').innerHTML = timelimit + ' - Out of Time - no credit given for answer '; // clearInterval(myVar); checkAnswer(); } timelimit--; } var pos = 0, posn, choice, correct = 0, rscore = 0; var maxtimelimit = 60, timelimit = maxtimelimit; var questions = [ ['Chair', 'Table'], ['Pen', 'Pencil'], ['Box', 'Circle'], ['Triangle', 'Rectangle'], ['Gun', 'Knife'] ]; var questionOrder = []; var maxNumberOfQuestions = questions.length; var maxNumberToDisplay = 5; function setQuestionOrder() { questionOrder.length = 0; for (var i = 0; i &lt; maxNumberOfQuestions; i++) { questionOrder.push(i); } questionOrder.sort(randOrd); pos = 0; posn = questionOrder[pos]; } function $_(IDS) { return document.getElementById(IDS); } function randOrd() { return (Math.round(Math.random()) - 0.5); } function renderResults() { var test = $_("test"); test.innerHTML = "&lt;h2&gt;You got " + correct + " of " + maxNumberToDisplay + " questions correct &lt; /h2&gt;"; $_("test_status").innerHTML = "Test Completed"; $_('timeleft').innerHTML = ''; test.innerHTML += '&lt;button onclick="location.reload()"&gt;Re-test&lt;/a&gt; '; setQuestionOrder(); correct = 0; clearInterval(myVar); return false; } function renderQuestion() { var test = $_("test"); $_("test_status").innerHTML = "Question " + (pos + 1) + " of "+maxNumberToDisplay; if (rscore != 0) { $_("test_status").innerHTML += '&lt;br&gt;Currently: ' + (correct / rscore * 100).toFixed(0) + '% correct'; } var question = questions[posn][0]; var chA = questions[posn][1]; test.innerHTML = "&lt;h3&gt;" + question + "&lt;/h3&gt;"; test.innerHTML += "&lt;input type='text' id='choices' value=''&gt;&lt;p&gt;"; test.innerHTML += "&lt;button onclick='checkAnswer()'&gt;Submit Answer&lt;/button&gt;"; } function setupTimer() { timelimit = maxtimelimit; clearInterval(myVar); startTimer(); } function checkAnswer() { var correctChoice = questions[posn][1]; var userChoice = document.getElementById("choices").value; rscore++; if (userChoice.toLowerCase() == correctChoice.toLowerCase() &amp;&amp; timelimit &gt; 0) { correct++; } pos++; posn = questionOrder[pos]; if (pos &lt; maxNumberToDisplay) { renderQuestion(); } else { renderResults(); } } window.onload = function () { setQuestionOrder(); renderQuestion(); setupTimer(); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt; &lt;h2 id="test_status"&gt; Quiz&lt;/h2&gt; &lt;h3 id="timeleft"&gt;Time left&lt;/h3&gt; &lt;/div&gt; &lt;div id="test"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
3
1,623
why am i getting Manifest merge error when apply firebase and google authentication libraries
<p>i am trying to connect my app to firebase and use the google authentication system inside it </p> <p>when applying the libraries i get a manifest merge error the error is in this line </p> <pre><code>implementation 'com.google.firebase:firebase-core:17.0.0' </code></pre> <p>this is the error i get </p> <pre><code>ERROR: Manifest merger failed : Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91 is also present at [androidx.core:core:1.0.0] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory). Suggestion: add 'tools:replace="android:appComponentFactory"' to &lt;application&gt; element at AndroidManifest.xml:5:5-23:19 to override. </code></pre> <p>when downgrading the version to 16.0.0 the error is gone however I can't add any other libraries for example if I want to add</p> <pre><code>implementation 'com.google.firebase:firebase-auth:18.0.0' </code></pre> <p>I get this error </p> <pre><code>ERROR: In project 'app' a resolved Google Play services library dependency depends on another at an exact version (e.g. "[15.0. 1]", but isn't being resolved to that version. Behavior exhibited by the library will be unknown. Dependency failing: com.google.android.gms:play-services-stats:15.0.1 -&gt; com.google.android.gms:play-services-basement@[ 15.0.1], but play-services-basement version was 17.0.0. The following dependencies are project dependencies that are direct or have transitive dependencies that lead to the art ifact with the issue. -- Project 'app' depends onto com.google.firebase:firebase-core@{strictly 16.0.0} -- Project 'app' depends onto com.google.android.gms:play-services-flags@{strictly 17.0.0} -- Project 'app' depends onto com.google.firebase:firebase-auth@18.0.0 -- Project 'app' depends onto com.google.firebase:firebase-core@16.0.0 -- Project 'app' depends onto com.google.firebase:firebase-analytics-impl@{strictly 16.0.0} </code></pre> <p>I am new to android and any advice would be great </p> <p>this is my app build.gradle</p> <pre><code>apply plugin: 'com.android.application' android { compileSdkVersion 28 defaultConfig { applicationId "com.example.firebasetestingprojecttwo" minSdkVersion 16 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support.constraint:constraint-layout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' implementation 'com.android.support:design:28.0.0' implementation 'com.android.support:support-v4:28.0.0' implementation 'com.android.support:gridlayout-v7:28.0.0' implementation 'com.google.firebase:firebase-core:17.0.0' } apply plugin: 'com.google.gms.google-services' </code></pre>
3
1,208
Highcharts Tootip in wrong location for multiple x axis
<p>I've got a chart with two x axis side-by-side, with one series in each. When I float over the Series 1 data, I see the tooltip, as expected. When I float over Series 2 data, it highlights the line, but no tooltip. However, if I move the cursor to the left at the same height as the data in Series 2 data, but above the Series 1 data, the tooltip shows the Series 2 information, and the Series 2 points are highlighted. Here's an example:</p> <p><a href="http://jsfiddle.net/q0gphwx2/5/" rel="nofollow">http://jsfiddle.net/q0gphwx2/5/</a></p> <p>Is there a way to correct for this? </p> <pre><code>$(function () { $('#container').highcharts({ chart: { zoomType: 'xy' }, plotOptions : { area : { stacking : 'normal', } }, title: { text: 'Tooltip Hover Anomoly' }, subtitle: { text: 'Float over Series 2 data, then stay at same height, but over series 1. ' }, xAxis: [{ width:300, categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] },{ left: 400, width: 300, offset:0, categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] } ], yAxis: [{ // Secondary yAxis gridLineWidth: 0, title: { text: 'Rainfall', style: { color: Highcharts.getOptions().colors[0] } }, labels: { format: '{value} mm', style: { color: Highcharts.getOptions().colors[0] } } }], tooltip: { shared: false }, series: [{ name: 'Series 1', type: 'line', xAxis: 0, stack: 0, data: [10, 20, 30, 40, 50, 40, 30, 20, 10, 20, 30], tooltip: { valueSuffix: ' mm' } }, { name: 'Series 2', type: 'line', xAxis: 1, stack: 1, data: [100, 120, 100, 120, 100, 120, 100, 120, 100, 120, 100, 120], tooltip: { valueSuffix: ' mm' } }] }); }); </code></pre>
3
1,114
Error on APIM 4.0.0 service catalog listing
<p>I deployed APIM 4.0.0 on Kubernetes. Then, I tried to use the Integration Studio with APIM. Then, I added these lines into the embedded deployment.toml file in Integration Studio.</p> <pre><code>[[service_catalog]] apim_host = &quot;https://xxx.xxx&quot; enable = true username = &quot;admin&quot; password = &quot;admin&quot; </code></pre> <p>After clicking export project artifacts and run, emdedded MI logged a success message.</p> <p>&quot;Successfully updated the service catalog&quot;.</p> <p>Now; when I try to access the service catalog in APIM Publisher Portal, I get this error on the browser:</p> <pre><code>OOPS Something went wrong API Listing Failed to construct 'URL': Invalid URL TypeError: Failed to construct 'URL': Invalid URL at https://xxx.xxx/publisher/site/public/dist/ProtectedApps.8633bb016fecd98c9d94.bundle.js:1:6884 at x (https://xxx.xxx/publisher/site/public/dist/ProtectedApps.8633bb016fecd98c9d94.bundle.js:1:7011) at $i (https://xxx.xxx/publisher/site/public/dist/index.7422e2feefc0de743eb6.bundle.js:81:57930) at vu (https://xxx.xxx/publisher/site/public/dist/index.7422e2feefc0de743eb6.bundle.js:81:104169) at lc (https://xxx.xxx/publisher/site/public/dist/index.7422e2feefc0de743eb6.bundle.js:81:96717) at uc (https://xxx.xxx/publisher/site/public/dist/index.7422e2feefc0de743eb6.bundle.js:81:96642) at Zu (https://xxx.xxx/publisher/site/public/dist/index.7422e2feefc0de743eb6.bundle.js:81:93672) at https://xxx.xxx/publisher/site/public/dist/index.7422e2feefc0de743eb6.bundle.js:81:45314 at t.unstable_runWithPriority (https://xxx.xxx/publisher/site/public/dist/index.7422e2feefc0de743eb6.bundle.js:102:3844) at Ho (https://xxx.xxx/publisher/site/public/dist/index.7422e2feefc0de743eb6.bundle.js:81:45023) in x in div in ForwardRef in ForwardRef in div in ForwardRef in ForwardRef in div in ForwardRef in a in ForwardRef in ForwardRef in ForwardRef in ForwardRef in ForwardRef in ForwardRef in div in ForwardRef in ForwardRef in w in div in ForwardRef in ForwardRef in div in ForwardRef in ForwardRef in _ in div in ForwardRef in ForwardRef in div in ForwardRef in div in ForwardRef in ForwardRef in div in ForwardRef in b in t in t in u in t in t in div in main in div in E in AppErrorBoundary in ForwardRef in Unknown in Unknown in Protected in Suspense in t in t in t in t in PublisherRootErrorBoundary in IntlProvider in Publisher </code></pre> <ul> <li>How can I solve this?</li> <li>How can I remove the service from the service catalog?</li> <li>Do I need to have a seperate deployment for the MI to make integrations in APIM or can APIM somehow run the Integrations itself. I am confused here because EI download page states that APIM includes the capabilities of EI. However, <a href="https://apim.docs.wso2.com/en/latest/get-started/integration-quick-start-guide/" rel="nofollow noreferrer">https://apim.docs.wso2.com/en/latest/get-started/integration-quick-start-guide/</a> it seems like MI should be seperately installed.</li> </ul>
3
1,316
Media queries stop overwriting?
<h2>Solved</h2> <hr /> <p>So - I have been building this grid-framework, when I stumbled upon an issue, which neither I had before nor I can find any evidence on online.</p> <hr /> <p><strong>In short</strong>: when I have multiple <code>@media queries</code> arranged like this:</p> <pre><code>@media (min-width: 400px) {...} @media (min-width: 600px) {...} @media (min-width: 840px) {...} </code></pre> <p>I expect each one to overwrite these who are before it [e.g. <code>@media (min-width: 840px) {...}</code> will overwrite <code>@media (min-width: 600px) {...}</code> and <code>@media (min-width: 400px) {...}</code>] based on the current viewport.</p> <hr /> <p>I am using Sass to generate multiple <code>@media queries</code> as well as a bunch of <code>classes</code>, but its probably not to something being <em>wrong</em> in the code, but something being <em>missing</em>.</p> <p>So what is this supposed to do?</p> <p>The number of columns changes based on the viewport.</p> <pre><code>$breakpoints: ( //name bp col-count xs: [0 4], sm: [400 4], md: [600 8], lg: [840 12], xl: [1024 12], xxl: [1440 12], ); </code></pre> <p>Imagining I am in the <code>xs</code> breakpoint, which reaches froom <code>0px</code> to <code>400px</code>, and I have a column with the class <code>xs:col:11</code>, then I don't want it with to be <code>100vw / (12 / 11)</code> [<code>91.6666667</code>], but <code>100%</code>. So naturally I am trying to overwrite each class, <strong>however</strong>:</p> <p><a href="https://i.stack.imgur.com/L4NNP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L4NNP.png" alt="enter image description here" /></a></p> <p>It stops overwriting after the second <code>@media querie</code>, I expect it to still be 6 columns until the <code>sm</code> breakpoint.</p> <hr /> <p>Below you can see my code and <a href="https://codepen.io/SimplyCius/pen/RwajMjy" rel="nofollow noreferrer">here</a> is a Codepen too.</p> <pre><code>$permanent-grid: true; @mixin permanent-grid-cols($prefix, $span, $col-count) { .#{$prefix}\3A col\3A #{$span} { flex: 0 0 #{100vw / ($col-count / $span)}; max-width: #{100vw / ($col-count / $span)}; } } @if($permanent-grid) { body { @each $breakpoint-name, $breakpoint-content in $breakpoints { $breakpoint: nth($breakpoint-content, 1); $col-count: nth($breakpoint-content, 2); $prefix: $breakpoint-name; @if unit($breakpoint) != &quot;&quot; { @error 'Breakpoints should not be backed up by a unit. But &quot;#{$breakpoint-name}&quot; in map: #{&quot;$&quot; + &quot;breakpoints&quot;} is backed up by a unit'; } @media (min-width: #{$breakpoint}px) { @each $breakpoint-nameC, $breakpoint-contentC in $breakpoints { $col-countC: nth($breakpoint-contentC, 2); $prefixC: $breakpoint-nameC; @for $iC from 1 through $col-countC { @if $col-count &lt; $iC { @include permanent-grid-cols($prefixC, $iC, $iC); } } } @for $i from 1 through $col-count { @include permanent-grid-cols($prefix, $i, $col-count); } } } } } </code></pre> <hr /> <p>This is a fraction of what it compiles to:</p> <pre><code>@media (min-width: 600px) { body .lg\3A col\3A 9 { flex: 0 0 100vw; max-width: 100vw; } body .lg\3A col\3A 10 { flex: 0 0 100vw; max-width: 100vw; } body .lg\3A col\3A 11 { flex: 0 0 100vw; max-width: 100vw; } body .lg\3A col\3A 12 { flex: 0 0 100vw; max-width: 100vw; } body .xl\3A col\3A 9 { flex: 0 0 100vw; max-width: 100vw; } body .xl\3A col\3A 10 { flex: 0 0 100vw; max-width: 100vw; } body .xl\3A col\3A 11 { flex: 0 0 100vw; max-width: 100vw; } body .xl\3A col\3A 12 { flex: 0 0 100vw; max-width: 100vw; } body .xxl\3A col\3A 9 { flex: 0 0 100vw; max-width: 100vw; } body .xxl\3A col\3A 10 { flex: 0 0 100vw; max-width: 100vw; } body .xxl\3A col\3A 11 { flex: 0 0 100vw; max-width: 100vw; } body .xxl\3A col\3A 12 { flex: 0 0 100vw; max-width: 100vw; } body .md\3A col\3A 1 { flex: 0 0 12.5vw; max-width: 12.5vw; } body .md\3A col\3A 2 { flex: 0 0 25vw; max-width: 25vw; } body .md\3A col\3A 3 { flex: 0 0 37.5vw; max-width: 37.5vw; } body .md\3A col\3A 4 { flex: 0 0 50vw; max-width: 50vw; } body .md\3A col\3A 5 { flex: 0 0 62.5vw; max-width: 62.5vw; } body .md\3A col\3A 6 { flex: 0 0 75vw; max-width: 75vw; } body .md\3A col\3A 7 { flex: 0 0 87.5vw; max-width: 87.5vw; } body .md\3A col\3A 8 { flex: 0 0 100vw; max-width: 100vw; } } </code></pre>
3
2,289
Visual Studio 2017 reports this error for my multi-platform xamarin App
<p>Someone Help I have been on this issue for 4 days, my app was working perfectly fine when it started reporting this error "This debug engine does not support exception conditions. The condition(s) will be ignored". It does not find some of the dll.so packages, I tried deleting the bin and debug folder, and rebuild the App, I have also reinstalled and installed visual studio, formatted my PC and did a clean installation all to no avail. The same comes up, when I try running the same app from different user in the project Repo in gitlab. I tried different emulators and now using my phone but still mp solution. </p> <p><a href="https://i.stack.imgur.com/XFNYR.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XFNYR.jpg" alt="enter image description here"></a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>This debug engine does not support exception conditions. The condition(s) will be ignored. 03-04 23:59:08.480 E/Zygote (32704): v2 03-04 23:59:08.480 I/SELinux (32704): Function: selinux_compare_spd_ram, index[1], SPD-policy is existed. and_ver=SEPF_SM-G903W_5.1.1 ver=51 03-04 23:59:08.480 W/SELinux (32704): Function: selinux_compare_spd_ram, index[1], priority [2], priority version is VE=SEPF_SECMOBILE_6.0.1_0033 03-04 23:59:08.480 E/Zygote (32704): accessInfo : 0 03-04 23:59:08.480 W/SELinux (32704): SELinux: seapp_context_lookup: seinfo=default, level=s0:c512,c768, pkgname=com.companyname.CHA 03-04 23:59:08.480 I/art (32704): Late-enabling -Xcheck:jni 03-04 23:59:08.480 I/libpersona(32704): KNOX_SDCARD checking this for 10006 03-04 23:59:08.480 I/libpersona(32704): KNOX_SDCARD not a persona 03-04 23:59:08.530 D/TimaKeyStoreProvider(32704): TimaSignature is unavailable 03-04 23:59:08.530 D/ActivityThread(32704): Added TimaKeyStore provider 03-04 23:59:08.590 D/ResourcesManager(32704): For user 0 new overlays fetched Null 03-04 23:59:08.760 W/monodroid(32704): Creating public update directory: `/data/user/0/com.companyname.CHA/files/.__override__` 03-04 23:59:08.760 W/monodroid(32704): Using override path: /data/user/0/com.companyname.CHA/files/.__override__ 03-04 23:59:08.760 W/monodroid(32704): Using override path: /storage/emulated/0/Android/data/com.companyname.CHA/files/.__override__ 03-04 23:59:08.760 W/monodroid(32704): Trying to load sgen from: /data/user/0/com.companyname.CHA/files/.__override__/libmonosgen-2.0.so 03-04 23:59:08.760 W/monodroid(32704): Trying to load sgen from: /storage/emulated/0/Android/data/com.companyname.CHA/files/.__override__/libmonosgen-2.0.so 03-04 23:59:08.760 W/monodroid(32704): Trying to load sgen from: /storage/emulated/0/../legacy/Android/data/com.companyname.CHA/files/.__override__/libmonosgen-2.0.so 03-04 23:59:08.760 W/monodroid(32704): Trying to load sgen from: /data/app/com.companyname.CHA-1/lib/arm/libmonosgen-2.0.so 03-04 23:59:08.770 W/monodroid(32704): Trying to load sgen from: /data/user/0/com.companyname.CHA/files/.__override__/links/libmonosgen-2.0.so 03-04 23:59:08.780 W/monodroid-debug(32704): Trying to initialize the debugger with options: --debugger-agent=transport=dt_socket,loglevel=0,address=127.0.0.1:29210,server=y,embedding=1 03-04 23:59:08.820 W/monodroid-debug(32704): Accepted stdout connection: 23 03-04 23:59:09.610 D/Mono (32704): Image addref mscorlib[0xea2d09e0] -&gt; mscorlib.dll[0xee999600]: 2 03-04 23:59:09.620 D/Mono (32704): Prepared to set up assembly 'mscorlib' (mscorlib.dll) 03-04 23:59:09.620 D/Mono (32704): AOT: image 'mscorlib.dll.so' not found: dlopen failed: library "/data/app/com.companyname.CHA-1/lib/arm/libaot-mscorlib.dll.so" not found 03-04 23:59:09.620 D/Mono (32704): AOT: image '/Users/builder/jenkins/workspace/xamarin-android-d15-9/xamarin-android/external/mono/sdks/out/android-armeabi-v7a-release/lib/mono/aot-cache/arm/mscorlib.dll.so' not found: dlopen failed: library "/data/app/com.companyname.CHA-1/lib/arm/libaot-mscorlib.dll.so" not found 03-04 23:59:09.620 D/Mono (32704): Config attempting to parse: 'mscorlib.dll.config'. 03-04 23:59:09.620 D/Mono (32704): Config attempting to parse: '/Users/builder/jenkins/workspace/xamarin-android-d15-9/xamarin-android/external/mono/sdks/out/android-armeabi-v7a-release/etc/mono/assemblies/mscorlib/mscorlib.config'. 03-04 23:59:09.670 D/Mono (32704): Assembly mscorlib[0xea2d09e0] added to domain RootDomain, ref_count=1 03-04 23:59:11.940 D/Mono (32704): Assembly Loader probing location: '/storage/emulated/0/Android/data/com.companyname.CHA/files/.__override__/CHA.Android.dll'. 03-04 23:59:11.940 D/Mono (32704): Image addref CHA.Android[0xea2d0bc0] -&gt; /storage/emulated/0/Android/data/com.companyname.CHA/files/.__override__/CHA.Android.dll[0xea427500]: 2 03-04 23:59:11.940 D/Mono (32704): Prepared to set up assembly 'CHA.Android' (/storage/emulated/0/Android/data/com.companyname.CHA/files/.__override__/CHA.Android.dll) 03-04 23:59:11.940 D/Mono (32704): Assembly CHA.Android[0xea2d0bc0] added to domain RootDomain, ref_count=1 03-04 23:59:11.940 D/Mono (32704): AOT: image '/storage/emulated/0/Android/data/com.companyname.CHA/files/.__override__/CHA.Android.dll.so' not found: dlopen failed: library "/data/app/com.companyname.CHA-1/lib/arm/libaot-CHA.Android.dll.so" not found 03-04 23:59:11.940 D/Mono (32704): AOT: image '/Users/builder/jenkins/workspace/xamarin-android-d15-9/xamarin-android/external/mono/sdks/out/android-armeabi-v7a-release/lib/mono/aot-cache/arm/CHA.Android.dll.so' not found: dlopen failed: library "/data/app/com.companyname.CHA-1/lib/arm/libaot-CHA.Android.dll.so" not found 03-04 23:59:11.940 D/Mono (32704): Assembly Loader loaded assembly from location: '/storage/emulated/0/Android/data/com.companyname.CHA/files/.__override__/CHA.Android.dll'. 03-04 23:59:11.940 D/Mono (32704): Config attempting to parse: '/storage/emulated/0/Android/data/com.companyname.CHA/files/.__override__/CHA.Android.dll.config'. 03-04 23:59:11.940 D/Mono (32704): Config attempting to parse: '/Users/builder/jenkins/workspace/xamarin-android-d15-9/xamarin-android/external/mono/sdks/out/android-armeabi-v7a-release/etc/mono/assemblies/CHA.Android/CHA.Android.config'. 03-04 23:59:11.940 D/Mono (32704): Assembly Loader probing location: '/storage/emulated/0/Android/data/com.companyname.CHA/files/.__override__/BottomNavigationBar.dll'. 03-04 23:59:11.940 D/Mono (32704): Image addref BottomNavigationBar[0xea2d0aa0] -&gt; /storage/emulated/0/Android/data/com.companyname.CHA/files/.__override__/BottomNavigationBar.dll[0xea427a00]: 2 03-04 23:59:11.940 D/Mono (32704): Prepared to set up assembly 'BottomNavigationBar' (/storage/emulated/0/Android/data/com.companyname.CHA/files/.__override__/BottomNavigationBar.dll) 03-04 23:59:11.940 D/Mono (32704): Assembly BottomNavigationBar[0xea2d0aa0] added to domain RootDomain, ref_count=1 03-04 23:59:11.940 D/Mono (32704): AOT: image '/storage/emulated/0/Android/data/com.companyname.CHA/files/.__override__/BottomNavigationBar.dll.so' not found: dlopen failed: library "/data/app/com.companyname.CHA-1/lib/arm/libaot-BottomNavigationBar.dll.so" not found 03-04 23:59:11.940 D/Mono (32704): AOT: image '/Users/builder/jenkins/workspace/xamarin-android-d15-9/xamarin-android/external/mono/sdks/out/android-armeabi-v7a-release/lib/mono/aot-cache/arm/BottomNavigationBar.dll.so' not found: dlopen failed: library "/data/app/com.companyname.CHA-1/lib/arm/libaot-BottomNavigationBar.dll.so" not found 03-04 23:59:11.940 D/Mono (32704): Assembly Loader loaded assembly from location: '/storage/emulated/0/Android/data/com.companyname.CHA/files/.__override__/BottomNavigationBar.dll'. 03-04 23:59:11.950 D/Mono (32704): Config attempting to parse: '/storage/emulated/0/Android/data/com.companyname.CHA/files/.__override__/BottomNavigationBar.dll.config'. 03-04 23:59:11.950 D/Mono (32704): Config attempting to parse: '/Users/builder/jenkins/workspace/xamarin-android-d1</code></pre> </div> </div> </p>
3
3,156
My excel userform becomes unresponsive the next time I load it
<p>I have two forms, a login form to authenticate users to enter the system and a main form to work with if the authentication is successful. I work with an access database to search for the valid users and also to populate lists in the main form.</p> <p><a href="https://i.stack.imgur.com/nvHhR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nvHhR.png" alt="The user form for authentication"></a></p> <p>And here is the code for that:</p> <pre><code>Private Sub CancelCommandButton_Click() CloseDatabase Unload Me End Sub Private Sub ConfirmCommandButton_Click() ... End Sub Private Sub UserForm_Initialize() ConnectDatabase End Sub Private Sub OpenMainForm() Unload Me MainForm.Show End Sub Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer) If CloseMode = vbFormControlMenu Then Cancel = True End If End Sub </code></pre> <p>And here is the code for managing main form load-up and close:</p> <pre><code>Public Sub UpdateControls() PopulateUserList End Sub Private Sub UserForm_Activate() sTag = Split(Me.Tag, "|") If sTag(0) &lt;&gt; "1" Then Me.MainFormMultiPage.Pages(0).Enabled = False Me.MainFormMultiPage.Value = 1 Else Me.MainFormMultiPage.Pages(0).Enabled = True Me.MainFormMultiPage.Value = 0 UpdateControls End If UserLabel1.Caption = sTag(1) UserLabel2.Caption = sTag(1) UserLabel3.Caption = sTag(1) End Sub Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer) If CloseMode = vbFormControlMenu Then ' Tip: If you want to prevent closing UserForm by Close (×) button in the right-top corner of the UserForm, just uncomment the following line: ' Cancel = True Dim answer As Integer answer = MsgBox("ÂíÇ ãØãÆäíÏ ˜å ãí ÎæÇåíÏ ÇÒ ÓÇãÇäå ÎÇÑÌ ÔæíÏ¿", vbYesNo + vbQuestion, "ÎÑæÌ ÇÒ ÓÇãÇäå") If answer = vbYes Then CloseDatabase Else Cancel = True End If End If End Sub Private Sub UserForm_Terminate() loginForm.Show End Sub </code></pre> <p>When I close the main form by clicking 'X' button, the login form reappears and the main form is closed; But when I login again (preferably using the same credentials) the main form is displayed but totally unresponsive (No list population, 'X' button doesn't work or any other controls in the form).</p> <p>What should I do? Does the code in the UserForm_CloseQuery() unload the main form and all of its macros and I can't get the required events back to function or am I missing something?</p> <p>It's not a time I started coding VBA and I can't make the head or tail of it easily when new problems arise. Any help would be appreciated. Thanks</p>
3
1,037
How to transfer an image to another component using Redux?
<p>I've set up my Redux to capture a user selection from a webshop (item, size, price) and send it to another <code>Cart</code> component. This is working perfectly, but I want to capture an image of the item and send it to <code>Cart</code>. Within each product page where you can add an item to the cart there is an image that I also would like to send with the user selection. This is an example of the product page component:</p> <pre><code>import React, { Component } from 'react'; import { connect } from 'react-redux'; import { addCart } from '../../actions'; import SeltzShirt from './seltzshirt.jpg'; import Slideone from './slideSeltzOne'; import Slidetwo from './slideSeltzTwo'; import RightArrow from './rightarrow'; import LeftArrow from './leftarrow'; export class ProductPage3 extends Component { constructor(props) { super(props); this.state = { slideCount: 1, value: 'medium', cartData: {} } this.nextSlide = this.nextSlide.bind(this); this.previousSlide = this.previousSlide.bind(this); this.handleClick = this.handleClick.bind(this); this.change = this.change.bind(this); } handleClick() { let cart = {price:25,item:this.description.innerHTML,size:this.state.value}; this.props.onCartAdd(cart); console.log(cart); this.itemSelection(cart); } ... componentDidMount () { window.scrollTo(0, 0) } render() { return ( &lt;div className= "ProductPage" id="ProductPage"&gt; &lt;div id='slider'&gt; {this.state.slideCount === 1 ? &lt;Slideone /&gt; : null} {this.state.slideCount === 2 ? &lt;Slidetwo /&gt; : null} &lt;RightArrow nextSlide={this.nextSlide} /&gt; &lt;LeftArrow previousSlide={this.previousSlide} /&gt; &lt;/div&gt; &lt;div id='InfoSquare'&gt; &lt;div id='wrapper'&gt; &lt;div id='item' ref={i=&gt;this.description=i}&gt;LOGO TEE&lt;/div&gt; &lt;div id='description'&gt;Black tee 100% cotton with red silkscreened logo on front and back.&lt;/div&gt; &lt;select id="size2" onChange={this.change} value={this.state.value}&gt; &lt;option value="medium"&gt;Medium&lt;/option&gt; &lt;option value="large"&gt;Large&lt;/option&gt; &lt;option value="x-large"&gt;X-large&lt;/option&gt; &lt;/select&gt; &lt;button onClick={this.handleClick} className="addit"&gt;ADD TO CART&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ); } nextSlide() { this.setState({ slideCount: this.state.slideCount + 1 }) } previousSlide() { this.setState({ slideCount: this.state.slideCount - 1 }) } } const mapDispatchToProps = (dispatch) =&gt; { return { onCartAdd: (cart) =&gt; { dispatch(addCart(cart)); }, } } function mapStateToProps(state) { return { cart: state.cart }; } export default connect(mapStateToProps,mapDispatchToProps)(ProductPage3); </code></pre> <p>This is my <code>Cart</code> component:</p> <pre><code>import React, { Component } from 'react'; import {addCart} from './Shop'; import { removeCart } from '../../actions'; import { connect } from 'react-redux'; export class Cart extends Component { constructor(props) { super(props); this.state = {items: this.props.cart,cart: [],total: 0}; } ... render() { return( &lt;div className= "Webcart" id="Webcart"&gt; &lt;div id='WebcartWrapper'&gt; &lt;ul id='webCartList'&gt; {this.state.items.map((item, index) =&gt; { return &lt;li className='cartItems' key={'cartItems_'+index}&gt; &lt;h4&gt;{item.item}&lt;/h4&gt; &lt;p&gt;Size: {item.size}&lt;/p&gt; &lt;p&gt;Price: {item.price}&lt;/p&gt; &lt;button onClick={() =&gt; this.handleClick(item)}&gt;Remove&lt;/button&gt; &lt;/li&gt; })} &lt;/ul&gt; &lt;div&gt;Total: ${this.countTotal()}&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ); } } const mapDispatchToProps = (dispatch) =&gt; { return { onCartAdd: (cart) =&gt; { dispatch(addCart(cart)); }, onCartRemove: (item) =&gt; { dispatch(removeCart(item)); }, } } function mapStateToProps(state) { return { cart: state.cart }; } export default connect(mapStateToProps, mapDispatchToProps)(Cart); </code></pre> <p>In <code>Cart</code> I'm rendering the item selection data for each object added to the cart. Here is where I want to display the item image also.</p> <p>Since I have a image slider set up, an example of one of the slides would be:</p> <pre><code>import React, { Component } from 'react'; import take1 from './DETAIL.png'; const SlideNocHOne= (props) =&gt; { return &lt;img src= {take1} id="slide"&gt;&lt;/img&gt; } export default SlideNocHOne; </code></pre> <p>Let's say I want this <code>DETAIL.png</code> image on the <code>Cart</code>, how could I transfer it with the user selection using Redux?</p> <p>These are my Redux components:</p> <pre><code>import { createStore, applyMiddleware, compose } from 'redux'; import { persistStore, autoRehydrate } from 'redux-persist'; import reducer from './reducers'; import thunkMiddleware from 'redux-thunk'; import {createLogger} from 'redux-logger'; const store = createStore( reducer, undefined, compose( applyMiddleware(createLogger(), thunkMiddleware), autoRehydrate() ) ); persistStore(store, {whitelist: ['cart']}); export default store; import {ADD_CART} from './actions'; import {REMOVE_CART} from './actions'; import { REHYDRATE } from 'redux-persist/constants'; export default Reducer; var initialState = { cart:{}, data: [], url: "/api/comments", pollInterval: 2000 }; function Reducer(state = initialState, action){ switch(action.type){ case REHYDRATE: if (action.payload &amp;&amp; action.payload.cart) { return { ...state, ...action.payload.cart }; } return state; case ADD_CART: return { ...state, cart: [...state.cart, action.payload] } case REMOVE_CART: return { ...state, cart: state.cart.filter((item) =&gt; action.payload !== item) } default: return state; }; } export const ADD_CART = 'ADD_CART'; export const REMOVE_CART = 'REMOVE_CART'; export function addCart(item){ return { type: ADD_CART, payload: item } }; export function removeCart(item){ return{ type:REMOVE_CART, payload: item } }; </code></pre> <p>How can I use my Redux setup to transfer the image of a user selection to <code>Cart</code>?</p>
3
3,604
Unable to consume JAVA sdk for Google classroom API's getting PERMISSION_DENIED Request had insufficient authentication scopes
<p>I am trying to integrate google classroom in my java project Using OAuth 2.0 for <strong>Server to Server</strong> authentication, example is given here <a href="https://developers.google.com/classroom/quickstart/java" rel="nofollow noreferrer">Official Google class room integration doc</a> uses <strong>OAuth consent screen authentication</strong>, I altered the code for <strong>Server to Server</strong> authentication with few changes</p> <p>Progress so far:</p> <ul> <li>Created a Google App </li> <li><p>Enabled Google classroom API from Dashboard.</p></li> <li><p>Created Service Account Key (.p12) for server-to-server authentication(later used that in code along with Application name)</p> <pre><code>public class Quickstart2 { private static final String APPLICATION_NAME ="MY_APP_NAME"; private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); private static HttpTransport httpTransport; /** Global instance of the HTTP transport. */ private static HttpTransport HTTP_TRANSPORT; private static final String SERVICE_ACCOUNT_EMAIL = "ID_CREADED_ON_GOOGLE_APP"; /** Global instance of the scopes required by this quickstart. * * If modifying these scopes, delete your previously saved credentials * at ~/.credentials/classroom.googleapis.com-java-quickstart */ private static final List&lt;String&gt; SCOPES = Arrays.asList(ClassroomScopes.CLASSROOM_COURSEWORK_ME); static { try { HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); } catch (Throwable t) { t.printStackTrace(); System.exit(1); } } /** * Creates an authorized Credential object. * @return an authorized Credential object. * @throws IOException * @throws GeneralSecurityException */ public static Credential authorize() throws IOException, GeneralSecurityException { /* Added this code in given sample code for Server-to-server authentication*/ httpTransport = GoogleNetHttpTransport.newTrustedTransport(); GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport) .setJsonFactory(JSON_FACTORY) .setServiceAccountId(SERVICE_ACCOUNT_EMAIL) .setServiceAccountScopes(SCOPES) .setServiceAccountPrivateKeyFromP12File(new File("BULB-1cb9e145138b.p12")) .setServiceAccountUser("bulb-88@bulb-173512.iam.gserviceaccount.com") .build(); return credential; } /** * Build and return an authorized Classroom client service. * @return an authorized Classroom client service * @throws IOException * @throws GeneralSecurityException */ public static com.google.api.services.classroom.Classroom getClassroomService() throws IOException, GeneralSecurityException { Credential credential = authorize(); System.out.println("token "+credential.getAccessToken()); return new com.google.api.services.classroom.Classroom.Builder( HTTP_TRANSPORT, JSON_FACTORY, credential) .setApplicationName(APPLICATION_NAME) .build(); } public static void main(String[] args) throws IOException, GeneralSecurityException { // Build a new authorized API client service. com.google.api.services.classroom.Classroom service = getClassroomService(); Course course = new Course() .setName("10th Grade Biology") .setSection("Period 2") .setDescriptionHeading("Welcome to 10th Grade Biology") .setDescription("test descriptioon") .setRoom("301") .setOwnerId("me") .setCourseState("PROVISIONED"); course = service.courses().create(course).execute(); /* here I am getting the exception */ // List the first 10 courses that the user has access to. ListCoursesResponse response = service.courses().list() .setPageSize(10) .execute(); List&lt;Course&gt; courses = response.getCourses(); System.out.println(courses); if (courses == null || courses.size() == 0) { System.out.println("No courses found."); } else { System.out.println("Courses:"); for (Course course1 : courses) { System.out.printf("%s\n", course1.getName()); } } } </code></pre> <p>}</p></li> </ul> <p>I belive nothing is wrong with authentication because whenever I run this piece of code, get an entry in dashboard on my app "<a href="https://console.developers.google.com/apis/dashboard" rel="nofollow noreferrer">https://console.developers.google.com/apis/dashboard</a>"</p> <p><a href="https://i.stack.imgur.com/KoPJz.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KoPJz.jpg" alt="here is the image of what I am getting on dashboard"></a></p> <p>I am new to Google class room and Its been a long time I am trying to integrating this no success so far, need help.</p> <p>One more thing It says it is mandatory to have a G suite account (I dont get it where it is used, yet I have not created G suit account, is this the reason I am getting exception)</p> <p>Please let me know If I am suppose to add more details on above senerio.</p> <p>Thanks in advance</p>
3
1,995
php mysql query deleting items even when the item is not present in the table
<p>This is my "DELETE BOOKS FROM LIBRARY PAGE"</p> <pre><code>&lt;HTML&gt; &lt;?php global $bkiderr; ?&gt; &lt;link rel="stylesheet" href="btndeletebooks.css"&gt; &lt;link rel="stylesheet" href="tablealncenter.css"&gt; &lt;link rel="stylesheet" href="spanerror.css"&gt; &lt;p&gt;&lt;span class="error"&gt;* required field.&lt;/span&gt;&lt;/p&gt; &lt;HEAD&gt; &lt;h1 align="center"&gt;THIS PAGE REMOVES BOOKS FROM THE LIBRARY&lt;/h1&gt; &lt;/HEAD&gt; TO REMOVE BOOKS FROM THE LIBRARY&lt;BR&gt;&lt;BR&gt; &lt;FORM action="&lt;?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?&gt;" method="POST"&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;ENTER THE BOOK ID &amp;nbsp;(format -&gt; bkyearbkno ) :&lt;/td&gt; &lt;td&gt;&lt;input type=text name="bkid"&gt; &lt;span class="error"&gt;* &lt;?php echo $bkiderr;?&gt;&lt;/span&gt; &lt;/TR&gt; &lt;/table&gt; &lt;BR&gt; CLICK HERE TO REMOVE BOOK: &lt;table&gt; &lt;tr&gt; &lt;td&gt;&lt;input id="rndbutton1" type="submit" value="REMOVE BOOK FROM LIBRARY" name="submit" title="CLICK HERE TO REMOVE A BOOK"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/br&gt;&lt;/br&gt; &lt;/FORM&gt; &lt;?php include 'dbcon.php'; $qbkname="select bkname from books where bkid="; #-------------------------REMOVE BOOKS FROM LIBRARY-----------------------# if( $_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["bkid"])) $bkiderr="BOOK ID is required"; else $bkid = $_POST["bkid"]; if(isset($bkid)) { $qchkissuestat="select * from books where bkid='$bkid'"; $reschkissuestat=$mysqli-&gt;query($qchkissuestat,MYSQLI_STORE_RESULT); while($res=$reschkissuestat-&gt;fetch_array(MYSQLI_NUM)) { $k=$res{5}; echo $res{0}." ".$k."\n"; break; } if($k='YES') { $query="delete from books where bkid='$bkid'"; $result=$mysqli-&gt;query($query,MYSQLI_STORE_RESULT); echo "YOU REMOVED THE BOOK FROM THE LIBRARY"; echo "&lt;table border='1'&gt;"; echo "&lt;th&gt;BOOK ID"; echo "&lt;tr&gt;"; echo "&lt;td class='alncenter'&gt;$bkid&lt;/td&gt;"; echo "&lt;/tr&gt;"; echo "&lt;/table&gt;"; exit(); } } } $mysqli-&gt;close(); ?&gt; &lt;div class="error"&gt; &lt;?php echo "$bkiderr &lt;BR&gt;"; ?&gt; &lt;/div&gt; &lt;/HTML&gt; </code></pre> <p>Code on this page is deleting the books supplied as book ids even when there is no books assigned with the book id given as input,which I do not want.I need a mechanism with which I can check whether a particular book id is present in the table or not before deleting the item from the table.</p>
3
1,839
Error While Uploading Image to server using PHP
<p>I'm trying to upload an image to a server by using php. But I'm getting following error:</p> <blockquote> Caused by: java.lang.IllegalArgumentException: Illegal character in query at index 171:my server name/upload.php?sel_bar_code=ab12&text=hello&image=[encoded image to base64 comes hear]</blockquote> <p>I'm not getting this error on android. Below is my code that uploades images to the server.</p> <pre><code>if (isImage) { imgPreview.setVisibility(View.VISIBLE); vidPreview.setVisibility(View.GONE); // bimatp factory BitmapFactory.Options options = new BitmapFactory.Options(); // down sizing image as it throws OutOfMemory Exception for larger // images options.inSampleSize = 8; bitmap = BitmapFactory.decodeFile(filePath, options); imgPreview.setImageBitmap(bitmap); ByteArrayOutputStream ByteStream=new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG,100, ByteStream); byte [] b=ByteStream.toByteArray(); image_value=Base64.encodeToString(b, Base64.DEFAULT); </code></pre> <p>Background process code:</p> <pre><code>protected String doInBackground(Void... params) { return uploadFile(); } @SuppressWarnings("deprecation") private String uploadFile() { String responseString = null; HttpClient httpclient = new DefaultHttpClient(); List&lt;NameValuePair&gt; qparams = new ArrayList&lt;NameValuePair&gt;(); // These params should ordered in key qparams.add(new BasicNameValuePair("sel_bar_code", product_id)); HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL+"sel_bar_code="+product_id+"&amp;text="+text_value +"&amp;image="+image_value); try { AndroidMultiPartEntity entity = new AndroidMultiPartEntity( new ProgressListener() { @Override public void transferred(long num) { publishProgress((int) ((num / (float) totalSize) * 100)); } }); File sourceFile = new File(filePath); // Adding file data to http body entity.addPart("image", new FileBody(sourceFile)); // Extra parameters if you want to pass to server entity.addPart("website", new StringBody("www.google.com")); entity.addPart("email", new StringBody("info@gmail.com")); totalSize = entity.getContentLength(); httppost.setEntity(entity); // Making server call HttpResponse response = httpclient.execute(httppost); HttpEntity r_entity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { // Server response responseString = EntityUtils.toString(r_entity); } else { responseString = "Error occurred! Http Status Code: " + statusCode; } } catch (ClientProtocolException e) { responseString = e.toString(); } catch (IOException e) { responseString = e.toString(); } return responseString; } </code></pre>
3
1,665
Parsing nested JSON Object in recyclerview using retrofit gives error: "Expected begin ARRAY but was BEGIN_OBJECT at line 1
<blockquote> <p>So i was trying to parse JSON data into my recyclerview. But got error saying: &quot;Expected begin ARRAY but was BEGIN_OBJECT at line 1&quot;</p> </blockquote> <p>My <strong>JSON</strong> response:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;status&quot;: &quot;success&quot;, &quot;data&quot;: { &quot;0&quot;: { &quot;id&quot;: &quot;8&quot;, &quot;name&quot;: &quot;hmhshwv&quot;, &quot;description&quot;: &quot;vhhh&quot;, &quot;location&quot;: &quot;nhhjj&quot; }, &quot;1&quot;: { &quot;id&quot;: &quot;54&quot;, &quot;name&quot;: &quot;mabwb&quot;, &quot;description&quot;: &quot;ywg&quot;, &quot;location&quot;: &quot;gwgw&quot; } &quot;2&quot;: { &quot;id&quot;: &quot;48&quot;, &quot;name&quot;: &quot;nnf&quot;, &quot;description&quot;: &quot;gwb&quot;, &quot;location&quot;: &quot;wggw&quot; } } } </code></pre> <p>My Model class:</p> <pre class="lang-java prettyprint-override"><code>public class DataModel { private String id; private String firstname; private String lastname; private String contact; public DataModel(String id, String firstname, String lastname, String contact) { this.id = id; this.firstname = firstname; this.lastname = lastname; this.contact = contact; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } } </code></pre> <p>My apiInterface: the api has body parameters such as apikey, userid and storeid.</p> <pre class="lang-java prettyprint-override"><code>public interface MyApiCall { @Headers(&quot;Accept: application/json&quot;) @POST(&quot;mybiz/api/staff-list&quot;) Call&lt;List&lt;DataModel&gt;&gt; getDataModel( @Body String apikey, @Body String userid, @Body String storeid ); } </code></pre> <p>My <strong>RetrofitClient</strong> class:</p> <pre class="lang-java prettyprint-override"><code>public class RetrofitClient { private static final String BASE_URL = &quot;https://api.pidu.in/&quot;; private static Retrofit retrofit = null; public static MyApiCall getRetrofitClient() { if(retrofit == null) { retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit.create(MyApiCall.class); } } </code></pre> <p>My <strong>MainActivity</strong>:</p> <pre class="lang-java prettyprint-override"><code>private static final String TAG = MainActivity.class.getSimpleName(); private static final String apikey = &quot;somethinggg&quot;; private static final String userid = &quot;a number&quot;; private static final String storeid = &quot;158&quot;; RecyclerView recyclerView; ProgressBar progressBar; LinearLayoutManager linearLayoutManager; DataModelAdapter dataModelAdapter; List&lt;DataModel&gt; dataModels = new ArrayList&lt;&gt;(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = (RecyclerView) findViewById(R.id.recyclerView); progressBar = (ProgressBar) findViewById(R.id.progressBar3); linearLayoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(linearLayoutManager); dataModelAdapter = new DataModelAdapter(dataModels); recyclerView.setAdapter(dataModelAdapter); fetchDataModel(); } private void fetchDataModel() { progressBar.setVisibility(View.VISIBLE); RetrofitClient.getRetrofitClient().getDataModel(apikey, userid, storeid).enqueue(new Callback&lt;List&lt;DataModel&gt;&gt;() { @Override public void onResponse(@NonNull Call&lt;List&lt;DataModel&gt;&gt; call, @NonNull Response&lt;List&lt;DataModel&gt;&gt; response) { if(response.isSuccessful() &amp;&amp; response.body() != null) { Log.e(TAG, &quot;Error: &quot; + response.body()); dataModels.addAll(response.body()); dataModelAdapter.notifyDataSetChanged(); progressBar.setVisibility(View.GONE); } } @Override public void onFailure(@NonNull Call&lt;List&lt;DataModel&gt;&gt; call, @NonNull Throwable t) { Toast.makeText(MainActivity.this, &quot;Error: &quot; + t.getLocalizedMessage(), Toast.LENGTH_LONG).show(); } }); } </code></pre> <p>And for reference my hoppscotch api looks like:</p> <p><a href="https://i.stack.imgur.com/gQKyU.png" rel="nofollow noreferrer">hoppscotch api</a></p> <p>I understand that I should parse the JSON object but can't find a particular way to do that.</p>
3
2,374
How do I call my Date Picker from a button press?
<p>I am trying to create an app that allows me to pick a date and a table is populated with appointments on that day. I am having troubles with getting the date picker to show.</p> <p>I have taken a look at this <a href="https://developer.android.com/guide/topics/ui/controls/pickers" rel="nofollow noreferrer">https://developer.android.com/guide/topics/ui/controls/pickers</a> and created a date picker from this code. I want to call that date picker from a button press found in the <code>AddAppointmentActivity</code> class.</p> <p>Here is my Appointment class:</p> <pre><code>package com.example.dentdevils.ui.HomeLinks; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.DialogFragment; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.TextView; import com.example.dentdevils.R; import com.example.dentdevils.ui.HomeActivity; import java.util.Calendar; public class AddAppointmentActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_appointment); // Date label TextView dateLabel = (TextView) findViewById(R.id.txtDateLabel); // Date Picker Button Functionality Button datePicker = (Button) findViewById(R.id.btnDatePicker); datePicker.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); // Back Button Functionality Button btnBack = (Button) findViewById(R.id.btnBack); btnBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent launchHomepage = new Intent(AddAppointmentActivity.this, HomeActivity.class); startActivity(launchHomepage); } }); } } class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { @NonNull @Override public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { final Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); return new DatePickerDialog(getActivity(), this, year, month, day); } @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { // Get date set by user and display appointments in table for the date chosen. } public void showDatePickerDialog() { DialogFragment newFragment = new com.example.dentdevils.ui.HomeLinks.DatePickerFragment(); newFragment.show(getFragmentManager(), &quot;datePicker&quot;); } } </code></pre> <p>I did have the classes in separate files but was testing different things hence why they are in the same file (I will move them back out again to separate files after I have managed to call the date picker).</p> <p>My question is, how would I call the date picker dialog from the button press?</p>
3
1,202
How do I convert a libGDX GWT game to version 1.9.5?
<p>I am trying to upgrade my game to libGDX 1.9.5. The game works fine on desktop, but when I try to build the HTML version I get the following error:</p> <pre><code>Configuration on demand is an incubating feature. :core:compileJava UP-TO-DATE :core:processResources UP-TO-DATE :core:classes UP-TO-DATE :core:jar UP-TO-DATE :html:compileJava UP-TO-DATE :html:processResources UP-TO-DATE :html:classes UP-TO-DATE :html:addSource :html:compileGwt Loading inherited module 'tech.otter.merchant.GdxDefinition' Loading inherited module 'com.badlogic.gdx.backends.gdx_backends_gwt' Loading inherited module 'com.google.gwt.user.User' Loading inherited module 'com.google.gwt.media.Media' Loading inherited module 'com.google.gwt.user.UI' Loading inherited module 'com.google.gwt.uibinder.UiBinder' [ERROR] Line 20: Unexpected element 'resource' [ERROR] Failure while parsing XML com.google.gwt.core.ext.UnableToCompleteException: (see previous log entries) at com.google.gwt.dev.util.xml.DefaultSchema.onUnexpectedElement(DefaultSchema.java:86) </code></pre> <p>Historically, the biggest challenges for me when using GWT have been VisUI and gdx-kiwi, but I have gone to their wikis and updated their versions in my gradle files shown below:</p> <p><strong>/build.gradle</strong></p> <pre><code>buildscript { repositories { mavenLocal() mavenCentral() maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } jcenter() } dependencies { classpath 'de.richsource.gradle.plugins:gwt-gradle-plugin:0.6' classpath 'com.android.tools.build:gradle:2.2.0' classpath "com.badlogicgames.gdx:gdx-tools:1.9.4" } } allprojects { apply plugin: "eclipse" apply plugin: "idea" version = '1.1' ext { appName = "merchant" gdxVersion = '1.9.5' roboVMVersion = '2.2.0' box2DLightsVersion = '1.4' ashleyVersion = '1.7.0' aiVersion = '1.8.0' kiwiVersion = '1.8.1.9.4' visVersion = '1.3.0-SNAPSHOT' } repositories { mavenLocal() mavenCentral() maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } maven { url "https://oss.sonatype.org/content/repositories/releases/" } } } project(":desktop") { apply plugin: "java" dependencies { compile project(":core") compile "com.badlogicgames.gdx:gdx-backend-lwjgl:$gdxVersion" compile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop" compile "com.badlogicgames.gdx:gdx-tools:$gdxVersion" compile "com.github.czyzby:gdx-kiwi:$kiwiVersion" } } project(":android") { apply plugin: "android" configurations { natives } dependencies { compile project(":core") compile "com.badlogicgames.gdx:gdx-backend-android:$gdxVersion" natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi" natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi-v7a" natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-arm64-v8a" natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86" natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86_64" compile "com.badlogicgames.gdx:gdx-ai:$aiVersion" } } project(":html") { apply plugin: "gwt" apply plugin: "war" dependencies { compile project(":core") compile "com.badlogicgames.gdx:gdx-backend-gwt:$gdxVersion" compile "com.badlogicgames.gdx:gdx:$gdxVersion:sources" compile "com.badlogicgames.gdx:gdx-backend-gwt:$gdxVersion:sources" compile "com.badlogicgames.gdx:gdx-ai:$aiVersion:sources" compile "com.github.czyzby:gdx-kiwi:$kiwiVersion:sources" compile "com.kotcrab.vis:vis-ui:$visVersion:sources" } } project(":core") { apply plugin: "java" dependencies { compile "com.badlogicgames.gdx:gdx:$gdxVersion" compile "com.badlogicgames.gdx:gdx-ai:$aiVersion" compile "com.github.czyzby:gdx-kiwi:$kiwiVersion" compile "com.kotcrab.vis:vis-ui:$visVersion" } } tasks.eclipse.doLast { delete ".project" } </code></pre> <p><strong>html/build.gradle</strong></p> <pre><code>apply plugin: "java" apply plugin: "jetty" gwt { gwtVersion='2.6.1' // Should match the gwt version used for building the gwt backend maxHeapSize="1G" // Default 256m is not enough for gwt compiler. GWT is HUNGRY minHeapSize="1G" src = files(file("src/")) // Needs to be in front of "modules" below. modules 'tech.otter.merchant.GdxDefinition' devModules 'tech.otter.merchant.GdxDefinitionSuperdev' project.webAppDirName = 'webapp' compiler { strict = true; enableClosureCompiler = true; disableCastChecking = true; } } task draftRun(type: JettyRunWar) { dependsOn draftWar dependsOn.remove('war') webApp=draftWar.archivePath daemon=true } task superDev(type: de.richsource.gradle.plugins.gwt.GwtSuperDev) { dependsOn draftRun doFirst { gwt.modules = gwt.devModules } } task dist(dependsOn: [clean, compileGwt]) { doLast { file("build/dist").mkdirs() copy { from "build/gwt/out" into "build/dist" } copy { from "webapp" into "build/dist" } copy { from "war" into "build/dist" } delete "../../madigan.github.io/merchant/" copy { from "build/dist" into "../../madigan.github.io/merchant/" } doGit } } task doGit(type: Exec) { commandLine 'git', '-C', '../../madigan.github.io', 'add', '.' commandLine 'git', '-C', '../../madigan.github.io', 'commit', '-m', '"Distribution."' commandLine 'git', '-C', '../../madigan.github.io', 'push' } draftWar { from "war" } task addSource &lt;&lt; { sourceSets.main.compileClasspath += files(project(':core').sourceSets.main.allJava.srcDirs) } tasks.compileGwt.dependsOn(addSource) tasks.draftCompileGwt.dependsOn(addSource) sourceCompatibility = 1.8 sourceSets.main.java.srcDirs = [ "src/" ] eclipse.project { name = appName + "-html" } </code></pre> <p>Any advice or tips on how to troubleshoot this error would be much appreciated.</p> <p><strong>[EDIT]</strong></p> <p>I read the release notes a little closer, and it says that I should change the GWT version to 2.8.0. Even when I do this, I still get the following error:</p> <pre><code>Configuration on demand is an incubating feature. :core:compileJava UP-TO-DATE :core:processResources UP-TO-DATE :core:classes UP-TO-DATE :core:jar UP-TO-DATE :html:compileJava UP-TO-DATE :html:processResources UP-TO-DATE :html:classes UP-TO-DATE :html:addSource :html:compileGwt Unknown argument: -XenableClosureCompiler Google Web Toolkit 2.8.0 Compiler [-logLevel (ERROR|WARN|INFO|TRACE|DEBUG|SPAM|ALL)] [-workDir dir] [-X[no]closureFormattedOutput] [-[no]compileReport] [-X[no]checkCasts] [-X[no]classMetadata] [-[no]draftCompile] [-[no]checkAssertions] [-XfragmentCount numFragments] [-XfragmentMerge numFragments] [-gen dir] [-[no]generateJsInteropExports] [-XmethodNameDisplayMode (NONE|ONLY_METHOD_NAME|ABBREVIATED|FULL)] [-Xnamespace (NONE|PACKAGE)] [-optimize level] [-[no]saveSource] [-setProperty name=value,value...] [-style (DETAILED|OBFUSCATED|PRETTY)] [-[no]failOnError] [-[no]validateOnly] [-sourceLevel [auto, 1.8]] [-localWorkers count] [-[no]incremental] [-war dir] [-deploy dir] [-extra dir] [-saveSourceOutput dir] module[s] where -logLevel The level of logging detail: ERROR, WARN, INFO, TRACE, DEBUG, SPAM or ALL (defaults to INFO) -workDir The compiler's working directory for internal use (must be writeable; defaults to a system temp dir) -X[no]closureFormattedOutput EXPERIMENTAL: Enables Javascript output suitable for post-compilation by Closure Compiler (defaults to OFF) -[no]compileReport Compile a report that tells the "Story of Your Compile". (defaults to OFF) -X[no]checkCasts EXPERIMENTAL: DEPRECATED: use jre.checks.checkLevel instead. (defaults to OFF) -X[no]classMetadata EXPERIMENTAL: Include metadata for some java.lang.Class methods (e.g. getName()). (defaults to ON) -[no]draftCompile Compile quickly with minimal optimizations. (defaults to OFF) -[no]checkAssertions Include assert statements in compiled output. (defaults to OFF) -XfragmentCount EXPERIMENTAL: Limits of number of fragments using a code splitter that merges split points. -XfragmentMerge DEPRECATED (use -XfragmentCount instead): Enables Fragment merging code splitter. -gen Debugging: causes normally-transient generated types to be saved in the specified directory -[no]generateJsInteropExports Generate exports for JsInterop purposes (defaults to OFF) -XmethodNameDisplayMode EXPERIMENTAL: Specifies method display name mode for chrome devtools: NONE, ONLY_METHOD_NAME, ABBREVIATED or FULL (defaults to NONE) -Xnamespace Puts most JavaScript globals into namespaces. Default: PACKAGE for -draftCompile, otherwise NONE -optimize Sets the optimization level used by the compiler. 0=none 9=maximum. -[no]saveSource Enables saving source code needed by debuggers. Also see -debugDir. (defaults to OFF) -setProperty Set the values of a property in the form of propertyName=value1[,value2...]. -style Script output style: DETAILED, OBFUSCATED or PRETTY (defaults to OBFUSCATED) -[no]failOnError Fail compilation if any input file contains an error. (defaults to ON) -[no]validateOnly Validate all source code, but do not compile. (defaults to OFF) -sourceLevel Specifies Java source level (defaults to 1.8) -localWorkers The number of local workers to use when compiling permutations -[no]incremental Compiles faster by reusing data from the previous compile. (defaults to OFF) -war The directory into which deployable output files will be written (defaults to 'war') -deploy The directory into which deployable but not servable output files will be written (defaults to 'WEB-INF/deploy' under the -war directory/jar, and may be the same as the -extra directory/jar) -extra The directory into which extra files, not intended for deployment, will be written -saveSourceOutput Overrides where source files useful to debuggers will be written. Default: saved with extras. and module[s] Specifies the name(s) of the module(s) to compile :html:compileGwt FAILED </code></pre> <p><strong>[EDIT #2]</strong></p> <p>Now that the flag is removed per @Colin Altworth's answer, I get the following error particular to vis-ui (again, updated to use the recommended version for libGDX 1.9.5):</p> <pre><code>:html:compileGwt Compiling module tech.otter.merchant.GdxDefinition Tracing compile failure path for type 'com.kotcrab.vis.ui.util.async.AsyncTask' [ERROR] Errors in 'jar:file:/home/john/.gradle/caches/modules-2/files-2.1/com.kotcrab.vis/vis-ui/1.3.0-SNAPSHOT/e5f8abbdc3524212158f65d63c9a28d226795f97/vis-ui-1.3.0-SNAPSHOT-sources.jar!/com/kotcrab/vis/ui/util/async/AsyncTask.java' [ERROR] Line 46: The constructor Thread(new Runnable(){}, String) is undefined [ERROR] Line 51: The method start() is undefined for the type Thread [ERROR] Aborting compile due to errors in some input files :html:compileGwt FAILED FAILURE: Build failed with an exception. </code></pre> <p><strong>[EDIT #3]</strong></p> <p>Turns out the rest of the issue was a bug in VisUI- the latest update tries to use the Thread class, which is not supported by GWT.</p>
3
5,035
Gunicorn + Supervisor configuration issue. Django project deployed on amazon ec2 + ubuntu + nginx
<p>I've been running a django project on an ubuntu ec2 instance with gunicorn and nginx. I know it was running for at least a couple days with no issues, but I just checked in on it a week after deployment, and it is no longer running. I get a 502 Bad Gateway error when I access the site. I put in my usual gunicorn command, <code>sudo gunicorn adventure_time.wsgi:application –b 127.0.0.1:8001</code> but all I get is </p> <pre><code>[2015-07-28 05:14:47 +0000] [11164] [INFO] Starting gunicorn 19.3.0 [2015-07-28 05:14:47 +0000] [11164] [ERROR] Connection in use: ('127.0.0.1', 8000) [2015-07-28 05:14:47 +0000] [11164] [ERROR] Retrying in 1 second. [2015-07-28 05:14:48 +0000] [11164] [ERROR] Connection in use: ('127.0.0.1', 8000) [2015-07-28 05:14:48 +0000] [11164] [ERROR] Retrying in 1 second. [2015-07-28 05:14:49 +0000] [11164] [ERROR] Connection in use: ('127.0.0.1', 8000) [2015-07-28 05:14:49 +0000] [11164] [ERROR] Retrying in 1 second. [2015-07-28 05:14:50 +0000] [11164] [ERROR] Connection in use: ('127.0.0.1', 8000) [2015-07-28 05:14:50 +0000] [11164] [ERROR] Retrying in 1 second. [2015-07-28 05:14:51 +0000] [11164] [ERROR] Connection in use: ('127.0.0.1', 8000) [2015-07-28 05:14:51 +0000] [11164] [ERROR] Retrying in 1 second. [2015-07-28 05:14:52 +0000] [11164] [ERROR] Can't connect to ('127.0.0.1', 8000) </code></pre> <p><code>netstat -tulpn</code> shows me this:</p> <pre><code>Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN - tcp 0 0 127.0.0.1:5432 0.0.0.0:* LISTEN - tcp 0 0 127.0.0.1:8000 0.0.0.0:* LISTEN - tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 11126/nginx: worker tcp6 0 0 :::22 :::* LISTEN - udp 0 0 0.0.0.0:68 0.0.0.0:* - udp 0 0 0.0.0.0:30444 0.0.0.0:* - udp6 0 0 :::63162 :::* - </code></pre> <p>So... it seems like nothing is running on 127.0.0.1:8000. Nothing for me to kill. (I've also tried <code>sudo pkill gunicorn</code>)Anyone got some tips on what I can do get my site running again? Also, why is it that gunicorn is still trying to connect to port 8000, but in my command I've asked it to connect to 8001? Thanks!!</p> <p>edit: I think it's more than just gunicorn. I'm also running supervisor, and I feel like that might be part of the issue.</p> <p>Inside my project folder is <code>gunicorn.conf.py</code></p> <pre><code>proc_name = "at_api" bind = '127.0.0.1:8001' loglevel = "error" workers = 2 </code></pre> <p>Inside my <code>/etc/supervisor/conf.d/at_api.conf</code></p> <pre><code>[group:at_api] programs=gunicorn_at_api [program:gunicorn_at_api] command=/home/ubuntu/.virtualenvs/adventure_time/bin/gunicorn -c gunicorn.conf.py -p gunicorn.pid wsgi:app\ lication --pythonpath directory=/home/ubuntu/at_api user=ubuntu autostart=true autorestart=true redirect_stderr=true </code></pre>
3
1,567
Why Elixir Guardian (DB) has Problems finding token?
<p>I have Problems to understand, how guardian works or handles errors, so in this example, I simply try to logout and get errors on the console..</p> <p>code:</p> <pre class="lang-ruby prettyprint-override"><code>def delete(conn, _params) do {:ok, claims} = Guardian.Plug.claims(conn) conn |&gt; Guardian.Plug.current_token |&gt; Guardian.revoke!(claims) conn |&gt; render("delete.json") end </code></pre> <p>Somehow the token is not found even there is the session deleted, the user logged out. I have problems to debug the code. How can I find errors or debug the code better?</p> <p>error message:</p> <pre><code>[error] #PID&lt;0.2061.0&gt; running PhoenixExample.Endpoint terminated Server: 127.0.0.1:4000 (http) Request: DELETE /api/v1/sessions ** (exit) an exception was raised: ** (Ecto.StaleEntryError) attempted to delete a stale struct: %GuardianDb.Token{__meta__: #Ecto.Schema.Metadata&lt;:loaded, "guardian_tokens"&gt;, aud: "User:96900", claims: %{"aud" =&gt; "User:96900", "exp" =&gt; 1474754356, "iat" =&gt; 1472162356, "iss" =&gt; "PhoenixExample", "jti" =&gt; "8947def5-ec3e-46e1-866d-2a1e9e16fd1f", "pem" =&gt; %{}, "sub" =&gt; "User:96900", "typ" =&gt; "token"}, exp: 1474754356, inserted_at: #Ecto.DateTime&lt;2016-08-25 21:59:16&gt;, iss: "PhoenixExample", jti: "8947def5-ec3e-46e1-866d-2a1e9e16fd1f", jwt: "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJVc2VyOjk2OTAwIiwiZXhwIjoxNDc0NzU0MzU2LCJpYXQiOjE0NzIxNjIzNTYsImlzcyI6IkNhbGx5YWNvcmUiLCJqdGkiOiI4OTQ3ZGVmNS1lYzNlLTQ2ZTEtODY2ZC0yYTFlOWUxNmZkMWYiLCJwZW0iOnt9LCJzdWIiOiJVc2VyOjk2OTAwIiwidHlwIjoidG9rZW4ifQ.BTYn7wjPlosztNmy3DKeRExzwBOiUG_ZLBJqUzUinDIpEl0xvUnb3EzYM7VaBpIT__JtVfZ0t7XET9D0LK0eMg", sub: "User:96900", typ: "token", updated_at: #Ecto.DateTime&lt;2016-08-25 21:59:16&gt;} (ecto) lib/ecto/repo/schema.ex:397: Ecto.Repo.Schema.apply/4 (ecto) lib/ecto/repo/schema.ex:341: anonymous fn/9 in Ecto.Repo.Schema.do_delete/4 lib/guardian_db.ex:98: GuardianDb.on_revoke/2 (guardian) lib/guardian.ex:131: Guardian.revoke!/3 (phoenixexample) web/controllers/api/v1/session_controller.ex:30: PhoenixExample.SessionController.delete/2 (phoenixexample) web/controllers/api/v1/session_controller.ex:1: PhoenixExample.SessionController.action/2 (phoenixexample) web/controllers/api/v1/session_controller.ex:1: PhoenixExample.SessionController.phoenix_controller_pipeline/2 (phoenixexample) lib/phoenixexample/endpoint.ex:1: PhoenixExample.Endpoint.instrument/4 (phoenixexample) lib/phoenix/router.ex:261: PhoenixExample.Router.dispatch/2 (phoenixexample) web/router.ex:1: PhoenixExample.Router.do_call/2 (phoenixexample) lib/phoenixexample/endpoint.ex:1: PhoenixExample.Endpoint.phoenix_pipeline/1 (phoenixexample) lib/plug/debugger.ex:122: PhoenixExample.Endpoint."call (overridable 3)"/2 (phoenixexample) lib/phoenixexample/endpoint.ex:1: PhoenixExample.Endpoint.call/2 (plug) lib/plug/adapters/cowboy/handler.ex:15: Plug.Adapters.Cowboy.Handler.upgrade/4 (cowboy) src/cowboy_protocol.erl:442: :cowboy_protocol.execute/4 </code></pre> <p>conn (inspected)</p> <pre><code>%Plug.Conn{adapter: {Plug.Adapters.Cowboy.Conn, :...}, assigns: %{}, before_send: [#Function&lt;1.66364769/1 in Plug.Logger.call/2&gt;, #Function&lt;0.78287744/1 in Phoenix.LiveReloader.before_send_inject_reloader/1&gt;], body_params: %{}, cookies: %Plug.Conn.Unfetched{aspect: :cookies}, halted: false, host: "127.0.0.1", method: "DELETE", owner: #PID&lt;0.2060.0&gt;, params: %{}, path_info: ["api", "v1", "sessions"], peer: {{127, 0, 0, 1}, 63006}, port: 4000, private: %{PhoenixExample.Router =&gt; {[], %{}}, :guardian_default_claims =&gt; {:ok, %{"aud" =&gt; "User:96900", "exp" =&gt; 1474754356, "iat" =&gt; 1472162356, "iss" =&gt; "PhoenixExample", "jti" =&gt; "8947def5-ec3e-46e1-866d-2a1e9e16fd1f", "pem" =&gt; %{}, "sub" =&gt; "User:96900", "typ" =&gt; "token"}}, :guardian_default_jwt =&gt; "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJVc2VyOjk2OTAwIiwiZXhwIjoxNDc0NzU0MzU2LCJpYXQiOjE0NzIxNjIzNTYsImlzcyI6IkNhbGx5YWNvcmUiLCJqdGkiOiI4OTQ3ZGVmNS1lYzNlLTQ2ZTEtODY2ZC0yYTFlOWUxNmZkMWYiLCJwZW0iOnt9LCJzdWIiOiJVc2VyOjk2OTAwIiwidHlwIjoidG9rZW4ifQ.BTYn7wjPlosztNmy3DKeRExzwBOiUG_ZLBJqUzUinDIpEl0xvUnb3EzYM7VaBpIT__JtVfZ0t7XET9D0LK0eMg", :guardian_default_resource =&gt; %PhoenixExample.User{__meta__: #Ecto.Schema.Metadata&lt;:loaded, "users"&gt;, account: nil, address: nil, approved: false, city: nil, country: nil, description: nil, email: "radosch@me.com", encrypted_password: "$2b$12$E8AOMRI6pVHLIuumenHMSOfCR8TRK4.HYaCSGQvrobgTYkWBdcV7m", firstname: nil, guid: nil, id: 96900, inserted_at: #Ecto.DateTime&lt;2016-08-05 01:06:19&gt;, is_provider: false, lastname: nil, password: nil, postcode: nil, tags: nil, updated_at: #Ecto.DateTime&lt;2016-08-05 01:06:19&gt;, username: "radosch"}, :phoenix_action =&gt; :delete, :phoenix_controller =&gt; PhoenixExample.SessionController, :phoenix_endpoint =&gt; PhoenixExample.Endpoint, :phoenix_format =&gt; "json", :phoenix_layout =&gt; {PhoenixExample.LayoutView, :app}, :phoenix_pipelines =&gt; [:api], :phoenix_route =&gt; #Function&lt;61.48695856/1 in PhoenixExample.Router.match_route/4&gt;, :phoenix_router =&gt; PhoenixExample.Router, :phoenix_view =&gt; PhoenixExample.SessionView, :plug_session_fetch =&gt; #Function&lt;1.82590416/1 in Plug.Session.fetch_session/1&gt;}, query_params: %{}, query_string: "", remote_ip: {127, 0, 0, 1}, req_cookies: %Plug.Conn.Unfetched{aspect: :cookies}, req_headers: [{"host", "127.0.0.1:4000"}, {"content-length", "0"}, {"connection", "keep-alive"}, {"accept", "*/*"}, {"user-agent", "CallYa/1 CFNetwork/808.0.1 Darwin/16.0.0"}, {"accept-language", "de-ch"}, {"authorization", "Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJVc2VyOjk2OTAwIiwiZXhwIjoxNDc0NzU0MzU2LCJpYXQiOjE0NzIxNjIzNTYsImlzcyI6IkNhbGx5YWNvcmUiLCJqdGkiOiI4OTQ3ZGVmNS1lYzNlLTQ2ZTEtODY2ZC0yYTFlOWUxNmZkMWYiLCJwZW0iOnt9LCJzdWIiOiJVc2VyOjk2OTAwIiwidHlwIjoidG9rZW4ifQ.BTYn7wjPlosztNmy3DKeRExzwBOiUG_ZLBJqUzUinDIpEl0xvUnb3EzYM7VaBpIT__JtVfZ0t7XET9D0LK0eMg"}, {"accept-encoding", "gzip, deflate"}], request_path: "/api/v1/sessions", resp_body: nil, resp_cookies: %{}, resp_headers: [{"cache-control", "max-age=0, private, must-revalidate"}, {"x-request-id", "bn5l49vfieh6mra9sq4toa9afcocq5c9"}], scheme: :http, script_name: [], secret_key_base: "A2LVGKIq88H3nrx6cx4PC7uWf/AAe9zcjwfCRFTx1X5xQ5KNvlLTzfxbGQxQctdb", state: :unset, status: nil} %Plug.Conn{adapter: {Plug.Adapters.Cowboy.Conn, :...}, assigns: %{}, before_send: [#Function&lt;1.66364769/1 in Plug.Logger.call/2&gt;, #Function&lt;0.78287744/1 in Phoenix.LiveReloader.before_send_inject_reloader/1&gt;], body_params: %{}, cookies: %Plug.Conn.Unfetched{aspect: :cookies}, halted: false, host: "127.0.0.1", method: "DELETE", owner: #PID&lt;0.2061.0&gt;, params: %{}, path_info: ["api", "v1", "sessions"], peer: {{127, 0, 0, 1}, 63007}, port: 4000, private: %{PhoenixExample.Router =&gt; {[], %{}}, :guardian_default_claims =&gt; {:ok, %{"aud" =&gt; "User:96900", "exp" =&gt; 1474754356, "iat" =&gt; 1472162356, "iss" =&gt; "PhoenixExample", "jti" =&gt; "8947def5-ec3e-46e1-866d-2a1e9e16fd1f", "pem" =&gt; %{}, "sub" =&gt; "User:96900", "typ" =&gt; "token"}}, :guardian_default_jwt =&gt; "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJVc2VyOjk2OTAwIiwiZXhwIjoxNDc0NzU0MzU2LCJpYXQiOjE0NzIxNjIzNTYsImlzcyI6IkNhbGx5YWNvcmUiLCJqdGkiOiI4OTQ3ZGVmNS1lYzNlLTQ2ZTEtODY2ZC0yYTFlOWUxNmZkMWYiLCJwZW0iOnt9LCJzdWIiOiJVc2VyOjk2OTAwIiwidHlwIjoidG9rZW4ifQ.BTYn7wjPlosztNmy3DKeRExzwBOiUG_ZLBJqUzUinDIpEl0xvUnb3EzYM7VaBpIT__JtVfZ0t7XET9D0LK0eMg", :guardian_default_resource =&gt; %PhoenixExample.User{__meta__: #Ecto.Schema.Metadata&lt;:loaded, "users"&gt;, account: nil, address: nil, approved: false, city: nil, country: nil, description: nil, email: "radosch@me.com", encrypted_password: "$2b$12$E8AOMRI6pVHLIuumenHMSOfCR8TRK4.HYaCSGQvrobgTYkWBdcV7m", firstname: nil, guid: nil, id: 96900, inserted_at: #Ecto.DateTime&lt;2016-08-05 01:06:19&gt;, is_provider: false, lastname: nil, password: nil, postcode: nil, tags: nil, updated_at: #Ecto.DateTime&lt;2016-08-05 01:06:19&gt;, username: "radosch"}, :phoenix_action =&gt; :delete, :phoenix_controller =&gt; PhoenixExample.SessionController, :phoenix_endpoint =&gt; PhoenixExample.Endpoint, :phoenix_format =&gt; "json", :phoenix_layout =&gt; {PhoenixExample.LayoutView, :app}, :phoenix_pipelines =&gt; [:api], :phoenix_route =&gt; #Function&lt;61.48695856/1 in PhoenixExample.Router.match_route/4&gt;, :phoenix_router =&gt; PhoenixExample.Router, :phoenix_view =&gt; PhoenixExample.SessionView, :plug_session_fetch =&gt; #Function&lt;1.82590416/1 in Plug.Session.fetch_session/1&gt;}, query_params: %{}, query_string: "", remote_ip: {127, 0, 0, 1}, req_cookies: %Plug.Conn.Unfetched{aspect: :cookies}, req_headers: [{"host", "127.0.0.1:4000"}, {"content-length", "0"}, {"connection", "keep-alive"}, {"accept", "*/*"}, {"user-agent", "CallYa/1 CFNetwork/808.0.1 Darwin/16.0.0"}, {"accept-language", "de-ch"}, {"authorization", "Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJVc2VyOjk2OTAwIiwiZXhwIjoxNDc0NzU0MzU2LCJpYXQiOjE0NzIxNjIzNTYsImlzcyI6IkNhbGx5YWNvcmUiLCJqdGkiOiI4OTQ3ZGVmNS1lYzNlLTQ2ZTEtODY2ZC0yYTFlOWUxNmZkMWYiLCJwZW0iOnt9LCJzdWIiOiJVc2VyOjk2OTAwIiwidHlwIjoidG9rZW4ifQ.BTYn7wjPlosztNmy3DKeRExzwBOiUG_ZLBJqUzUinDIpEl0xvUnb3EzYM7VaBpIT__JtVfZ0t7XET9D0LK0eMg"}, {"accept-encoding", "gzip, deflate"}], request_path: "/api/v1/sessions", resp_body: nil, resp_cookies: %{}, resp_headers: [{"cache-control", "max-age=0, private, must-revalidate"}, {"x-request-id", "u3c2qbajf1a0fofhlg7hl4aa57gttqrl"}], scheme: :http, script_name: [], secret_key_base: "A2LVGKIq88H3nrx6cx4PC7uWf/AAe9zcjwfCRFTx1X5xQ5KNvlLTzfxbGQxQctdb", state: :unset, status: nil} </code></pre>
3
4,996
iOS - AudioFormat issue linking up mixer, remoteio and dynamics processor
<p>I'm trying to link up my mixer -> remoteio -> dynamics processor</p> <p>Here is my AudioFormat // Describe format</p> <pre><code>memset( &amp;audioFormat, 0, sizeof(AudioStreamBasicDescription) ); audioFormat.mSampleRate = 44100.00; audioFormat.mFormatID = kAudioFormatLinearPCM; audioFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked; audioFormat.mFramesPerPacket = 1; audioFormat.mChannelsPerFrame = 1; audioFormat.mBitsPerChannel = 16; audioFormat.mBytesPerPacket = 2; audioFormat.mBytesPerFrame = 2; </code></pre> <p>When I use CAShow it gives me the following. </p> <pre><code>AudioUnitGraph 0x4725000: Member Nodes: node 1: 'auou' 'rioc' 'appl', instance 0x1c5ab3a0 O I node 2: 'aumx' 'mcmx' 'appl', instance 0x1d07a6d0 O I node 3: 'aufx' 'dcmp' 'appl', instance 0x1d085330 O I Connections: node 2 bus 0 =&gt; node 1 bus 0 [ 2 ch, 44100 Hz, 'lpcm' (0x00000C2C) 8.24-bit little-endian signed integer, deinterleaved] node 1 bus 0 =&gt; node 3 bus 0 [ 2 ch, 0 Hz, 'lpcm' (0x00000029) 32-bit little-endian float, deinterleaved] </code></pre> <p>Trying result = AudioUnitSetProperty ( _dynamicsUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &amp;audioFormat, sizeof (audioFormat) );</p> <p>to set the audioFormat to the desired format gives me a error code -10868.</p> <p>I also realised that getting the ASBD from the audynamicsprocessor yields this. </p> <pre><code>effectASBD AudioStreamBasicDescription mSampleRate Float64 44100 mFormatID UInt32 1819304813 mFormatFlags UInt32 41 mBytesPerPacket UInt32 4 mFramesPerPacket UInt32 1 mBytesPerFrame UInt32 4 mChannelsPerFrame UInt32 2 mBitsPerChannel UInt32 32 mReserved UInt32 0 </code></pre> <p>and I tried various things like letting the audioformat ABSD be as per the AUdynamicsprocessor but I get the same error. </p> <p>I would like to use my original audioformat ASBD as far as possible due to latency considerations. Also, my callback algorithms are already written for that audioformat. Is this possible? </p> <p>Thanks in advance. </p> <p>Pier. </p>
3
1,125
mySQL returns empty even though it shouldn't?
<p>am a total mySQL newbie, but I have no idea how to search for the answer to this, so that's why I'm bringing it here:</p> <pre><code> DESCRIBE rParam; +----------------+---------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------------+---------------+------+-----+---------+-------+ | p | float | YES | | NULL | | | d | float | YES | | NULL | | | LTP | float | YES | | NULL | | | LTD | float | YES | | NULL | | | alpha | float | YES | | NULL | | | N | smallint(6) | YES | | NULL | | | g | float | YES | | NULL | | | a | float | YES | | NULL | | | seed | float | YES | | NULL | | | startingWeight | float | YES | | NULL | | | path | varchar(1000) | YES | UNI | NULL | | | type | varchar(100) | YES | | NULL | | +----------------+---------------+------+-----+---------+-------+ 12 rows in set (0.00 sec) SELECT p FROM rParam GROUP BY p; +--------+ | p | +--------+ | 0 | | 0.001 | | 0.002 | | 0.003 | | 0.004 | | 0.005 | | 0.0075 | | 0.008 | | 0.01 | | 0.012 | | 0.0125 | | 0.014 | | 0.015 | | 0.02 | | 0.025 | | 0.03 | | 0.035 | | 0.04 | | 0.05 | | 0.1 | | 0.2 | | 0.3 | | 0.4 | | 0.5 | | 0.6 | | 0.7 | +--------+ 26 rows in set (0.00 sec) </code></pre> <p>I can get the results for one type of query:</p> <pre><code> SELECT p FROM rParam WHERE p=0.5 GROUP BY p; +------+ | p | +------+ | 0.5 | +------+ 1 row in set (0.00 sec) </code></pre> <p>However, changing the p-value that I'm asking for:</p> <pre><code> SELECT p FROM rParam WHERE p=0.6 GROUP BY p; Empty set (0.00 sec) </code></pre> <p>but we can clearly see from the first output that there are rows for which p=0.6? This is a problem for most of the p-values - why does mySQL return the empty set?</p>
3
1,767
Issues with time() when running a C musl application in docker container on arm
<p>My application is unable to handle time operations like <a href="https://linux.die.net/man/2/time" rel="nofollow noreferrer">time(2)</a> when it runs in alpine docker container on an arm device.</p> <p>What I have: I am building a native c application which is statically linked to musl with toolchain from musl.cc (arm-linux-musleabihf-gcc). I am using latest alpine container (without image tag).</p> <p>How it behaves:</p> <ul> <li>Running binary directly on arm device works as expected</li> <li>Running in alpine container on x64 device works as expected</li> <li>Running in alpine container on arm device does <strong>not</strong> work</li> </ul> <p>What's going wrong:</p> <ul> <li><code>time(NULL);</code> returns ((time_t) -1) and error=1: &quot;Operation not permitted&quot;</li> <li>The timestamps in the log outputs have cranked timestamps</li> <li>SSH handshake fails because the validity of the remote certificate is in the future.</li> </ul> <p>However, if I execute <code>date</code> in container's ash the output is valid. Thus, there seems to be a problem that only occurs in alpine containers on the ARM architecture. Funnily enough, I'm switching from Ubuntu to Alpine as we had <a href="https://bugs.launchpad.net/cloud-images/+bug/1896443" rel="nofollow noreferrer">similar problems</a> there.</p> <p>Does anyone have any idea what I am doing wrong?</p> <p>Update #1: Same problem on ubuntu. So the problem seems to be on any docker basis image but only on arm devices.</p> <p>Update #2: Here is a minimal example <strong>TimeTest.c</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &quot;time.h&quot; #include &quot;errno.h&quot; int main() { printf(&quot;hallo\n&quot;); time_t myTime; time_t result = time(&amp;myTime); printf(&quot;result: %lld\n&quot;, result); if ((long)result &lt; 0) { printf(&quot;time() error=%d: %s\n&quot;, errno, strerror(errno)); } else { struct tm* tm_info = localtime(&amp;myTime); printf(&quot;Current local time and date: %s\n&quot;, asctime(tm_info)); } return 0; } </code></pre> <p><strong>CMakeLists.txt</strong></p> <pre><code>cmake_minimum_required (VERSION 3.8) project (&quot;TimeTest&quot;) if(BUILD_TARGET STREQUAL &quot;ARM_MUSL&quot;) set(CMAKE_SYSTEM_PROCESSOR arm) set(CMAKE_C_COMPILER /usr/bin/arm-linux-musleabi-gcc) set(CMAKE_EXE_LINKER_FLAGS &quot;${CMAKE_EXE_LINKER_FLAGS} -fno-stack-protector -mfloat-abi=softfp -static --static&quot;) set(CMAKE_LINK_SEARCH_END_STATIC TRUE) endif() add_executable (TimeTest &quot;TimeTest.c&quot;) </code></pre> <p><strong>Output on arm device</strong></p> <pre><code>pi@raspberrypi:/tmp $ docker run --rm -it -v /tmp/TimeTest:/TimeTest alpine ash / # /TimeTest hallo result: -4696377169665647048 time() error=1: Operation not permitted </code></pre>
3
1,112
Tons of timeouts from Node.JS Express API hosted on Nginx behind Cloudflare
<p>I have a Node.JS Express API (MySQL) hosted on Nginx behind Cloudflare (2 instances running). I'm getting a lot of 504 timeout on Roblox and upstream timed out on Nginx. I have never seen a request I sent with Postman fail. I think it happens more under load. These instances are processing processing 11M requests a week. This is hosted on a 16 core, 64 GB RAM, dedicated server with 2-3 load average</p> <p><strong>Nginx error log spams these:</strong></p> <ul> <li>upstream timed out (110: Connection timed out) while reading response header from upstream</li> <li>no live upstreams while connecting to upstream</li> <li>upstream prematurely closed connection while reading response header from upstream</li> </ul> <p>The upstream timed out errors are the concern as they are the majority of the errors.</p> <p>Generally, I don't do too much processing on the API. I have less then a dozen endpoints that are mostly simple DB selects.</p> <p><strong>Can someone direct me in the right area to resolve this?</strong> Is it my Nginx config, do I need more instances, is it my design, is it Roblox, is it Cloudflare? I read Node.js can handle this (under one instance), so I tried to adjust worker connections in Nginx which caused more no live upstream errors. I cannot wrap my head around what the bottle neck is.</p> <p><strong>Site Config</strong></p> <pre><code> proxy_cache_path /tmp/NGINX_cache/ keys_zone=backcache:10m; map $http_upgrade $connection_upgrade { default upgrade; ' ' close; } upstream nodejs { # Use IP Hash for session persistence ip_hash; keepalive 90; # List of Node.js application servers server localhost:9000; server localhost:9001; } # HTTP: www and non-www to https server { listen 80; listen [::]:80; server_name example.com www.example.com; return 301 https://example.com$request_uri; } # HTTPS: non-www to www server { listen 443 ssl; listen [::]:443 ssl; ssl_certificate /example/example.com.cert.pem; ssl_certificate_key /example/example.com.key.pem; server_name example.com; return 301 https://www.example.com$request_uri; } # HTTPS: www server { listen 443 ssl http2; listen [::]:443 ssl http2; ssl_certificate /example/example.com.cert.pem; ssl_certificate_key /example/example.com.key.pem; server_name www.example.com; location / { return 301 $scheme://www.example.example$request_uri; } location /api { proxy_pass https://nodejs; proxy_cache backcache; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; proxy_read_timeout 90; proxy_redirect https://nodejs https://www.example.com; } location /api_staging { proxy_pass https://localhost:8000; proxy_cache backcache; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; proxy_read_timeout 90; proxy_redirect https://localhost:8000 https://www.example.com; } location /api_development { proxy_pass https://localhost:7000; proxy_cache backcache; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; proxy_read_timeout 90; proxy_redirect https://localhost:7000 https://www.example.com; } } </code></pre> <p><strong>Nginx Config</strong></p> <pre><code> user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 1000; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; client_max_body_size 100M; } #mail { # # See sample authentication script at: # # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript # # # auth_http localhost/auth.php; # # pop3_capabilities &quot;TOP&quot; &quot;USER&quot;; # # imap_capabilities &quot;IMAP4rev1&quot; &quot;UIDPLUS&quot;; # # server { # listen localhost:110; # protocol pop3; # proxy on; # } # # server { # listen localhost:143; # protocol imap; # proxy on; # } #} </code></pre> <p><strong>Cloudflare Edits</strong></p> <ul> <li>Proxied is on</li> <li>Full strict SSL</li> <li>All Roblox IPs are allowed through firewall</li> </ul>
3
2,792
Observable loses value after call to applyBindings
<p>I am working on this <a href="http://jsfiddle.net/StrandedPirate/yjhz6bvj/" rel="nofollow noreferrer">fiddle</a> trying to isolate a problem I'm having with the value not being set on a <code>select</code> element and now I'm stuck with nonsensical behavior in jsfiddle. I can't tell if this issue is my underlying problem or if this is a bug in jsfiddle.</p> <p>First I'm using inheritance with my view models as described here: <a href="http://www.bennadel.com/blog/1566-using-super-constructors-is-critical-in-prototypal-inheritance-in-javascript.htm" rel="nofollow noreferrer">Using Super Constructors Is Critical In Prototypal Inheritance In Javascript </a>. Perhaps this article has led me down the wrong path, I don't know. Bottom line is that I need to do inheritance. </p> <p>Second the problem with this particular fiddle is that after the call to <code>ko.applyBindings</code> my observable just loses its value (becomes <code>undefined</code>) and then out of no where gets set to <code>1</code>.</p> <p><img src="https://i.stack.imgur.com/0EOUZ.png" alt="enter image description here"></p> <pre><code>function userAddressModelBase(data) { var self = this; self.states = ko.observableArray(data.states); } userAddressModel.prototype = new userAddressModelBase({}); userAddressModel.constructor = userAddressModel; function userAddressModel(data) { var self = this; userAddressModelBase.call(self, data); self.sampleText = ko.observable("i'm here"); console.log("data.selectedStateId is: " + data.selectedStateId); self.selectedStateId = ko.observable(data.selectedStateId); console.log("self.selectedStateId is: " + self.selectedStateId()); self.getStates = function () { console.log("getStates running..."); window.setTimeout(function () { console.log("getStates callback..."); self.states([new stateModel({ id: 1, name: "New York" }), new stateModel({ id: 2, name: "Texas" }), new stateModel({ id: 3, name: "California" }), new stateModel({ id: 4, name: "Ohio" })]); console.log(ko.toJS(self)); console.log("getStates callback self.selectedStateId is: " + self.selectedStateId()); }, 1000); }; //console.log("self.selectedStateId is: " + self.selectedStateId()); //self.getStates(); //console.log("self.selectedStateId is: " + self.selectedStateId()); } function stateModel(data) { var self = this; self.id = ko.observable(data.id); self.name = ko.observable(data.name); } var model = new userAddressModel({ selectedStateId: 3 }); console.log(ko.toJS(model)); console.log("before applyBindings model.selectedStateId is: " + model.selectedStateId()); console.log("appling bindings..."); ko.applyBindings(model); // selectedStateId is now undefined!!! console.log("appling bindings finished."); console.log(ko.toJS(model)); console.log("after applyBindings model.selectedStateId is: " + model.selectedStateId()); model.getStates(); // selectedStateId is now 1 after this finishes!!! </code></pre>
3
1,194
Extract values conditionally from namespaced XML using XPath
<p>I need to extract some info from a XML using XPath ... the XML is like the following ...</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;feed xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" &gt; &lt;title type="text"&gt;DataEntities&lt;/title&gt; &lt;m:count&gt;4&lt;/m:count&gt; &lt;entry&gt; &lt;id&gt;0001&lt;/id&gt; &lt;title type="text"&gt;DataEntities&lt;/title&gt; &lt;content type="application/xml"&gt; &lt;m:properties&gt; &lt;d:internalId&gt;5b1daf597f3aee4f0d93e1ed&lt;/d:internalId&gt; &lt;d:datasetVersion&gt;2&lt;/d:datasetVersion&gt; &lt;d:Product&gt;PRODUCT0001&lt;/d:Product&gt; &lt;d:Version&gt;6.0.0&lt;/d:Version&gt; &lt;d:Middleware&gt;Apache WebServer&lt;/d:Middleware&gt; &lt;d:Versionmiddleware&gt;2.2.31&lt;/d:Versionmiddleware&gt; &lt;d:Hostname&gt;server01.mydomain.com&lt;/d:Hostname&gt; &lt;d:Technology&gt;PHP&lt;/d:Technology&gt; &lt;/m:properties&gt; &lt;/content&gt; &lt;/entry&gt; &lt;entry&gt; &lt;id&gt;0002&lt;/id&gt; &lt;title type="text"&gt;DataEntities&lt;/title&gt; &lt;content type="application/xml"&gt; &lt;m:properties&gt; &lt;d:internalId&gt;5b1daf345f3aee4f0d34e1ed&lt;/d:internalId&gt; &lt;d:datasetVersion&gt;2&lt;/d:datasetVersion&gt; &lt;d:Product&gt;PRODUCT0002&lt;/d:Product&gt; &lt;d:Version&gt;1.0.0&lt;/d:Version&gt; &lt;d:Middleware&gt;Apache WebServer&lt;/d:Middleware&gt; &lt;d:Versionmiddleware&gt;2.2.31&lt;/d:Versionmiddleware&gt; &lt;d:Hostname&gt;server02.mydomain.com&lt;/d:Hostname&gt; &lt;d:Technology&gt;Java&lt;/d:Technology&gt; &lt;/m:properties&gt; &lt;/content&gt; &lt;/entry&gt; &lt;entry&gt; &lt;id&gt;0003&lt;/id&gt; &lt;title type="text"&gt;DataEntities&lt;/title&gt; &lt;content type="application/xml"&gt; &lt;m:properties&gt; &lt;d:internalId&gt;5b1daf123f3aee4f0d33e1ed&lt;/d:internalId&gt; &lt;d:datasetVersion&gt;2&lt;/d:datasetVersion&gt; &lt;d:Product&gt;PRODUCT0003&lt;/d:Product&gt; &lt;d:Version&gt;5.0.0&lt;/d:Version&gt; &lt;d:Middleware&gt;Apache WebServer&lt;/d:Middleware&gt; &lt;d:Versionmiddleware&gt;2.2.31&lt;/d:Versionmiddleware&gt; &lt;d:Hostname&gt;server01.mydomain.com&lt;/d:Hostname&gt; &lt;d:Technology&gt;PHP&lt;/d:Technology&gt; &lt;/m:properties&gt; &lt;/content&gt; &lt;/entry&gt; &lt;entry&gt; &lt;id&gt;0004&lt;/id&gt; &lt;title type="text"&gt;DataEntities&lt;/title&gt; &lt;content type="application/xml"&gt; &lt;m:properties&gt; &lt;d:internalId&gt;5b1daf345f3aee4f0d34e1ed&lt;/d:internalId&gt; &lt;d:datasetVersion&gt;2&lt;/d:datasetVersion&gt; &lt;d:Product&gt;PRODUCT0004&lt;/d:Product&gt; &lt;d:Version&gt;4.0.0&lt;/d:Version&gt; &lt;d:Middleware&gt;Apache WebServer&lt;/d:Middleware&gt; &lt;d:Versionmiddleware&gt;2.2.31&lt;/d:Versionmiddleware&gt; &lt;d:Hostname&gt;server01.mydomain.com&lt;/d:Hostname&gt; &lt;d:Technology&gt;PHP&lt;/d:Technology&gt; &lt;/m:properties&gt; &lt;/content&gt; &lt;/entry&gt; &lt;/feed&gt; </code></pre> <p><strong>What I need is to find the products that are on the same hostname,</strong> for example fixing the server like "server01.mydomain.com" to extract, as result, PRODUCT0001, PRODUCT0003 and PRODUCT0004 (note NOT PRODUCT0002), or, fixing the server like "server02.mydomain.com" to extract , as result, only PRODUCT0002.</p> <p>I've tried to use</p> <pre><code>//d:Product </code></pre> <p>and it works and the result is</p> <pre><code>Element='&lt;d:Product xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices"&gt;PRODUCT0001&lt;/d:Product&gt;' Element='&lt;d:Product xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices"&gt;PRODUCT0002&lt;/d:Product&gt;' Element='&lt;d:Product xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices"&gt;PRODUCT0003&lt;/d:Product&gt;' Element='&lt;d:Product xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices"&gt;PRODUCT0004&lt;/d:Product&gt;' </code></pre> <p>I don't know how to indicate that I need "only" the products that are on the <code>d:Hostname</code> value "server01.mydomain.com"</p> <p>I've tried using </p> <pre><code>//d:Product/@d:Hostname['server01.mydomain.com'] </code></pre> <p>but it doesn't work.</p> <p>Any suggestions about the XPath syntax I have to use?</p>
3
2,449
add jsr80 on maven
<p>I am trying to add jsr80 with maven on eclipse on linux(Lubuntu).</p> <p>My pom.xml is</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven- 4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;Source.Web.java&lt;/groupId&gt; &lt;artifactId&gt;EjemploMaven&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;packaging&gt;jar&lt;/packaging&gt; &lt;name&gt;EjemploMaven&lt;/name&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;jsr80&lt;/groupId&gt; &lt;artifactId&gt;jsr80&lt;/artifactId&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;scope&gt;system&lt;/scope&gt; &lt;systemPath&gt;${basedir}/lib/jsr80.jar&lt;/systemPath&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;jsr80_ri&lt;/groupId&gt; &lt;artifactId&gt;jsr80_ri&lt;/artifactId&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;scope&gt;system&lt;/scope&gt; &lt;systemPath&gt;${basedir}/lib/jsr80_ri.jar&lt;/systemPath&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;jsr80_environment&lt;/groupId&gt; &lt;artifactId&gt;jsr80_environment&lt;/artifactId&gt; &lt;version&gt;1.0.1&lt;/version&gt; &lt;scope&gt;system&lt;/scope&gt; &lt;systemPath&gt;${basedir}/lib/${jsr80.env}&lt;/systemPath&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;log4j&lt;/groupId&gt; &lt;artifactId&gt;log4j&lt;/artifactId&gt; &lt;version&gt;1.2.16&lt;/version&gt; &lt;scope&gt;compile&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; </code></pre> <p> </p> <p>I have tried mvn clean, mvn update dependeces ... Log4j it's addes fine</p> <p>The error message is </p> <pre><code>Missing artifact jsr80:jsr80:jar:1.0:system Missing artifact jsr80_ri:jsr80_ri:jar:1.0:system Missing artifact jsr80_environment:jsr80_environment:jar:1.0.1:system </code></pre> <p>Thanks</p>
3
1,100
wxpython Segmentation Fault when deleting item from ListCtrl
<p>Whenever the program reach <code>self.DeleteItem</code> it crashes and print <code>Segmentation Fault (Core Dumped)</code>. After removing <code>self.DeleteItem</code> it does not crash anymore but we lose the ability to remove a row. I am not sure what is wrong with this as it is only one line that is broken. Can you help me see if anything is wrong?</p> <p><strong>Code</strong></p> <pre><code>import wx from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin from scrapy.crawler import CrawlerProcess from spider.spider import WIPOSpider from settings import settings from processor import process_xls class MainFrame(wx.Frame): TITLE = 'Neko' FRAME_MIN_SIZE = (820, 220) DEFAULT_BORDER_SIZE = 10 ADD_LABEL = 'Add' REMOVE_LABEL = 'Remove' START_LABEL = 'Start' FILE_LABEL = 'File' SIZE_LABEL = 'Size' PERCENT_LABEL = 'Percent' ETA_LABEL = 'ETA' SPEED_LABEL = 'Speed' STATUS_LABEL = 'Status' STATUS_LIST = { 'filename': (0, FILE_LABEL, 300, False), 'size': (1, SIZE_LABEL, 80, False), 'percent': (2, PERCENT_LABEL, 80, False), 'eta': (3, ETA_LABEL, 80, False), 'speed': (4, SPEED_LABEL, 80, False), 'status': (5, STATUS_LABEL, 80, False), } def __init__(self, *args, **kwargs): super(MainFrame, self).__init__(*args, **kwargs) self.index = 0 self.SetTitle(self.TITLE) self.SetSize(self.FRAME_MIN_SIZE) self._panel = wx.Panel(self) self._vertical_box = wx.BoxSizer(wx.VERTICAL) # Status List self._status_list = ListCtrl(self.STATUS_LIST, parent=self._panel, style=wx.LC_REPORT | wx.LEFT | wx.RIGHT) self._horizontal_box_status_list = wx.BoxSizer(wx.HORIZONTAL) self._horizontal_box_status_list.Add(self._status_list, proportion=1, flag=wx.EXPAND) status_list_buttons_data = { ('Add', self.ADD_LABEL, (-1, -1), self._on_add, wx.Button), ('remove', self.REMOVE_LABEL, (-1, -1), self._on_remove, wx.Button), ('start', self.START_LABEL, (-1, -1), self._on_start, wx.Button), } # Create buttons vertically self._vertical_control_box = wx.BoxSizer(wx.VERTICAL) for item in status_list_buttons_data: name, label, size, evt_handler, parent = item button = parent(self._panel, size=size) if parent == wx.Button: button.SetLabel(label) if evt_handler is not None: button.Bind(wx.EVT_BUTTON, evt_handler) self._vertical_control_box.Add(button, flag=wx.LEFT|wx.BOTTOM|wx.EXPAND, proportion=1, border=self.DEFAULT_BORDER_SIZE) self._horizontal_box_status_list.Add(self._vertical_control_box) self._vertical_box.Add(self._horizontal_box_status_list, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=self.DEFAULT_BORDER_SIZE) # Set Sizer self._panel.SetSizerAndFit(self._vertical_box) def _on_add(self, event): file_dialog = wx.FileDialog(self) file_dialog.Show() if file_dialog.ShowModal() == wx.ID_OK: file_path = file_dialog.GetPath() self._status_list.InsertItem(self.index, file_path) self.index += 1 def _on_remove(self, event): selected = self._status_list.get_selected() if selected: self._status_list.remove_row(selected) def _on_start(self, event): for item_count in range(0, self._status_list.GetItemCount()): item = self._status_list.GetItem(item_count, col=0) data = process_xls(item.GetText()) # Start spider if data: process = CrawlerProcess(settings['BOT_SETTINGS']) process.crawl(WIPOSpider(data)) process.start() # Copied from # https://github.com/MrS0m30n3/youtube-dl-gui/blob/57eb51ccc8e2df4e8c766b31d677513adb5c86cb/youtube_dl_gui/mainframe.py#L1095 class ListCtrl(wx.ListCtrl, ListCtrlAutoWidthMixin): """Custom ListCtrl widget. Args: columns (dict): See MainFrame class STATUSLIST_COLUMNS attribute. """ def __init__(self, columns, *args, **kwargs): super(ListCtrl, self).__init__(*args, **kwargs) ListCtrlAutoWidthMixin.__init__(self) self.columns = columns self._list_index = 0 self._set_columns() def remove_row(self, row_number): self.DeleteItem(row_number) self._list_index -= 1 def get_selected(self): return self.GetNextItem(-1, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED) def _set_columns(self): """Initializes ListCtrl columns. See MainFrame STATUSLIST_COLUMNS attribute for more info. """ for column_item in sorted(self.columns.values()): self.InsertColumn(column_item[0], column_item[1], width=wx.LIST_AUTOSIZE_USEHEADER) # If the column width obtained from wxLIST_AUTOSIZE_USEHEADER # is smaller than the minimum allowed column width # then set the column width to the minumum allowed size if self.GetColumnWidth(column_item[0]) &lt; column_item[2]: self.SetColumnWidth(column_item[0], column_item[2]) # Set auto-resize if enabled if column_item[3]: self.setResizeColumn(column_item[0]) </code></pre>
3
2,710
What is the best way to write a switch statement to return an image depending on a number without repeating to much code?
<p>I have a switch statement that returns an image based on the case number. I have 8 images of water droplets that start off as an empty droplet(drop_empty) and when the number increases from 1...6 and so on as shown in my code I want to change the images. For the 8 images as shown in the screenshot, I have each one set in an @IBOutlet and in an array in order to choose what image get's assigned to what. I do feel that I'm repeating my self way too much and am hoping to find a better solution to shorten my repetition. Hopefully, my code makes more sense.</p> <p><a href="https://i.stack.imgur.com/pZk9C.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pZk9C.png" alt="enter image description here" /></a></p> <pre><code> @IBOutlet var waterDropImage1: UIImageView! @IBOutlet var waterDropImage2: UIImageView! @IBOutlet var waterDropImage3: UIImageView! @IBOutlet var waterDropImage4: UIImageView! @IBOutlet var waterDropImage5: UIImageView! @IBOutlet var waterDropImage6: UIImageView! @IBOutlet var waterDropImage7: UIImageView! @IBOutlet var waterDropImage8: UIImageView! // Example function name that I would call func showDroplets() { dropletImageManager(waterPercentage: percentage, droplet: [waterDropImage1, waterDropImage2, waterDropImage3, waterDropImage4, waterDropImage5, waterDropImage6, waterDropImage7, waterDropImage8]) } func dropletImageManager(waterPercentage: Int, droplet: [UIImageView]) { switch waterPercentage { case 0: droplet[0].image = UIImage(named: &quot;drop_empty&quot;) case 1...6: droplet[0].image = UIImage(named: &quot;drop_half&quot;) case 7...12: droplet[0].image = UIImage(named: &quot;drop_full&quot;) case 13...18: droplet[0].image = UIImage(named: &quot;drop_full&quot;) droplet[1].image = UIImage(named: &quot;drop_half&quot;) case 19...25: droplet[0].image = UIImage(named: &quot;drop_full&quot;) droplet[1].image = UIImage(named: &quot;drop_full&quot;) case 26...31: droplet[0].image = UIImage(named: &quot;drop_full&quot;) droplet[1].image = UIImage(named: &quot;drop_full&quot;) droplet[2].image = UIImage(named: &quot;drop_empty&quot;) case 32...38: droplet[0].image = UIImage(named: &quot;drop_full&quot;) droplet[1].image = UIImage(named: &quot;drop_full&quot;) droplet[2].image = UIImage(named: &quot;drop_full&quot;) case 39...45: droplet[0].image = UIImage(named: &quot;drop_full&quot;) droplet[1].image = UIImage(named: &quot;drop_full&quot;) droplet[2].image = UIImage(named: &quot;drop_full&quot;) droplet[3].image = UIImage(named: &quot;drop_half&quot;) case 46...52: droplet[0].image = UIImage(named: &quot;drop_full&quot;) droplet[1].image = UIImage(named: &quot;drop_full&quot;) droplet[2].image = UIImage(named: &quot;drop_full&quot;) droplet[3].image = UIImage(named: &quot;drop_full&quot;) droplet[4].image = UIImage(named: &quot;drop_half&quot;) case 53...59: droplet[0].image = UIImage(named: &quot;drop_full&quot;) droplet[1].image = UIImage(named: &quot;drop_full&quot;) droplet[2].image = UIImage(named: &quot;drop_full&quot;) droplet[3].image = UIImage(named: &quot;drop_full&quot;) droplet[4].image = UIImage(named: &quot;drop_full&quot;) case 60...66: droplet[0].image = UIImage(named: &quot;drop_full&quot;) droplet[1].image = UIImage(named: &quot;drop_full&quot;) droplet[2].image = UIImage(named: &quot;drop_full&quot;) droplet[3].image = UIImage(named: &quot;drop_full&quot;) droplet[4].image = UIImage(named: &quot;drop_full&quot;) droplet[5].image = UIImage(named: &quot;drop_half&quot;) case 67...73: droplet[0].image = UIImage(named: &quot;drop_full&quot;) droplet[1].image = UIImage(named: &quot;drop_full&quot;) droplet[2].image = UIImage(named: &quot;drop_full&quot;) droplet[3].image = UIImage(named: &quot;drop_full&quot;) droplet[4].image = UIImage(named: &quot;drop_full&quot;) droplet[5].image = UIImage(named: &quot;drop_full&quot;) case 74...78: droplet[0].image = UIImage(named: &quot;drop_full&quot;) droplet[1].image = UIImage(named: &quot;drop_full&quot;) droplet[2].image = UIImage(named: &quot;drop_full&quot;) droplet[3].image = UIImage(named: &quot;drop_full&quot;) droplet[4].image = UIImage(named: &quot;drop_full&quot;) droplet[5].image = UIImage(named: &quot;drop_full&quot;) droplet[6].image = UIImage(named: &quot;drop_half&quot;) case 79...85: droplet[0].image = UIImage(named: &quot;drop_full&quot;) droplet[1].image = UIImage(named: &quot;drop_full&quot;) droplet[2].image = UIImage(named: &quot;drop_full&quot;) droplet[3].image = UIImage(named: &quot;drop_full&quot;) droplet[4].image = UIImage(named: &quot;drop_full&quot;) droplet[5].image = UIImage(named: &quot;drop_full&quot;) droplet[6].image = UIImage(named: &quot;drop_full&quot;) case 86...92: droplet[0].image = UIImage(named: &quot;drop_full&quot;) droplet[1].image = UIImage(named: &quot;drop_full&quot;) droplet[2].image = UIImage(named: &quot;drop_full&quot;) droplet[3].image = UIImage(named: &quot;drop_full&quot;) droplet[4].image = UIImage(named: &quot;drop_full&quot;) droplet[5].image = UIImage(named: &quot;drop_full&quot;) droplet[6].image = UIImage(named: &quot;drop_full&quot;) droplet[7].image = UIImage(named: &quot;drop_half&quot;) case 93...100: droplet[0].image = UIImage(named: &quot;drop_full&quot;) droplet[1].image = UIImage(named: &quot;drop_full&quot;) droplet[2].image = UIImage(named: &quot;drop_full&quot;) droplet[3].image = UIImage(named: &quot;drop_full&quot;) droplet[4].image = UIImage(named: &quot;drop_full&quot;) droplet[5].image = UIImage(named: &quot;drop_full&quot;) droplet[6].image = UIImage(named: &quot;drop_full&quot;) droplet[7].image = UIImage(named: &quot;drop_full&quot;) default: print(&quot;Error&quot;) } </code></pre>
3
3,285
grails generate war error java.lang.ArrayIndexOutOfBoundsException: 1
<p>I've tried to generate war file in grails with command :</p> <pre><code>grails war </code></pre> <p>but this error is shows up, and this is the first time with this error, previously war is generated normally.</p> <p>i know that array out of bound will be show up if the index doesn't exist in the arraylist, but i don't know which array? because all process in my application working fine.</p> <p>can anyone help me please? :(</p> <pre><code>java.lang.ArrayIndexOutOfBoundsException: 1 at org.codehaus.groovy.classgen.asm.InvocationWriter.loadArguments(InvocationWriter.java:192) at org.codehaus.groovy.classgen.asm.InvocationWriter.writeDirectMethodCall(InvocationWriter.java:130) at org.codehaus.groovy.classgen.asm.InvocationWriter.makeCall(InvocationWriter.java:229) at org.codehaus.groovy.classgen.asm.InvocationWriter.makeCall(InvocationWriter.java:76) at org.codehaus.groovy.classgen.asm.InvocationWriter.makeInvokeMethodCall(InvocationWriter.java:60) at org.codehaus.groovy.classgen.asm.InvocationWriter.writeInvokeMethod(InvocationWriter.java:342) at org.codehaus.groovy.classgen.AsmClassGenerator.visitMethodCallExpression(AsmClassGenerator.java:648) at org.codehaus.groovy.ast.expr.MethodCallExpression.visit(MethodCallExpression.java:67) at org.codehaus.groovy.classgen.asm.StatementWriter.writeExpressionStatement(StatementWriter.java:604) at org.codehaus.groovy.classgen.asm.OptimizingStatementWriter.writeExpressionStatement(OptimizingStatementWriter.java:354) at org.codehaus.groovy.classgen.AsmClassGenerator.visitExpressionStatement(AsmClassGenerator.java:509) at org.codehaus.groovy.ast.stmt.ExpressionStatement.visit(ExpressionStatement.java:40) at org.codehaus.groovy.classgen.asm.StatementWriter.writeBlockStatement(StatementWriter.java:81) at org.codehaus.groovy.classgen.asm.OptimizingStatementWriter.writeBlockStatement(OptimizingStatementWriter.java:155) at org.codehaus.groovy.classgen.AsmClassGenerator.visitBlockStatement(AsmClassGenerator.java:455) at org.codehaus.groovy.ast.stmt.BlockStatement.visit(BlockStatement.java:69) at org.codehaus.groovy.ast.ClassCodeVisitorSupport.visitClassCodeContainer(ClassCodeVisitorSupport.java:101) at org.codehaus.groovy.ast.ClassCodeVisitorSupport.visitConstructorOrMethod(ClassCodeVisitorSupport.java:112) at org.codehaus.groovy.classgen.AsmClassGenerator.visitStdMethod(AsmClassGenerator.java:319) at org.codehaus.groovy.classgen.AsmClassGenerator.visitConstructorOrMethod(AsmClassGenerator.java:276) at org.codehaus.groovy.ast.ClassCodeVisitorSupport.visitMethod(ClassCodeVisitorSupport.java:123) at org.codehaus.groovy.classgen.AsmClassGenerator.visitMethod(AsmClassGenerator.java:396) at org.codehaus.groovy.ast.ClassNode.visitContents(ClassNode.java:1059) at org.codehaus.groovy.ast.ClassCodeVisitorSupport.visitClass(ClassCodeVisitorSupport.java:50) at org.codehaus.groovy.classgen.AsmClassGenerator.visitClass(AsmClassGenerator.java:180) at org.codehaus.groovy.control.CompilationUnit$14.call(CompilationUnit.java:786) at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1027) at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:564) at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:542) at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:519) at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:498) at org.codehaus.groovy.control.CompilationUnit$compile.call(Unknown Source) at org.codehaus.groovy.grails.web.pages.GroovyPageCompiler$_compileGSP_closure1.doCall(GroovyPageCompiler.groovy:144) at sun.reflect.GeneratedMethodAccessor203.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:616) at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90) at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1082) at groovy.lang.ExpandoMetaClass.invokeMethod(ExpandoMetaClass.java:1106) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:906) at groovy.lang.Closure.call(Closure.java:412) at groovy.lang.Closure.call(Closure.java:425) at org.codehaus.groovy.runtime.IOGroovyMethods.withStream(IOGroovyMethods.java:1160) at org.codehaus.groovy.runtime.ResourceGroovyMethods.withInputStream(ResourceGroovyMethods.java:1523) </code></pre>
3
1,637
How do I return columns from different table using SQLAlchemy, Flask?
<p>I am trying to use SQLAlchemy, Marshmallow and FLask to query the tables from my classes Submission_status, Policy. I am trying to create a route call summary.py to use GET request to fetch something like this for my frontend:</p> <pre><code>&quot;policy_id&quot;: &quot;X0002&quot;, &quot;policy_holder&quot;: &quot;Mr Bean&quot;, &quot;policy_holder_contact&quot;:&quot;0123456789&quot; &quot;policy_holder_email&quot;:&quot;bean@hotmail.com&quot; &quot;product_id&quot;:&quot;1&quot;, &quot;status&quot;: &quot;incomplete&quot;, &quot;description&quot;:&quot;Pending UW&quot;, &quot;days_in_current_status&quot;:&quot;3&quot;, &quot;sales_name&quot;:&quot;Ali&quot;, &quot;sales_contact&quot;:&quot;0123454666&quot;, &quot;sales_email&quot;:&quot;ali@message.com&quot;, &quot;submission_date&quot;:&quot;12/12/2022 </code></pre> <p>I would like to get these datas from the following table:</p> <pre><code> 'policy_id': Submission_status.policy_id, 'policy_holder':Policy.policy_holder, 'policy_holder_contact':Policy.policy_holder_contact, 'policy_holder_email':Policy.policy_holder_email, 'product_id':Policy.product_id, 'status':Submission_status.status, 'description':Submission_status.description, 'num_days':(func.age(datetime.utcnow().strftime('%B %d %Y'),Submission_status.status_date)/86400).label('days'), 'sales_name':Policy.sales_name, 'sales_contact':Policy.sales_contact, 'sales_email':Policy.sales_email, 'submission_date':Submission_status.status_date </code></pre> <p>My Models and Schemas are as shown below:</p> <pre><code>''models.py'' #Policy Model class Policy(db.Model): id = db.Column(db.Integer, primary_key=True) sub_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) product_id=db.Column(db.Integer, db.ForeignKey('product.id'), nullable=False) policy_holder=db.Column(db.String(50),nullable=False) policy_holder_contact=db.Column(db.String(50)) policy_holder_email=db.Column(db.String(50)) sales_name=db.Column(db.String(50)) sales_contact=db.Column(db.String(50)) sales_email=db.Column(db.String(50)) sales_date=db.Column(db.DateTime) def __init__ (self,sub_date,product_id,policy_holder,policy_holder_contact,policy_holder_email,sales_name,sales_contact,sales_email,sales_date): self.sub_date=sub_date self.product_id=product_id self.policy_holder=policy_holder self.policy_holder_contact=policy_holder_contact self.policy_holder_email=policy_holder_email self.sales_name=sales_name self.sales_contact=sales_contact self.sales_email=sales_email self.sales_date=sales_date #Policy schema class PolicySchema(ma.Schema): class Meta: fields=('id','sub_date','product_id','policy_holder','policy_holder_contact','policy_holder_email','sales_name','sales_contact','sales_email','sales_date') policy_schema=PolicySchema() policys_schema=PolicySchema(many=True) #Submission_status Model class Submission_status(db.Model): id=db.Column(db.Integer,primary_key=True) status_date=db.Column(db.DateTime,nullable=False,default=datetime.utcnow) policy_id=db.Column(db.Integer,db.ForeignKey('policy.id'),nullable=False) policy = db.relationship('Policy', backref='submission_status') description=db.Column(db.String(200)) status=db.Column(db.String(50),nullable=False) user_id=db.Column(db.Integer,db.ForeignKey('user.id'),nullable=False) def __init__ (self,status_date,policy_id,description,status,user_id): self.status_date=status_date self.policy_id=policy_id self.description=description self.status=status self.user_id=user_id class SubmissionStatusSchema(ma.Schema): class Meta: fields=('id','status_date','policy_id','description','status','user_id','user.name','days') submissionstatus_schema=SubmissionStatusSchema() submissionstatuss_schema=SubmissionStatusSchema(many=True) #Summary Schema class SummarySchema(ma.Schema): class Meta: fields = ('submission_status.policy_id' 'policy.policy_holder', 'policy.policy_holder_contact', 'policy.policy_holder_email', 'policy.product_id', 'submission_status.status', 'submission_status.description', 'policy.sales_name', 'policy.sales_contact', 'policy.sales_email', 'submission_status.status_date,', ) summary_schema = SummarySchema() summarys_schema = SummarySchema(many=True) </code></pre> <p>Don't mind the wrong indentation, It is indented in the project and works fine for other functions.</p> <p>And here is my code in summary.py:</p> <pre><code>@summary.route(&quot;/&quot;, methods = ['GET']) def get_summary(): summary = db.session.query(Submission_status, Policy).outerjoin(Submission_status,Policy.id == Submission_status.policy_id).all() result = submissionstatuss_schema.dump(summary) return jsonify(result) </code></pre> <p>Can anyone help me on this? I keep getting empty brackets when I run the server and on the web...</p>
3
2,162
Returning many objects on html page - Django 2.0
<p>I am returning the "comentarios" objects of the database through a for, but since the display of these objects takes up a lot of space in the html page, I would like to know how to divide the objects into more lists or into a hidden space, since when they pass from seven comments they exceed the size of the body.</p> <p>template.html </p> <pre><code>{% extends 'baseR.html' %} {% load static %} {% block title %} Comentários - SMILE 3D {% endblock %} {% block tamanho %} 2000px {% endblock %} {% load bootstrap %} {% block main %} &lt;div class="row b2"&gt; &lt;div class="col-1"&gt;&lt;/div&gt; &lt;div class="col-10"&gt; &lt;h3 style="color:royalblue; font-weight:bold;"&gt;Pregão: &lt;/h3&gt; &lt;hr&gt; &lt;h2&gt;{{msg}}&lt;/h2&gt; &lt;br&gt; &lt;ul style="list-sytle:none;"&gt; &lt;div class="container pregoes"&gt; &lt;li style="list-style:none;"&gt; &lt;p&gt;&lt;strong&gt;Dono: &lt;/strong&gt;&lt;a href="{% url 'perfil-geral' pregoe.usuario.id %}" class="cNome"&gt;{{pregoe.usuario}}&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Tipo do pregão: &lt;/strong&gt;{{ pregoe.tipo }}&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Dente: &lt;/strong&gt;{{ pregoe.dente }}&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Cor: &lt;/strong&gt;{{ pregoe.cor }}&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Escala: &lt;/strong&gt;{{ pregoe.escala }}&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Material: &lt;/strong&gt;{{ pregoe.material }}&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Observações: &lt;/strong&gt;{{ pregoe.extra }}&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Preço inicial: &lt;/strong&gt;R${{ pregoe.preco }}&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Data de registro: &lt;/strong&gt;&lt;em&gt;{{ pregoe.data }}&lt;/em&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Prazo: &lt;/strong&gt;&lt;em&gt;{{ pregoe.prazo }}&lt;/em&gt;&lt;/p&gt; &lt;/li&gt; &lt;/div&gt; &lt;br&gt; &lt;hr&gt; **&lt;h3&gt;Comentários: &lt;/h3&gt; {% for comentario in comentarios %} &lt;div class="container" style="background-color:gainsboro; padding-bottom:2px; padding-top:10px;"&gt; &lt;a href="{% url 'delete-comentario' comentario.id %}"&gt;&lt;i class="far fa-times-circle" style="float: right;"&gt;&lt;/i&gt;&lt;/a&gt; &lt;a href="{% url 'perfil-geral' comentario.user.id %}" class="cNome"&gt; &lt;p&gt;&lt;strong&gt;{{comentario.user}}&lt;/strong&gt; &lt;/p&gt;&lt;/a&gt; &lt;p style="float:right;"&gt;{{comentario.comentario}}&lt;/p&gt; &lt;div class="circle1"&gt; &lt;a href="{% url 'perfil-geral' comentario.user.id %}"&gt;&lt;img src="../../media/{{comentario.user.foto}}" class="fotoPerfil img-fluid" style="max-width: 80px;"&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;br&gt; {% endfor %}** &lt;br&gt; {{msg}} &lt;a href="{% url 'novo-comentario' pregoe.id user.id %}" style="float:right; margin-top:-20px; margin-left:8px;"&gt; NOVO COMENTÁRIO &lt;i class="far fa-comment"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; {% endblock %} </code></pre> <p>views.py</p> <pre><code>@login_required def listaComentarios(request, id1, id2): user = get_object_or_404(CustomUser, pk=id2) pregao = get_object_or_404(Pregao, pk=id1) comentarios = Comentario.objects.all().filter(pregao=pregao) if user == pregao.usuario: return render(request, 'comentarios/lista-comentarios-dono.html', {'comentarios': comentarios, 'pregoe': pregao}) return render(request, 'comentarios/lista-comentarios.html', {'comentarios': comentarios, 'pregoe': pregao}) </code></pre>
3
2,224
Selenium grid launching browser on hub instead of node
<p>I have configured my hub and one of the node. Hub is setup on jenkins as a plugin which is running on ubundu machine and my node is running on windows machine. Hub and node are correctly configure. Now when I am running the test to launch the chrome browser on node it is behaving weird. The one browser instances is launched on the node and not redirected to url. After few seconds it launches the Firefox browser's 5 instances on hub node. (Although i have setup only chrome capabilities). </p> <p>Has anyone else faced the similar issue ? For reproducing the same issue I have created 2 sample classes and one testng.xml file. </p> <p>TestClass.java</p> <pre><code>import com.codeborne.selenide.Selenide; import org.testng.annotations.Test; public class TestClass extends ParentClass { @Test public void testcase1(){ Selenide.open("http://www.google.com"); } @Test public void testcase2(){ Selenide.open("http://www.ymail.com"); } @Test public void testcase3(){ Selenide.open("http://www.bbc.com"); } } </code></pre> <p>ParentClass.java</p> <pre><code>import com.codeborne.selenide.Configuration; import com.codeborne.selenide.WebDriverRunner; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.BeforeTest; import org.testng.annotations.Optional; import org.testng.annotations.Parameters; import java.net.MalformedURLException; import java.net.URL; public class ParentClass { Logger LOG = LoggerFactory.getLogger(ParentClass.class); @BeforeTest @Parameters({"Browser", "hubAddress"}) public void setupBrowser(@Optional("chrome") String browser, @Optional("") String hubAddress) { LOG.info("Setting up Browser: "); WebDriver driver=null; if (browser.equalsIgnoreCase("chrome")) { if (!hubAddress.equals("")){ DesiredCapabilities cap = DesiredCapabilities.chrome(); cap.setBrowserName("chrome"); driver= setUpRemoteBrowser(hubAddress,cap); WebDriverRunner.setWebDriver(driver); } } Configuration.startMaximized = true; Configuration.timeout = 10; LOG.info("Browser Setup completed"); } public WebDriver setUpRemoteBrowser(String hubUrl, DesiredCapabilities capabilities){ LOG.info("Running browser using hub"); WebDriver driver =null; try { driver = new RemoteWebDriver(new URL(hubUrl), capabilities); } catch (MalformedURLException e){ LOG.info("Incorrect URL"); e.printStackTrace(); } return driver; } } </code></pre> <p>testng.xml</p> <pre><code>&lt;!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" &gt; &lt;suite name="hue-test-Suite" parallel="true"&gt; &lt;parameter name="Browser" value="chrome"/&gt; &lt;parameter name="hubAddress" value="http://172.26.158.157:4444/wd/hub"/&gt; &lt;test name="HueMailSmoke-Tests"&gt; &lt;classes&gt; &lt;class name="TestClass"&gt; &lt;/class&gt; &lt;/classes&gt; &lt;/test&gt; &lt;/suite&gt; </code></pre> <p><a href="https://i.stack.imgur.com/Paoj3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Paoj3.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/hbl4e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hbl4e.png" alt="enter image description here"></a></p>
3
1,445
KendoUI - grid - template not getting data
<p>I have problem with KenfoUI grid. From server side I'm sending JSON data:</p> <pre><code>{ "data": [{ "process": { "id": "myProcess2:1:1206", "description": null, "name": "My process 2", "version": 1 }, "id": 42066, "description": "unisono-rest-evenem", "type": { "id": 2, "translation": "Faktura sprzedażowa", "name": "salesInvoice" }, "triger": { "id": 42048, "name": "Document recognized trigger", "code": "ocrEndTrigger", "type": "DOCUMENT_RECOGNIZED" } }, { "process": { "id": "myProcess2:1:1206", "description": null, "name": "My process 2", "version": 1 }, "id": 42067, "description": "6756757", "type": { "id": 5, "translation": "Słownik stawek VAT", "name": "dictVatRates" }, "triger": { "id": 42048, "name": "Document recognized trigger", "code": "ocrEndTrigger", "type": "DOCUMENT_RECOGNIZED" } }, { "process": { "id": "myProcess2:1:1206", "description": null, "name": "My process 2", "version": 1 }, "id": 42068, "description": "56546546", "type": { "id": 1, "translation": "Faktura", "name": "invoice" }, "triger": { "id": 42047, "name": "New document trigger", "code": "createDocument", "type": "CREATE_DOCUMENT" } }, { "process": { "id": "myProcess2:1:1206", "description": null, "name": "My process 2", "version": 1 }, "id": 42069, "description": "swswsws", "type": { "id": 5, "translation": "Słownik stawek VAT", "name": "dictVatRates" }, "triger": { "id": 42047, "name": "New document trigger", "code": "createDocument", "type": "CREATE_DOCUMENT" } }], "total": 4 } </code></pre> <p>and I defined columns in gird like:</p> <pre><code> columns: [{ field: "process", title: "Nazwa procesu", editor: staticEditors.processEditor, "template": function (data) { if (data.process != null &amp;&amp; data.process != undefined) { return "&lt;span class='gridText' title='" + data.process.name + "'&gt;" + data.process.name + "&lt;/span&gt;" } else { return "&lt;span&gt;&lt;/span&gt;" } } }, { field: "type", title: "Typ dokumentu", editor: $scope.typeEditor, "template": function (data) { if (data.type != null &amp;&amp; data.type != undefined) { return "&lt;span class='gridText' title='" + data.type.translation + "'&gt;" + data.type.translation + "&lt;/span&gt;" } else { return "&lt;span&gt;&lt;/span&gt;" } } }, { field: "triger", title: "Wyzwalacz", editor: staticEditors.triggerEditor, "template": function (data) { if (data.triger != null &amp;&amp; data.triger != undefined) { return "&lt;span class='gridText' title='" + data.triger.name + "'&gt;" + data.triger.name + "&lt;/span&gt;" } else { return "&lt;span&gt;&lt;/span&gt;" } } }, { field: "description", title: "Description", "template": function (data) { if (data.description != null &amp;&amp; data.description != undefined) { return "&lt;span class='gridText' title='" + data.description + "'&gt;" + data.description + "&lt;/span&gt;" } else { return "&lt;span&gt;&lt;/span&gt;" } } } </code></pre> <p>There is a problem in template function because data object doesn't have all data. I noticed that has problem with nested data (field like type, trigger, process has null or string ("[object Object]") values.)</p> <p>How can I solve this problem ?</p>
3
2,079
How to resize (reduce) image in carousel
<p>I need help to reduce a picture so it could be nicely placed into carousel. I made 2 pages with a slightly different carousel.</p> <p>In first page it is placed nicely: <a href="https://i.stack.imgur.com/1BMf5.jpg" rel="nofollow noreferrer">first carousel where picture if nicely placed</a></p> <p>And on a second carousel with a slightly different look it looks like this: <a href="https://i.stack.imgur.com/dICyU.jpg" rel="nofollow noreferrer">second carousel where picture is too big</a></p> <p>Codes for second carousel are (first CSS and second HTML)</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#thumbnail-preview-indicators { position: relative; overflow: hidden; } #thumbnail-preview-indicators .slides .slide-1, #thumbnail-preview-indicators .slides .slide-2, #thumbnail-preview-indicators .slides .slide-3, #thumbnail-preview-indicators .slides .slide-4, #thumbnail-preview-indicators .slides .slide-5, #thumbnail-preview-indicators .slides .slide-6, #thumbnail-preview-indicators .slides .slide-7, #thumbnail-preview-indicators .slides .slide-8, #thumbnail-preview-indicators .slides .slide-9, #thumbnail-preview-indicators .slides .slide-10, #thumbnail-preview-indicators .slides .slide-11{ background-size: 50%; background-position: center center; background-repeat: no-repeat; } #thumbnail-preview-indicators, #thumbnail-preview-indicators .slides, #thumbnail-preview-indicators .slides .slide-1, #thumbnail-preview-indicators .slides .slide-2, #thumbnail-preview-indicators .slides .slide-3, #thumbnail-preview-indicators .slides .slide-4, #thumbnail-preview-indicators .slides .slide-5, #thumbnail-preview-indicators .slides .slide-6, #thumbnail-preview-indicators .slides .slide-7, #thumbnail-preview-indicators .slides .slide-8, #thumbnail-preview-indicators .slides .slide-9, #thumbnail-preview-indicators .slides .slide-10, #thumbnail-preview-indicators .slides .slide-11{ height: 480px; } #thumbnail-preview-indicators .slides .slide-1{ background-image: url(img/AudiA3.jpg); } #thumbnail-preview-indicators .slides .slide-2{ background-image: url(img/AudiA3b.jpg); } #thumbnail-preview-indicators .slides .slide-3{ background-image: url(img/AudiA3c.jpg); } #thumbnail-preview-indicators .slides .slide-4{ background-image: url(img/AudiA3d.jpg); } #thumbnail-preview-indicators .slides .slide-5{ background-image: url(img/AudiA3e.jpg); } #thumbnail-preview-indicators .slides .slide-6{ background-image: url(img/AudiA3g.jpg); } #thumbnail-preview-indicators .slides .slide-7{ background-image: url(img/AudiA3h.jpg); } #thumbnail-preview-indicators .slides .slide-8{ background-image: url(img/AudiA3i.jpg); } #thumbnail-preview-indicators .slides .slide-9{ background-image: url(img/AudiA3j.jpg); } #thumbnail-preview-indicators .slides .slide-10{ background-image: url(img/AudiA3k.jpg); } #thumbnail-preview-indicators .slides .slide-11{ background-image: url(img/AudiA3l.jpg); } #thumbnail-preview-indicators .carousel-inner .item .carousel-caption { top: 20%; bottom: inherit; } /* CAROUSEL INDICATORS */ #thumbnail-preview-indicators .carousel-indicators li, #thumbnail-preview-indicators .carousel-indicators li.active { width: 102px; height: 69px; background-color: transparent; border: 1px solid white; border-radius: 1px; } #thumbnail-preview-indicators .carousel-indicators li.active { border: 1px solid red; } #thumbnail-preview-indicators .carousel-indicators li &gt; .thumbnail { width: 100px; height: 66px; overflow: hidden; opacity: 0.8; display: block; padding: 0; margin-bottom: 0; background-color: #fff; border: none; border-radius: 2px; transition: all 550ms ease-out; } #thumbnail-preview-indicators .carousel-indicators li:hover &gt; .thumbnail, #thumbnail-preview-indicators .carousel-indicators li.active &gt; .thumbnail:hover { position: relative; display: block; border: 1px solid white; opacity: 1; transform: scale(1.5); z-index: 1; } #thumbnail-preview-indicators .carousel-indicators li.active &gt; .thumbnail:hover { border: 1px solid red; } @media screen and (min-width: 480px) { } @media screen and (min-width: 768px) { } @media screen and (min-width: 1024px) { } @media screen and (min-width: 1200px) { } @media screen and (min-width: 1440px) { }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="thumbnail-preview-indicators" class="carousel slide" data-ride="carousel"&gt; &lt;!-- INDIKATORI --&gt; &lt;ol class="carousel-indicators"&gt; &lt;li data-target="#thumbnail-preview-indicators" data-slide-to="0" class="active"&gt; &lt;div class="thumbnail"&gt; &lt;img class="img-responsive" src="img/AudiA3.jpg"&gt; &lt;/div&gt; &lt;/li&gt; &lt;li data-target="#thumbnail-preview-indicators" data-slide-to="1"&gt; &lt;div class="thumbnail"&gt; &lt;img class="img-responsive" src="img/AudiA3b.jpg"&gt; &lt;/div&gt; &lt;/li&gt; &lt;li data-target="#thumbnail-preview-indicators" data-slide-to="2"&gt; &lt;div class="thumbnail"&gt; &lt;img class="img-responsive" src="img/AudiA3c.jpg"&gt; &lt;/div&gt; &lt;/li&gt; &lt;li data-target="#thumbnail-preview-indicators" data-slide-to="3"&gt; &lt;div class="thumbnail"&gt; &lt;img class="img-responsive" src="img/AudiA3d.jpg"&gt; &lt;/div&gt; &lt;/li&gt; &lt;li data-target="#thumbnail-preview-indicators" data-slide-to="4"&gt; &lt;div class="thumbnail"&gt; &lt;img class="img-responsive" src="img/AudiA3e.jpg"&gt; &lt;/div&gt; &lt;/li&gt; &lt;li data-target="#thumbnail-preview-indicators" data-slide-to="5"&gt; &lt;div class="thumbnail"&gt; &lt;img class="img-responsive" src="img/AudiA3g.jpg"&gt; &lt;/div&gt; &lt;/li&gt; &lt;li data-target="#thumbnail-preview-indicators" data-slide-to="6"&gt; &lt;div class="thumbnail"&gt; &lt;img class="img-responsive" src="img/AudiA3h.jpg"&gt; &lt;/div&gt; &lt;/li&gt; &lt;li data-target="#thumbnail-preview-indicators" data-slide-to="7"&gt; &lt;div class="thumbnail"&gt; &lt;img class="img-responsive" src="img/AudiA3i.jpg"&gt; &lt;/div&gt; &lt;/li&gt; &lt;li data-target="#thumbnail-preview-indicators" data-slide-to="8"&gt; &lt;div class="thumbnail"&gt; &lt;img class="img-responsive" src="img/AudiA3j.jpg"&gt; &lt;/div&gt; &lt;/li&gt; &lt;li data-target="#thumbnail-preview-indicators" data-slide-to="9"&gt; &lt;div class="thumbnail"&gt; &lt;img class="img-responsive" src="img/AudiA3k.jpg"&gt; &lt;/div&gt; &lt;/li&gt; &lt;li data-target="#thumbnail-preview-indicators" data-slide-to="10"&gt; &lt;div class="thumbnail"&gt; &lt;img class="img-responsive" src="img/AudiA3l.jpg"&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ol&gt; &lt;!-- KRAJ NAVIGATORA--&gt; &lt;div class="carousel-inner"&gt; &lt;div class="item slides active"&gt; &lt;div class="slide-1"&gt;&lt;img src="img/AudiA3.jpg" alt="Audi A3"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item slides"&gt; &lt;div class="slide-2"&gt;&lt;img src="img/AudiA3b.jpg" alt="Audi A3"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item slides"&gt; &lt;div class="slide-3"&gt;&lt;img src="img/AudiA3c.jpg" alt="Audi A3"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item slides"&gt; &lt;div class="slide-4"&gt;&lt;img src="img/AudiA3d.jpg" alt="Audi A3"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item slides"&gt; &lt;div class="slide-5"&gt;&lt;img src="img/AudiA3e.jpg" alt="Audi A3"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item slides"&gt; &lt;div class="slide-6"&gt;&lt;img src="img/AudiA3g.jpg" alt="Audi A3"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item slides"&gt; &lt;div class="slide-7"&gt;&lt;img src="img/AudiA3h.jpg" alt="Audi A3"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item slides"&gt; &lt;div class="slide-8"&gt;&lt;img src="img/AudiA3i.jpg" alt="Audi A3"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item slides"&gt; &lt;div class="slide-9"&gt;&lt;img src="img/AudiA3j.jpg" alt="Audi A3"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item slides"&gt; &lt;div class="slide-10"&gt;&lt;img src="img/AudiA3k.jpg" alt="Audi A3"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="item slides"&gt; &lt;div class="slide-11"&gt;&lt;img src="img/AudiA3l.jpg" alt="Audi A3"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;a class="left carousel-control" href="#thumbnail-preview-indicators" role="button" data-slide="prev"&gt;&lt;span class="glyphicon glyphicon-chevron-left"&gt;&lt;/span&gt;&lt;/a&gt; &lt;a class="right carousel-control" href="#thumbnail-preview-indicators" role="button" data-slide="next"&gt;&lt;span class="glyphicon glyphicon-chevron-right"&gt;&lt;/span&gt;&lt;/a&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>So I hope that somebody knows how to fix this because I tried everythig.</p>
3
5,782
Performance Issues - Parallelism - SQL Server
<p>SQL agent job never finishes.</p> <p>Server : 2.4hZ, 24 processor, 256GB RAM, Windows 2008 Server, SQL 2008</p> <p>As per the activity monitor: %ProcessTime is 100%</p> <p>With SP_Who found below:</p> <pre><code>SPID Status DBName Command CPUTime ProgramName SPID 141 SUSPENDED STL UPDATE 5429 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 22362478 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 21178290 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 22590708 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 21682298 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 20652239 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 22315694 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 22362120 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 21867097 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 22746381 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 20301456 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 22236445 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 19998611 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 21139087 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 22628117 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 21512351 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 21354649 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 20256823 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 21185138 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 21272530 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 22084796 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 20745996 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 21812185 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 21738442 .Net SqlClient Data Provider 141 141 RUNNABLE STL UPDATE 20895694 .Net SqlClient Data Provider 141 </code></pre> <p>As per it is 24 process the query been split into 24 parallel threads.</p> <p>Settings for Cost Threshold for Parallelism is 30 and Max Degree of Parallelism is 0 (default).</p> <p>Cannot see anything going in Profiler and all the thread above are waiting for CPU Time.</p> <p>How to find what is SQL Server doing and what is holding up the CPU?</p>
3
1,423
Validating value of a Certain key before adding it to a c# dictionary
<p>I am trying to implement a dictionary in such a way that It will only add in a certain value to a key if that <strong>new value</strong> is greater than the <strong>currently existing value</strong></p> <p>So the basic scenarios would be:</p> <ol> <li>If the key is not available, it will create a new key and a value</li> <li>If the key if available, it will check if the current value is greater than the value that is already assigned to that key and will only update if it is greater.</li> </ol> <p>Before I explain the problem I am facing here is my code</p> <pre><code>static IDictionary&lt;string, string&gt; versionStack = new Dictionary&lt;string, string&gt;(); </code></pre> <pre><code>foreach(var item in RequiredApps) { nameOfApp = item.Key; minimumVersionOfApp = item.Value.minVersion; if (versionStack.TryGetValue(nameOfApp, out minimumVersionOfApp)) { if (Convert.ToInt32(minimumVersionOfApp) &gt;= Convert.ToInt32(item.Value.minVersion)) minimumVersionOfApp = item.Value.minVersion; } versionStack[nameOfApp] = minimumVersionOfApp; } </code></pre> <p><strong>Note:</strong> Kindly do not worry about the <code>for</code> loop as it works fine and gives no problem there. Just want to display only the specific code that gives me problem</p> <p>Right now I have been able to fulfill the functionality to a certain level but the problem is when the <code>TryGetValue</code> is executed it turns all my values to null.</p> <p>I am using the <code>TryGetValue</code> to see if a key has a value and if so to retrieve it.</p> <p>I am stuck here right now and would appreciate if anyone can help show me what I am doing wrong.</p> <p><strong>Edit :-</strong></p> <p>Given that the problem I am facing is quite unclear and as suggested by Rufus L I am adding a sample dummy application with exactly the problem I am facing</p> <p>Hope this helps to clear any confusion :)</p> <pre><code>class Program { static IDictionary&lt;string, string&gt; versionStack = new Dictionary&lt;string, string&gt;(); static string appName; static string minVersion; static void Main(string[] args) { AddOnce(); AddTwice(); } public static void AddOnce() { appName = "app01"; minVersion = "1.0"; versionStack.Add(appName, minVersion); } public static void AddTwice() { string existingValue; appName = "app01"; minVersion = "3.0"; if (!versionStack.TryGetValue("app01", out existingValue) || Convert.ToInt32(existingValue) &lt; Convert.ToInt32(minVersion)) { versionStack[appName] = minVersion; } } } </code></pre>
3
1,053
Image button in android pressed and get a random image in an array sequentially
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>public abstract class MainActivity extends Activity implements View.OnClickListener{ private ImageButton bt1; public int index =0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final Drawable[][] images = new Drawable[4][16]; bt1 = (ImageButton) findViewById(R.id.im_bt1); bt1.setImageDrawable(images[index][(int)(Math.random()*16)]); bt1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { index++; ((ImageButton)v).setImageDrawable(images[index][(int)(Math.random()*16)]); } }); } Red RR1 = new Red(R.drawable.rr1); Red RY1 = new Red(R.drawable.ry1); Red RG1 = new Red(R.drawable.rg1); Red RB1 = new Red(R.drawable.rb1); Green GB1 = new Green(R.drawable.greenblue); Green GG1 = new Green(R.drawable.greengreen); Green GR1 = new Green(R.drawable.greenred); Green GY1 = new Green(R.drawable.greenyellow); Yellow YY1 = new Yellow(R.drawable.yellowyellow); Yellow YB1 = new Yellow(R.drawable.yellowblue); Yellow YG1 = new Yellow(R.drawable.yellowgreen); Yellow YR1 = new Yellow(R.drawable.yellowred); Blue BR1= new Blue(R.drawable.br1); Blue BB1=new Blue(R.drawable.bb1); Blue BY1=new Blue(R.drawable.by1); Blue BG1= new Blue(R.drawable.bg1); Red[] Redarray = new Red[]{ RR1,RY1,RG1,RB1 }; Green[] Greenarray = new Green[]{ GR1,GB1,GY1,GG1 }; Blue[] Bluearray = new Blue[]{ BB1,BY1,BG1,BR1 }; Yellow[] Yellowarray = new Yellow[]{ YB1,YG1,YR1,YY1 }; }</code></pre> </div> </div> </p> <p>I have an <code>ImageButton</code> in my layout and I want to press the button and get another random <code>ImageButton</code> from an array and the get another when I press that one, but I want it to show sequentially on the arrays that I made.</p> <p>array of images 1 array of images 2 array of images 3 array of images 4</p> <p>Image Button from <code>array1</code> to another random Image Button from <code>array2</code> to another Image Button from <code>array 3</code>...</p> <p>edit: so I made a class of all the arrays and it's not working.. I'm struggling to make an array of arrays.. can u guys check my code? thanks..</p>
3
1,094
getImageData returns white image
<p>I need to read the image data from an image object in javascript. But my code returns always a blank array (set to 255) </p> <pre><code>&lt;html&gt; &lt;header&gt; &lt;/header&gt; &lt;body&gt; &lt;input type="file" id="imgfile" onchange="testImageData(event);" /&gt; &lt;canvas id="canvas1" width="640" height="480"&gt;&lt;/canvas&gt; &lt;script src="./../scripts/cam.js" &gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Here is the script</p> <pre><code>var canvas1 = document.getElementById('canvas1'); var context1 = canvas1.getContext('2d'); function getImageData(image){ /* returns Uint8ClampedArray object takes an image obj */ var canvas = document.createElement("canvas"); canvas.height = image.height; canvas.width = image.width; var ctx = canvas.getContext("2d"); ctx.width = image.width; ctx.height = image.height; ctx.drawImage(image,0,0); return ctx.getImageData(0, 0, ctx.width, ctx.height); } function testImageData(event){ var selectedFile = event.target.files[0]; var reader = new FileReader(); var img = new Image(); reader.onload = function(event) { console.log('onload'); img.src = event.target.result; img.onload = function(){ context1.drawImage(img, 0,0, img.width, img.height); var imgData = getImageData(img); // console.log(imgData); var data = imgData.data; for(var i = 0; i&lt;data.length;i+=4){ console.log(data[i],data[i+1],data[i+2],data[i+3]); } } }; </code></pre> <p> In my understanding, the console.log should return me the data in RGBA. But I'm just getting 255.</p> <p> <a href="https://i.stack.imgur.com/f5rKU.png" rel="nofollow noreferrer">console.log output</a></p> <hr> <h2>EDIT:</h2> <p>Okay I found a work around but I don't understand why this is working.<br> Instead using getImageData, I get the data directly from the drawn context1. </p> <pre><code>function testImageData(event){ var selectedFile = event.target.files[0]; var reader = new FileReader(); var img = new Image(); reader.onload = function(event) { console.log('onload'); img.src = event.target.result; img.onload = function(){ context1.drawImage(img, 0,0, img.width, img.height); var imgData = context1.getImageData(0,0,img.width,img.height); var data = imgData.data; for(var i = 0; i&lt;data.length;i+=4){ console.log(data[i],data[i+1],data[i+2],data[i+3]); } } }; </code></pre> <p>So the problem must lie in creating a new canvas.</p>
3
1,039
newUser coming up undefined
<p>I am fairly new to Express and am trying to create a simple authentication login/register form. "newUser" is coming up undefined and I am not really sure why.... any suggestions are greatly appreciated. Thanks!</p> <pre><code>bcrypt.hash(newUser.password, salt, function(err, hash) { </code></pre> <hr> <pre><code>let express = require("express"); let router = express.Router(); let mongojs = require("mongojs"); let db = mongojs("carapp", ["users"]); let bcrypt = require("bcryptjs"); let passport = require("passport"); let LocalStrategy = require("passport-local").Strategy; // login GET PAGE router.get("/login", function(req, res) { res.render("login"); }); // Register GET PAGE router.get("/register", function(req, res) { res.render("register"); }); // Register POST router.post("/register", function(req, res) { let name = req.body.name; let email = req.body.email; let username = req.body.username; let password = req.body.password; let confirm_password = req.body.confirm_password; // Validation req.checkBody("name", "Name field is required").notEmpty(); req.checkBody("email", "Email field is required").notEmpty(); req.checkBody("email", "Please use a Valid Email Address").isEmail(); req.checkBody("username", "Username field is required").notEmpty(); req.checkBody("password", "Password field is required").notEmpty(); req.checkBody("confirm_password", "Passwords Do Not Match".equals(req.body.password); // Check For Errors let errors = req.validationErrors(); if (errors) { console.log("Form has errors"); res.render("register", { errors: errors, name: name, email: email, username: username, password: password, confirm_password: confirm_password }); } else { let newUser = { name: name, email: email, username: username, password: password }; } bcrypt.genSalt(10, function(err, salt) { bcrypt.hash(newUser.password, salt, function(err, hash) { newUser.password = hash; db.users.insert(newUser, function(err, doc) { if (err) { res.send(err); } else { console.log("User Added. Good JOB using MONGODB Matt!"); req.flash("success", "You are registered and can log in"); res.location("/"); res.redirect("/"); } }); }); }); passport.serializeUser(function(user, done) { done(null, user._id); }); passport.deserializeUser(function(id, done) { db.users.findOne({ _id: mongojs.OnjectId(id) }, function(err, user{ done(err, user); }); }); passport.use( new LocalStrategy(function(username, password, done) { db.users.findOne({ username: username }, function(err, user) { if (err) { return done(err); } if (!user) { return done(null, false, { message: "Incorrect Username" }); } bcrypt.compare(password, user.password, function(err, isMatch) { if (err) { return done(err); } if (isMatch) { return done(null, user); } else { return done(null, false, { message: "Incorrect Password" }); } }); }); }) ); // Login Post router.post("/login",passport.authenticate("local",{ successRedirect: "/", failureRedirect: "/users/login", failureFlash: "Invalid Username or Password" } + function(req, res) { console.log("Auth Successful"); res.redirect("/"); } ) ); }); module.exports = router; //brackets needed here </code></pre> <hr> <p>Here is my package.json file</p> <pre><code> { "name": "cars", "version": "1.0.0", "description": "car buying application", "main": "app.js", "scripts": { "start" : "nodemon" }, "author": "", "license": "ISC", "dependencies": { "bcryptjs": "^2.4.3", "body-parser": "^1.18.3", "bootstrap": "^4.1.3", "connect-flash": "^0.1.1", "ejs": "^2.6.1", "express": "^4.16.4", "express-messages": "^1.0.1", "express-session": "^1.15.6", "mongojs": "^2.6.0", "passport": "^0.4.0", "passport-local": "^1.0.0", "pug": "^2.0.3" } } </code></pre>
3
1,577
Js/jQuery - How to hide/show an input created on the fly?
<p>This code creates a group of elements (four inputs) on the fly. Once you create an element (four inputs) you can select/deselect, when you select an element will bring up the editor for the corresponding element. I've made a function to hide only the first element. The problem is that I can not make it comeback without affecting the other elements. </p> <p>Instructions:</p> <p>Click on the "Price" link, an element will be created on the fly (four nested inputs) Select the element (four nested inputs) to bring up the editor ( one input and a brown little square). Click on the little brown square to hide the first input of the element (four nested inputs) and that will hide the first input. I need the little brown square to hide and show the same input.</p> <p>Go here to see the full code: To see the problem you have to create more than one element to find out.</p> <p><a href="http://jsfiddle.net/yjfGx/13/" rel="nofollow">http://jsfiddle.net/yjfGx/13/</a></p> <p>This is the JS/jQuery code, for the full code go to the link above.</p> <pre><code>var _PriceID = 1; $('#Price').on('click',function(){ var label = 'Price' var Id = 'Price_'; var P = $( '&lt;p class="inputContainer" /&gt;' ).fadeIn(100); var l = $( '&lt;label /&gt;' ).attr({'for':Id + _PriceID, 'id':Id + _PriceID, 'class':'priceLb'}).text( label ).after('&lt;br/&gt;'); var l1 = $( '&lt;span class="dollar-sign" /&gt;' ).text( '$' ).css({"font-family":"Arial", "color":"#333", "font-weight":"bold"}); var input1 = $( '&lt;input /&gt;' ).attr({ 'type':'text', 'name':'', 'class':'inputs', 'maxlength':'3', 'placeholder':'one', 'id':Id + _PriceID, 'class':'pricePh-1' }) .css({ "width":"60px", "paddingLeft":"1.3em", "paddingRight":"0.2em", "margin":"3px" }); var l2 = $( '&lt;span class="priceComma-1" /&gt;' ).text( ',' ).css({"font-family":"Arial", "color":"#333", "font-weight":"bold"}); var input2 = $( '&lt;input /&gt;' ).attr({ 'type':'text', 'name':'', 'class':'inputs', 'maxlength':'3', 'placeholder':'two', 'id':Id + _PriceID, 'class':'pricePh-2' }) .css({ "width":"68px", "paddingLeft":"0.7em", "paddingRight":"0.2em", "margin":"3px" }); var l3 = $( '&lt;span class="priceComma-2" /&gt;' ).text( ',' ).css({"font-family":"Arial", "color":"#333", "font-weight":"bold"}); var input3 = $( '&lt;input /&gt;' ).attr({ 'type':'text', 'name':'', 'class':'inputs', 'maxlength':'3', 'placeholder':'three', 'id':Id + _PriceID, 'class':'pricePh-3' }) .css({ "width":"64px", "paddingLeft":"1em", "paddingRight":"0.2em", "margin":"3px" }); var l4 = $( '&lt;span /&gt;' ).text( ',' ).css({"font-family":"Arial", "color":"#333", "font-weight":"bold"}); var input4 = $( '&lt;input /&gt;' ).attr({ 'type':'text', 'name':'', 'class':'inputs', 'maxlength':'2', 'placeholder':'four', 'id':Id + _PriceID, 'class':'pricePh-4' }) .css({ "width":"37px", "paddingLeft":"0.5em", "paddingRight":"0.2em", "margin":"3px" }); P.append( l, l1, input1, l2, input2, l3, input3, l4, input4); var D = $( 'form' ); P.on({ mouseenter: function() { $(this).addClass("pb"); }, mouseleave: function() { $(this).removeClass("pb"); } }); P.appendTo(D); _PriceID++; }); /*** Select element individually and load editor. ***/ var flag = false; $("form").on("click", "p", function () { var cur = $(this).css("background-color"); if (cur == "rgb(255, 255, 255)") { if (flag == false) { $(this).css("background-color", "#FDD"); LoadPriceProperties($(this)); flag = true; } } else { $(this).css("background-color", "white"); $('.properties-panel').hide(); flag = false; } }); /*** Element editor ***/ var LoadPriceProperties = function (obj) { $('.properties-panel').css('display', 'none'); $('#priceProps-edt').css('display', 'block'); var label = $('.priceLb', obj); var price1 = $('.pricePh-1', obj); var price2 = $('.pricePh-2', obj); $('#SetPricePlaceholder-1').val(price1.attr('placeholder')); $('#SetPricePlaceholder-2').val(price2.attr('placeholder')); /*** Getting an answer, depending on what they click on. ***/ $('#fieldOptionsContainer_1 div').bind('click', function () { if ($(this).hasClass('field-option-delete')) { RemoveUnwantedPriceField1($(this)); } else { /*** Function loacated on "line 98" ***/ HideUnwantedPriceField_1($(this)); } }); _CurrentElement = obj; }; function HideUnwantedPriceField_1() { var input = $('.pricePh-1', _CurrentElement); var comma = $('.priceComma-1', _CurrentElement); if($(input).is(":hidden")){ } else { input.hide(); comma.hide(); } } </code></pre>
3
2,800
How would my model be in MVC3 if I needed to reference a foreign key, for example CountryID?
<p>Here's what I have so far Model and View:</p> <pre><code>public class RegisterModel { [Required] [Display(Name = "Usuario")] public string UserName { get; set; } [Required] [DataType(DataType.EmailAddress)] [Display(Name = "Correo")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Contraseña")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirme Su Contraseña")] [Compare("Password", ErrorMessage = "Sus contraseñas no son las mismas.")] public string ConfirmPassword { get; set; } [Required] [Display(Name = "Direccion")] public string Address { get; set; } [Required] [Display(Name = "Telefono Fijo")] public string Telephone { get; set; } [Required] [Display(Name = "Celular")] public string MobilePhone { get; set; } [Required] [Display(Name = "Fecha de Nacimiento")] public DateTime DateOfBirth { get; set; } [Required] [Display(Name = "Sexo")] public bool Sex { get; set; } [Required] [Display(Name = "Pais")] public int Country { get; set; } } @model Foo.WebUI.Models.RegisterModel @{ ViewBag.Title = "Register"; } &lt;script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"&gt;&lt;/script&gt; &lt;div id="registerform"&gt; &lt;h2&gt;Cree Su Cuenta&lt;/h2&gt; @using (Html.BeginForm()) { @Html.ValidationSummary(true) &lt;h3&gt;Informacion de Usuario&lt;/h3&gt; &lt;div class="editor-field"&gt; @Html.LabelFor(model =&gt; model.UserName) @Html.EditorFor(model =&gt; model.UserName) @Html.ValidationMessageFor(model =&gt; model.UserName) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.LabelFor(model =&gt; model.Email) @Html.EditorFor(model =&gt; model.Email) @Html.ValidationMessageFor(model =&gt; model.Email) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.LabelFor(model =&gt; model.Password) @Html.EditorFor(model =&gt; model.Password) @Html.ValidationMessageFor(model =&gt; model.Password) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.LabelFor(model =&gt; model.ConfirmPassword) @Html.EditorFor(model =&gt; model.ConfirmPassword) @Html.ValidationMessageFor(model =&gt; model.ConfirmPassword) &lt;/div&gt; &lt;h3&gt;Informacion Personal&lt;/h3&gt; &lt;div class="editor-field"&gt; @Html.LabelFor(model =&gt; model.Address) @Html.EditorFor(model =&gt; model.Address) @Html.ValidationMessageFor(model =&gt; model.Address) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.LabelFor(model =&gt; model.Telephone) @Html.EditorFor(model =&gt; model.Telephone) @Html.ValidationMessageFor(model =&gt; model.Telephone) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.LabelFor(model =&gt; model.MobilePhone) @Html.EditorFor(model =&gt; model.MobilePhone) @Html.ValidationMessageFor(model =&gt; model.MobilePhone) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.LabelFor(model =&gt; model.DateOfBirth) @Html.EditorFor(model =&gt; model.DateOfBirth) @Html.ValidationMessageFor(model =&gt; model.DateOfBirth) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.LabelFor(model =&gt; model.Sex) @Html.EditorFor(model =&gt; model.Sex) @Html.ValidationMessageFor(model =&gt; model.Sex) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.LabelFor(model =&gt; model.Country) @Html.EditorFor(model =&gt; model.Country) @Html.ValidationMessageFor(model =&gt; model.Country) &lt;/div&gt; &lt;p&gt; &lt;input type="submit" value="Create" /&gt; &lt;/p&gt; } &lt;/div&gt; </code></pre> <p>Now, since my User will belong to a single country, in the database it has a foreign key reference to the Country table. In my model, I set the Country property to be of type int. Is this correct?</p> <p>How would I correctly set this up so a dropdownlist is shown for choosing a country in the View but a numerical value is saved for persistance to the database?</p>
3
2,438
jQuery mobile getting wrong authentication
<p>I have the following situation:</p> <p>index.html (which is my login page)</p> <pre><code>&lt;div data-role="page" id="page_login"&gt; &lt;div id="wrapper_top_image"&gt; &lt;div id="top_image"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div data-role="content" data-theme="b"&gt; &lt;div id="landmark-1" data-landmark-id="1"&gt; &lt;form id="loginForm" onsubmit="return submitLogin();"&gt; &lt;div data-role="fieldcontain" class="ui-hide-label"&gt; &lt;label for="username"&gt;Username:&lt;/label&gt; &lt;input type="text" name="username" id="username" value="" placeholder="Username" /&gt; &lt;/div&gt; &lt;div data-role="fieldcontain" class="ui-hide-label"&gt; &lt;label for="password"&gt;Password:&lt;/label&gt; &lt;input type="password" name="password" id="password" value="" placeholder="Password" /&gt; &lt;/div&gt; &lt;input type="submit" value="Login" id="submitButton"&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;div data-role="footer"&gt; &lt;h4&gt;&amp;copy; 2013 Company&lt;/h4&gt; &lt;h6&gt;Developed by Alex&lt;/h6&gt; &lt;/div&gt; </code></pre> <p></p> <p>and then my PHP Script that is going to check everything -> ps.. I fixed to avoid injection already! :</p> <p>auth.php</p> <pre><code>$mysqli = new mysqli($mysql_hostname,$mysql_user, $mysql_password, $mysql_database); // Parse the log in form if the user has filled it out and pressed "Log In" if (isset($_POST["username"]) &amp;&amp; isset($_POST["password"])) { $username =$_POST['username']; $password =$_POST['password']; $sql = "SELECT id, password, username FROM users WHERE username='$username' AND password='$password' LIMIT 1"; $result = $mysqli-&gt;query($sql) or die( $mysqli-&gt;error() ); $rowN= mysqli_num_rows($result); if($rowN==1){ $response_array['status'] = 'success'; } else { $response_array['status'] = 'error'; } echo json_encode($response_array); } $mysqli-&gt;close(); </code></pre> <p>Finally my JQuery Script:</p> <pre><code>function submitLogin(){ jQuery.support.cors = true; $.ajax({ url: 'http://www.xxxx.com/mobile/auth.php', crossDomain: true, type: "post", data: $("#loginForm").serialize(), success: function(data){ if(data.status == 'success'){ //alert("Granted Access!"); $.mobile.changePage("main.html"); }else if(data.status == 'error'){ alert("Authentication Invalid. Please try again!"); navigator.app.exitApp(); $.mobile.changePage("index.html"); } } }); }; </code></pre> <p>Everything is working ok! Data is checked and if it is okay, is redirected to main.html (main page) otherwise the app pops up a window saying that the authentication is wrong, keeping the user in the same page.</p> <p>Here is the dilemma: If users type the wrong credential trying to login again, any credential that he/she enter will be considerate invalid even if he/she entered the right one and the app will keep going back to the login page until I refresh the browser or end the app in case of running in the device.</p> <p>Does anyone knows what may be happening?</p>
3
1,323
AngularJS: Setting up default input values when the page is initially loading
<p>I am developing an web app with AngularJS &amp; Bootstrap. In my application there is a bootstrap modal on main dashboard. This modal is showing up on a toggle button. In the main dashboard there are some charts &amp; grids. The input fields for drawing these charts and grids are coming from that modal.</p> <p>This is the main dashboard html.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html ng-app="myApp"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;meta name="description" content=""&gt; &lt;meta name="author" content=""&gt; &lt;title&gt;&lt;/title&gt; &lt;!-- angularJS scripts --&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"&gt;&lt;/script&gt; &lt;script src="../mvc/constants/constants.js"&gt;&lt;/script&gt; &lt;script src="../mvc/service/Service.js"&gt;&lt;/script&gt; &lt;script src="../mvc/controller/DashboardController.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"&gt; &lt;link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css"&gt; &lt;!-- KENDO scripts for creating charts --&gt; &lt;script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body ng-controller="DashboardController" ng-init="initModal()"&gt; &lt;div id="mainContainer"&gt; &lt;div class="demo-section k-content wide"&gt; &lt;div class="col-xs-8"&gt; &lt;h1 style="padding-left: 15px"&gt; HotelName&lt;i class="fa fa-pencil-square-o" style="color: #6789DA; cursor: pointer; position: relative; top: -10px; font-size: 27px;" data-toggle="modal" data-target="#hotelDetailModal"&gt;&lt;/i&gt; &lt;/h1&gt; &lt;h5 style="padding-left: 15px"&gt;{{packageString}}&lt;/h5&gt; &lt;h5 style="padding-left: 15px"&gt;{{requestRoomTypeName}}&lt;/h5&gt; &lt;/div&gt; &lt;div class="col-xs-4"&gt; &lt;!-- ng-click="initialMethod()" --&gt; &lt;h4 style="text-align: right; margin-top: 14px; margin-right: 20px;"&gt;{{algoName}} &lt;/h4&gt; &lt;h6 style="padding-right: 20px; float: right"&gt;{{startDateString}} {{endDateString}}&lt;/h6&gt; &lt;!-- &lt;button type="submit" class="btn btn-default" style="margin-right: 20px; margin-bottom: 20px; margin-top: 2px; float: right;" data-toggle="modal" data-target="#changeSearch" ng-click="initialMethod()"&gt;Edit criteria&lt;/button&gt; --&gt; &lt;/div&gt; &lt;!-- &lt;/div&gt; --&gt; &lt;/div&gt; &lt;div class="col-md-12"&gt; &lt;div id="grid" class="demo-section k-content wide"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div id="example" class="col-md-12"&gt; &lt;div class="demo-section k-content wide"&gt; &lt;div id="chart"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="chartContainer" class="col-md-7"&gt; &lt;div id="competitorPriceChart"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Modal --&gt; &lt;div class="modal fade" id="hotelDetailModal" role="dialog"&gt; &lt;div class="modal-dialog"&gt; &lt;!-- Modal content--&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;button type="button" class="close" data-dismiss="modal"&gt;&amp;times;&lt;/button&gt; &lt;h1&gt;Hotel Details&lt;/h1&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;div class="row"&gt; &lt;div class="col-xs-6"&gt; &lt;label&gt;Schema Type&lt;/label&gt; &lt;select class="form-control" required="required" ng-model="schemaType" ng-change="changeSchemaType()"&gt; &lt;option value="0"&gt;Hotel&lt;/option&gt; &lt;option value="1"&gt;Destination&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div class=col-xs-6&gt; &lt;label&gt;Sub Type&lt;/label&gt; &lt;select class="form-control" id="subType" ng-options="sub_type.cityCode for sub_type in subTypeList" ng-model="subType" required="required" ng-change="getHotelDataByDestination()" value="{{sub_type.cityName}}"&gt; &lt;option value="" disabled selected hidden=true&gt;Select Option &lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-xs-4"&gt; &lt;label&gt;Hotel&lt;/label&gt; &lt;/div&gt; &lt;div class="col-xs-12"&gt; &lt;select class="form-control" ng-options="hotel.hotelName for hotel in hotelList" ng-model="hotel" required="required" value="{{hotel}}" ng-change="getRoomTypeByHotelName();getMealPlanByHotelName();"&gt; &lt;option value="" disabled selected hidden=true&gt;Select Option &lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-xs-6"&gt; &lt;label&gt;Room Type&lt;/label&gt; &lt;select class="form-control" ng-options="roomType.roomTypeName for roomType in roomTypeList" ng-model="roomType" required="required" value="{{roomType}}"&gt; &lt;option value="" disabled selected hidden=true&gt;Select Option &lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div class="col-xs-6"&gt; &lt;label&gt;Meal Plan&lt;/label&gt; &lt;select class="form-control" ng-options="mealPlan.description for mealPlan in mealPlanList" ng-model="mealPlan" required="required" value="{{mealPlan}}"&gt; &lt;option value="" disabled selected hidden=true&gt;Select Option &lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-xs-3"&gt; &lt;label&gt;Rooms&lt;/label&gt; &lt;input id="rooms" class="form-control" required="required" ng-model="rooms" type="number"/&gt; &lt;/select&gt; &lt;/div&gt; &lt;div class="col-xs-3"&gt; &lt;label&gt;Adults&lt;/label&gt; &lt;input id="adults" class="form-control" required="required" ng-model="adults" type="number"/&gt; &lt;/select&gt; &lt;/div&gt; &lt;div class="col-xs-3"&gt; &lt;label&gt;Children&lt;/label&gt; &lt;input id="kids" class="form-control" required="required" ng-model="kids" type="number"/&gt; &lt;/select&gt; &lt;/div&gt; &lt;div class="col-md-3"&gt; &lt;label&gt;Nights&lt;/label&gt; &lt;input id="nights" class="form-control" required="required" ng-model="nights" type="number"/&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-xs-6"&gt; &lt;label style="margin: 15px 0"&gt;Departure Date&lt;/label&gt; &lt;input type="date" class="form-control" ng-model="departureDate"&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- &lt;div class="row"&gt; &lt;div class="col-xs-6"&gt; &lt;button ng-click="detailCtrlViewModel.submit()" class="btn btn-default" style="float: right;"&gt;Next&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; --&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button ng-click="submit()" class="btn btn-primary" style="float: right;" data-dismiss="modal"&gt;SUBMIT &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p> </p> <p>When the app is running it should show the main page with all the charts &amp; grids. i.e. there should be default values for inputs when the page is loading.</p> <p>The modal-body field(drop down menus) are populating from the database.</p> <p>My <strong>DashboardController</strong> is as follows.</p> <pre><code>var myApp = angular.module('myApp', ['DataService']); myApp.controller('DashboardController', function ($scope, DataService) { $scope.rooms = 1; $scope.adults = 1; $scope.kids = 0; $scope.nights = 7; $scope.departureDate = new Date(); $scope.schemaType = 1; $scope.caclulateOn = new Date().toISOString().slice(0, 10); $scope.initModal = function () { console.log('initModal'); $scope.changeSchemaType(); $scope.getHotelDataByDestination(); }; $scope.changeSchemaType = function () { $scope.subTypeList = []; if ($scope.schemaType == "0") { $scope.subTypeList.push({ cityName : "5 star", cityCode : "city1", }, { cityName : "4 star or above", cityCode : "city2", }); $scope.subType = $scope.subTypeList[0]; } else { $scope.subTypeList.push({cityCode:"CITY1",cityName:"CITY1"},{cityCode:"city2",cityName:"city2"}); $scope.subType = $scope.subTypeList[0]; console.log($scope.subType); } } $scope.getHotelDataByDestination = function () { console.log($scope.subType); console.log($scope.subType.cityCode); var destinationCode = $scope.subType.cityCode; DataService.getHotelByDestinationService(destinationCode).success( function(data) { $scope.hotelList = []; for (var k = 0; k &lt; data.length; k++) { $scope.hotelList.push({hotelId: data[k].hotelId, hotelName:data[k].hotelName }); } if(destinationCode == "CITY1"){ $scope.hotel = $scope.hotelList[17]; console.log($scope.hotel); }else if(destinationCode == "CITY2"){ $scope.hotel = $scope.hotelList[2]; console.log($scope.hotel); }else { $scope.hotel = $scope.hotelList[0]; } $scope.getRoomTypeByHotelName(); $scope.getMealPlanByHotelName(); }).error(function(error) { console.log(error) }); } $scope.getRoomTypeByHotelName = function () { console.log($scope.hotel); var hotelName = $scope.hotel.hotelName; DataService.getRoomTypeByHotelNameService(hotelName).success( function(data) { $scope.roomTypeList = []; for (var k = 0; k &lt; data.length; k++) { $scope.roomTypeList.push({roomTypeName: data[k].roomTypeName }); } $scope.roomType = $scope.roomTypeList[0]; }).error(function(error) { console.log(error) }); } $scope.getMealPlanByHotelName = function () { var hotelName = $scope.hotel.hotelName; DataService.getMealPlanByHotelNameService(hotelName).success( function(data) { console.log(data) $scope.mealPlanList= []; for (var k = 0; k &lt; data.length; k++) { $scope.mealPlanList.push({code: data[k].code, description: data[k].description }); } $scope.mealPlan = $scope.mealPlanList[0]; }).error(function(error) { console.log(error) }); } $scope.submit = function () { console.log('submit'); console.log($scope.rooms); console.log($scope.adults); console.log($scope.kids); console.log($scope.nights); console.log($scope.departureDate); console.log($scope.hotel); console.log($scope.roomType); console.log($scope.mealPlan); // call function to draw charts and grid $scope.displayTableView($scope.hotel.hotelId, $scope.roomType.roomTypeName, $scope.departureDate, $scope.nights, $scope.mealPlan.code); $scope.initCompetitorPriceChart($scope.hotel.hotelId, $scope.departureDate, $scope.nights, $scope.mealPlan.code); } }); </code></pre> <p>When the page is loading it calls <strong>initModal</strong> function &amp; populate all the drop down field in the modal. But actually I am getting an empty page, them I toggle the modal I can select fields an clicks the submit button, then it draws charts. Initially it doesn't draw any graph or grid. The thing I really want is show main page with charts, those charts should be drawn for default input fields(when the modal is loading default values are the first element in the drop down). Again, once I select new values from the modal &amp; submit it should reload the main page with new charts based on newly selected values.</p> <p>Hope you clear what I am mentioning. Any suggestions would be highly appreciated.</p> <p><strong>UPDATED</strong></p> <p>This is the response right after </p> <pre><code>DataService.getHotelByDestinationService(destinationCode).success( function(data) {} [{"hotelId":26047,"hotelCode":null,"hotelName":"Anahita Residence and Villas","rating":null,"cityCode":null,"holidayId":27751},{"hotelId":26341,"hotelCode":null,"hotelName":"Belle Mare Plage (Hotel CONSTANCE)","rating":null,"cityCode":null,"holidayId":27911},{"hotelId":26364,"hotelCode":null,"hotelName":"Blumarine Attitude Hotel","rating":null,"cityCode":null,"holidayId":27874},{"hotelId":26362,"hotelCode":null,"hotelName":"Friday Attitude Hotel","rating":null,"cityCode":null,"holidayId":27873},{"hotelId":26965,"hotelCode":null,"hotelName":"Heritage Awali","rating":null,"cityCode":null,"holidayId":27934},{"hotelId":26963,"hotelCode":null,"hotelName":"Heritage le Telfair","rating":null,"cityCode":null,"holidayId":27931},{"hotelId":26306,"hotelCode":null,"hotelName":"Hotel Angsana Balaclava Mauritius","rating":null,"cityCode":null,"holidayId":27971},{"hotelId":26046,"hotelCode":null,"hotelName":"Hotel Sofitel So Mauritius","rating":null,"cityCode":null,"holidayId":27752},{"hotelId":26301,"hotelCode":null,"hotelName":"Long Beach Resort","rating":null,"cityCode":null,"holidayId":27753},{"hotelId":26763,"hotelCode":null,"hotelName":"LUX* Belle Mare","rating":null,"cityCode":null,"holidayId":27914},{"hotelId":26762,"hotelCode":null,"hotelName":"LUX* Grand Gaube","rating":null,"cityCode":null,"holidayId":27913},{"hotelId":26761,"hotelCode":null,"hotelName":"LUX* Le Morne","rating":null,"cityCode":null,"holidayId":27892},{"hotelId":26721,"hotelCode":null,"hotelName":"Maradiva Villas Resort &amp; Spa","rating":null,"cityCode":null,"holidayId":27891},{"hotelId":26330,"hotelCode":null,"hotelName":"Mont Choisy Beach Villas","rating":null,"cityCode":null,"holidayId":27932},{"hotelId":26331,"hotelCode":null,"hotelName":"Mystik Apart Hotel","rating":null,"cityCode":null,"holidayId":27933},{"hotelId":26048,"hotelCode":null,"hotelName":"One and Only Le Saint Geran","rating":null,"cityCode":null,"holidayId":27791},{"hotelId":26328,"hotelCode":null,"hotelName":"Preskil Beach Resort","rating":null,"cityCode":null,"holidayId":27771},{"hotelId":26361,"hotelCode":null,"hotelName":"Recif Attitude Hotel","rating":null,"cityCode":null,"holidayId":27872},{"hotelId":26329,"hotelCode":null,"hotelName":"Solana Beach Resort","rating":null,"cityCode":null,"holidayId":27792},{"hotelId":26743,"hotelCode":null,"hotelName":"Tamassa All-Inclusive Resort","rating":null,"cityCode":null,"holidayId":27893},{"hotelId":26541,"hotelCode":null,"hotelName":"The Ravenala Attitude Hotel","rating":null,"cityCode":null,"holidayId":27871},{"hotelId":26821,"hotelCode":null,"hotelName":"The Saint Regis Mauritius Resort","rating":null,"cityCode":null,"holidayId":27936},{"hotelId":26053,"hotelCode":null,"hotelName":"The Sands Suites Resort and Spa","rating":null,"cityCode":null,"holidayId":27772},{"hotelId":26822,"hotelCode":null,"hotelName":"The Westin Turtle Bay Resort &amp; Spa","rating":null,"cityCode":null,"holidayId":27935},{"hotelId":26764,"hotelCode":null,"hotelName":"Villas de LUX* Belle Mare","rating":null,"cityCode":null,"holidayId":27912},{"hotelId":26363,"hotelCode":null,"hotelName":"Zilwa Attitude Hotel","rating":null,"cityCode":null,"holidayId":27875}] </code></pre> <p>Thank You</p>
3
8,744
java.util.Scanner object throws NullPointerException while parsing text file
<p>I created this JAVA code for <a href="https://code.google.com/codejam/contest/544101/dashboard#s=p0" rel="nofollow">this Google Code Jam question</a>. When i execute the code and select <a href="https://code.google.com/codejam/contest/544101/dashboard/do/A-large-practice.in?cmd=GetInputFile&amp;problem=567116&amp;input_id=1&amp;filename=A-large-practice.in&amp;redownload_last=1&amp;agent=website&amp;csrfmiddlewaretoken=NGRhMjVlNjE3N2IwODc4Yzk5YTBkYzNmODYzNTVlYjV8fDE0MjIyNzc3MjE1NDQ5Njk%3D" rel="nofollow">this text file</a>, it throws NullPointerException. Please help. I guess it is because nextLine() positions the scanner to the nextLine and returns the rest of the current line which is empty.</p> <pre><code> line = ab.nextLine(); </code></pre> <p>How do I fix this error so that it reads the next line of text? Provide code along with your suggestions. I will be grateful to you for the rest of my life :)</p> <pre><code> /* JEditorPaneFileChooser.java * Copyright (c) 2014, HerongYang.com, All Rights Reserved. */ import java.io.*; import java.nio.*; import java.nio.charset.*; import java.awt.event.*; import javax.swing.*; import javax.swing.filechooser.*; import java.util.Scanner; public class JEditorPaneFileChooser implements ActionListener { JFrame myFrame = null; JEditorPane myPane = null; JScrollPane mySPane = null; JMenuItem cmdOpen = null; JMenuItem cmdSave = null; String dirName = "\\herong\\swing\\"; String fileName = ""; public static void main(String[] a) { (new JEditorPaneFileChooser()).test(); } private void test() { myFrame = new JFrame("JEditorPane JFileChooser Test"); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myFrame.setSize(300,400); myPane = new JEditorPane(); myPane.setContentType("text/plain"); myPane.setText( "CLICK ON \'File\' AND SELECT \'Open\'\nTHEN SELECT \'A-large-practice.in\'"); mySPane = new JScrollPane(myPane); myFrame.setContentPane(mySPane); JMenuBar myBar = new JMenuBar(); JMenu myMenu = getFileMenu(); myBar.add(myMenu); myFrame.setJMenuBar(myBar); myFrame.setVisible(true); } private JMenu getFileMenu() { JMenu myMenu = new JMenu("File"); cmdOpen = new JMenuItem("Open"); cmdOpen.addActionListener(this); myMenu.add(cmdOpen); return myMenu; } public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(dirName)); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); FileNameExtensionFilter filter = new FileNameExtensionFilter( ".in file", "in"); chooser.setFileFilter(filter); Object cmd = e.getSource(); try { if (cmd == cmdOpen) { int code = chooser.showOpenDialog(myPane); if (code == JFileChooser.APPROVE_OPTION) { File selectedFile = chooser.getSelectedFile(); long ag= selectedFile.length(); fileName = selectedFile.getName(); FileInputStream fis = new FileInputStream(selectedFile); InputStreamReader in= new InputStreamReader(fis, Charset.forName("UTF-8")); char[] buffer=new char[(int)ag]; int n = in.read(buffer); String text = new String(buffer, 0, n); String ans =bag(text); myPane.setText(ans); in.close(); } } } catch (Exception f) { f.printStackTrace(); } } public static String bag(String input){ Scanner ab=new Scanner(input); int case1,lp=0; case1 = ab.nextInt(); int total, k; char[][] chari,m=null,n=null; int R1[][]=null,B1[][]=null; String line="",line1="",ghost="",answ=""; int axr=0,minr=0,maxr=0,axrb=0,minrb=0,maxrb=0,xr=0,lr=0,nex=0,xrb=0,lrb=0,nexb=0,yr=0,lr1=0,lr2=0,lr3=0,yrb=0,lr1b=0,lr2b=0,lr3b=0,man=0,min=0, manb=0,minb=0,rax=0,ray=0,cra=0,raxb=0,rayb=0,crab=0; int t,i,j,x,p,q,p1,g,h,y,w,sumit,sum,RX=0,BX=0; for (i=1;i&lt;=case1;i++) { total = ab.nextInt(); k=ab.nextInt(); chari=new char[total][total]; for(x=0;x&lt;total;x++) { line = ab.nextLine(); for (y=0;y&lt;total;y++) { chari[x][y] =line.charAt(y);} } for (g=0;g&lt;total;g++) { w=0; for(h=total-1;h&gt;=0;h--) { m[g][w]=chari[h][g]; w++; } } for (q=0;q&lt;total;q++) { p1=total-1; for (p=total-1;p&gt;=0;p--) { if( (m[p][q]=='R') || (m[p][q]=='B')) { n[p1][q]=m[p][q]; p--;} } } for (sumit=total-1;sumit&gt;=0;sumit--) { for (sum=0;sum&lt;total;sum++) { if (n[sumit][sum] == 'R') { R1[RX][0]=sumit; R1[RX][3]=sum; RX++; } else if (n[sumit][sum]=='B') { B1[BX][0] = sumit; B1[BX][4]= sum; BX++; } } } axr=R1.length; for (minr=0;minr&lt;axr;minr++) { xr = R1 [minr][0]; for (maxr=minr+1;maxr&lt;axr;maxr++) { if (R1 [maxr][0] == xr) lr++;} if (lr&gt;=k) nex=1; if (lr&lt;=k) break; else lr=0; } if (nex!=1) { for (minr=0;minr&lt;axr;minr++) { yr=R1[minr][5]; for (maxr=minr+1;maxr&lt;axr;maxr++) { if (R1[maxr][6]==yr) lr1++;} if (lr1&gt;=k)nex=1; if (lr1&gt;=k) break; else lr1=0; } if (nex!=1) { for (man=0;man&lt;axr;man++) { rax=R1[man][0]; ray = R1 [man][7]; cra=1; for (min=man+1;min&lt;axr;min++) { if ( (R1[min][0]==rax-cra) &amp;&amp; (R1[min][8] == ray +cra) ) {lr2++; cra++;} else break; } cra=1; if (lr2&gt;=k) nex=1; if (lr2&gt;=k) break; else lr2=0; } if (nex!=1) { for (man=0;man&lt;axr;man++) { rax=R1[man][0]; ray = R1 [man][9]; cra=1; for (min=man+1;min&lt;axr;min++) { if ( (R1[min][0]==rax-cra) &amp;&amp; (R1[min][10] == ray -cra) ) {lr3++; cra++;} else break; } cra=1; if (lr3&gt;=k) nex=1; if (lr3&gt;=k) break; else lr3=0; } } } } axrb=B1.length; for (minrb=0;minrb&lt;axrb;minrb++) { xrb = B1 [minrb][0]; for (maxrb=minrb+1;maxrb&lt;axrb;maxrb++) { if (B1 [maxrb][0] == xrb) lr++;} if (lrb&gt;=k) nexb=1; if (lrb&lt;=k) break; else lr=0; } if (nexb!=1) { for (minrb=0;minrb&lt;axrb;minrb++) { yr=B1[minrb][11]; for (maxrb=minrb+1;maxrb&lt;axrb;maxrb++) { if (B1[maxrb][12]==yrb) lr1b++;} if (lr1b&gt;=k)nexb=1; if (lr1b&gt;=k) break; else lr1b=0; } if (nexb!=1) { for (manb=0;manb&lt;axrb;manb++) { raxb=B1[manb][0]; rayb = B1 [manb][13]; crab=1; for (minb=manb+1;minb&lt;axrb;minb++) { if ( (B1[minb][0]==raxb-crab) &amp;&amp; (B1[minb][14] == rayb +crab) ) {lr2b++; crab++;} else break; } crab=1; if (lr2b&gt;=k) nexb=1; if (lr2b&gt;=k) break; else lr2b=0; } if (nexb!=1) { for (manb=0;manb&lt;axrb;manb++) { raxb=B1[manb][0]; rayb = B1 [manb][15]; crab=1; for (minb=manb+1;minb&lt;axrb;minb++) { if ( (B1[minb][0]==raxb-crab) &amp;&amp; (B1[minb][16] == rayb -crab) ) {lr3b++; crab++;} else break; } crab=1; if (lr3b&gt;=k) nexb=1; if (lr3b&gt;=k) break; else lr3b=0; } } } } if (nex==1) {ghost=(nexb==1)?"Both": "Red";} else {ghost =(nexb==1)? "Blue":"Neither";} answ= "case1 #" + i+ ": " +ghost+"\n"; } return answ; } } </code></pre> <p>stacktrace --</p> <pre><code>java.lang.NullPointerException at JEditorPaneFileChooser.bag(JEditorPaneFileChooser.java:112) at JEditorPaneFileChooser.actionPerformed(JEditorPaneFileChooser.java:78) </code></pre>
3
8,652
Docker: Connected as id undefined. Error trying to establish connection between database container and backend container
<p>I'm trying to make a Docker project containing Backend (express.js), GUI (Angular), and Database (MySQL) containers. Each container runs correctly individually, but when I try to make the connection between database and backend I get the following error when I try to print the threadID. Also, if I try to query from this connection I just get a promise and not the data itself.</p> <p>&quot;connected as id undefined&quot; <a href="https://i.stack.imgur.com/x38Il.png" rel="nofollow noreferrer">Error</a></p> <p>The files composition of the project is the following.</p> <p><a href="https://i.stack.imgur.com/9fv9f.png" rel="nofollow noreferrer">File Directory</a></p> <pre><code>version: '3.8' services: gui: container_name: gui-container restart: always build: ./gui ports: - '4200:4200' environment: NODE_ENV: dev DEBUG: 'true' volumes: - ./gui:/usr/src/app/gui - /usr/src/app/gui/node_modules links: - backend command: npm run start backend: container_name: backend-container restart: always # command: sh -c &quot;npm cache clean --force &amp;&amp; npm start&quot; build: ./backend ports: - 3000:3000 volumes: - ./backend:/usr/src/app/backend - /usr/src/app/backend/node_modules environment: NODE_ENV: dev DATABASE_HOST: database depends_on: - database # command: npm run debug database: build: ./database container_name: database-container command: --default-authentication-plugin=mysql_native_password restart: always ports: - 3318:3306 </code></pre> <p>My config file is the following.</p> <pre><code>var mysql = require(&quot;mysql&quot;); function DataBaseHandler() { this.connection = null; } DataBaseHandler.prototype.createConnection = function () { console.log(&quot;Trying to connect to database.&quot;); this.connection = mysql.createConnection({ host: 'database', user: 'root', password: 'testingpassword', database: 'KuoteSuite', port: 3306 }); this.connection.connect(function (err) { if (err) { console.error(&quot;error connecting &quot; + err.stack); return null; } console.log(&quot;connected as id &quot; + this.threadId); }); return this.connection; }; module.exports = DataBaseHandler; </code></pre> <p>I'm trying to establish the connection inside the lead.repository.js file inside backend/repositories.</p> <pre><code>const Lead = require('../models/lead'); const mysql = require('mysql'); var DataBaseHandler = require(&quot;../config/DataBaseHandler&quot;); var dataBaseHandler = new DataBaseHandler(); var connection = dataBaseHandler.createConnection(); const table = '`Lead`'; // Repository uses Object Models to interact with Tables from Databases class LeadRepository{ async getAllLeads(){ const result = await connection.query(`SELECT * FROM ${table}`); await connection.commit(); return result; } } module.exports = LeadRepository; </code></pre>
3
1,179
Unable to start my react application and getting error in webpack server
<p>I don't know where am going wrong</p> <p>Am not sharing all package.json but whatever required am sharing.</p> <p>here is my package.json</p> <pre><code> &quot;scripts&quot;: { &quot;develop&quot;: &quot;webpack serve --hot --port 8080 --disable-host-check --config webpack.develop.js&quot;, }, &quot;engines&quot;: { &quot;node&quot;: &quot;&gt;=10&quot; }, &quot;devDependencies&quot;: { &quot;react-hot-loader&quot;: &quot;^4.12.20&quot;, &quot;react-test-renderer&quot;: &quot;^17.0.1&quot;, &quot;typescript&quot;: &quot;4.1.2&quot;, &quot;webpack&quot;: &quot;^5.70.0&quot;, &quot;webpack-bundle-analyzer&quot;: &quot;^4.2.0&quot;, &quot;webpack-cli&quot;: &quot;^4.9.2&quot;, &quot;webpack-dev-server&quot;: &quot;^4.7.4&quot; } </code></pre> <p>web.develop.js</p> <pre><code>const commonConfig = require('./webpack.config') module.exports = { ...commonConfig, output: { ...commonConfig.output, publicPath: 'http://localhost:8080/', }, mode: 'development', module: { rules: [ ...commonConfig.module.rules, { test: /\.(js|jsx|ts|tsx)?$/, use: 'react-hot-loader/webpack', include: /node_modules/, }, ], }, devServer: { index: 'index.html', hot: &quot;only&quot;, // hot:true headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS', 'Access-Control-Allow-Headers': 'X-Requested-With, content-type, Authorization', }, }, plugins: [...commonConfig.plugins], } </code></pre> <p>error:</p> <pre><code>[webpack-cli] Error: Unknown option '--disable-host-check' [webpack-cli] Run 'webpack --help' to see available commands and options </code></pre> <p>if i use this command</p> <pre><code>&quot;develop&quot;: &quot;webpack serve --hot --port 8080 --allowed-hosts all --config webpack.develop.js&quot; </code></pre> <p>am getting below error</p> <pre><code>[webpack-cli] Invalid options object. Dev Server has been initialized using an options object that does not match the API schema. - options has an unknown property 'index'. These properties are valid: object { allowedHosts?, bonjour?, client?, compress?, devMiddleware?, headers?, historyApiFallback?, host?, hot?, http2?, https?, ipc?, liveReload?, magicHtml?, onAfterSetupMiddleware?, onBeforeSetupMiddleware?, onListening?, open?, port?, proxy?, server?, setupExitSignals?, setupMiddlewares?, static?, watchFiles?, webSocketServer? } </code></pre> <p>i removed index and localhost up and running but build.js is not created in dist folder.</p> <p>webpack.config.js</p> <pre><code>const fs = require('fs') const path = require('path') const webpack = require('webpack') const dotenv = require('dotenv') const BundleAnalyzerPlugin = require('webpack-bundle-analyzer') .BundleAnalyzerPlugin // Create .env file if it does not exist if (!fs.existsSync('.env')) { fs.copyFileSync('.env_example', '.env') } dotenv.config() if (!process.env.POSTS_SERVER_URL) { // webpack 5 is stricter about environment variables. The POSTS_SERVER_URL // environment variable was not mentioned in the README so default it for // those developers who may have created a .env file without the variable. process.env.POSTS_SERVER_URL = 'http://127.0.0.1:3000' } const PATHS = { app: path.join(__dirname, 'src/index.tsx'), } module.exports = { entry: { app: PATHS.app, }, output: { path: __dirname + '/dist', filename: 'bundle.js', }, module: { rules: [{ test: /\.(js|jsx|ts|tsx)$/, loader: 'babel-loader', exclude: /node_modules/, include: /src/, sideEffects: false, }, { test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'file-loader'}, { test: /\.(scss|css)$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader', options: { modules: { localIdentName: &quot;[hash:base64]&quot;, auto: true }, sourceMap: true } }, { loader: 'sass-loader' } ] } ], }, resolve: { extensions: ['.tsx', '.ts', '.js', '.css'], modules: [__dirname, 'node_modules' ], fallback: { buffer: false }, }, devtool: 'source-map' } </code></pre> <p>Can anyone suggest me where is my configuration is going wrong</p>
3
2,317
How to mock newly created objects inside Presenters method?
<p>I have PaymentPresenter with method payWorkOrder(). That method accepts some parameters and based on the logic created two new objects:</p> <ol> <li>WoPayment</li> <li>PaymentRequest</li> </ol> <p>Here is the code for that:</p> <pre><code>@RunWith(PowerMockRunner.class) @PrepareForTest({TextUtils.class, WoPayment.class, PaymentRequest.class}) public class PaymentPresenterTest extends BaseTest { @Rule TrampolineSchedulerRule trampolineSchedulerRule = new TrampolineSchedulerRule(); @Mock CustomersRepository customersRepository; @Mock AgreementsRepository agreementsRepository; @Mock WorkOrdersRepository workOrdersRepository; @Mock PaymentPresenter.View view; @Mock ResponseBody responseBody; private PaymentPresenter presenter; @Before public void setUp() { mockTextUtils(); presenter = new PaymentPresenter(customersRepository, agreementsRepository, workOrdersRepository); presenter.setView(view); } public void payWorkOrderInvoice(int workOrderId, double amount, String paymentMethod, String checkNumber) { disposables = RxUtil.initDisposables(disposables); WoPayment woPayment = new WoPayment(); if(amount &gt; 0) { woPayment.setAmount(amount); } else { view.displayAmountShouldBeGreaterThanZero(); return; } if(TextUtils.isEmpty(paymentMethod)) { view.displayPaymentMethodInvalid(); return; } else { woPayment.setPaymentMethod(paymentMethod); } if(paymentMethod.equalsIgnoreCase("Check") &amp;&amp; TextUtils.isEmpty(checkNumber)) { view.displayReferenceNumberError(); return; } else { woPayment.setCheckNumber(checkNumber); } view.disablePayButton(); Disposable disposable = workOrdersRepository.payWorkOrderInvoice(workOrderId, new PaymentRequest(woPayment)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(response -&gt; { if(response.isSuccessful()) { view.displayWorkOrderInvoicePaid(response.body()); } else { view.enablePayButton(); view.displayWorkOrderInvoiceNotPaid(); } }, throwable -&gt; { view.enablePayButton(); view.handleError(throwable); }); disposables.add(disposable); } } } </code></pre> <p>Here is my unit test:</p> <pre><code>@Test public void shouldPayWorkOrderInvoice() { // Given int workOrderId = 1; double amount = 1.0; String paymentMethod = "cash"; String checkNumber = "1"; WorkOrderDetails workOrderDetails = Mockito.mock(WorkOrderDetails.class); Response&lt;WorkOrderDetails&gt; response = Response.success(200, workOrderDetails); WoPayment woPayment = new WoPayment(); woPayment.setAmount(amount); woPayment.setCheckNumber(checkNumber); woPayment.setPaymentMethod(paymentMethod); PaymentRequest paymentRequest = new PaymentRequest(woPayment); // When Mockito.when(workOrdersRepository.payWorkOrderInvoice(workOrderId, paymentRequest)).thenReturn(Single.just(response)); presenter.payWorkOrderInvoice(workOrderId, amount, paymentMethod, checkNumber); // Then Mockito.verify(view).displayWorkOrderInvoicePaid(workOrderDetails); } </code></pre> <p><strong>It throws exception here:</strong></p> <pre><code>Disposable disposable = workOrdersRepository.payWorkOrderInvoice(workOrderId, new PaymentRequest(woPayment)) .subscribeOn(Schedulers.io()) </code></pre> <p>But it fails with the following stacktrace: </p> <blockquote> <p>java.lang.NullPointerException at com.test.presentation.agreements.payment.PaymentPresenter.payWorkOrderInvoice(PaymentPresenter.java:168) at com.test.presentation.agreements.PaymentPresenterTest.shouldPayWorkOrderInvoice(PaymentPresenterTest.java:175) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68) at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310) at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89) at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97) at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294) at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127) at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.access$100(PowerMockJUnit47RunnerDelegateImpl.java:59) at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner$LastRuleTestExecutorStatement.evaluate(PowerMockJUnit47RunnerDelegateImpl.java:148) at com.test.presentation.core.TrampolineSchedulerRule$1.evaluate(TrampolineSchedulerRule.java:21)</p> </blockquote>
3
1,761
Unable to send Array to correct destination processor in MPI
<p>I am trying to send an array to the different processors in the hypercube architecture. The problem is that it either doesn't send to all the processors or it sends to wrong processor. When I try to send a single integer it works correctly.</p> <p>Here is the code:</p> <pre><code>void hypercube(int d,int my_id,int X[]){ mask = (int)pow((double)2,d)-1; for(i = d-1;i&gt;=0;i--){ //printf("before xor mask is %d and power is %d\n",mask,(int)pow((double)2,i)); mask = xor(mask,(int)pow((double)2,i)); //printf("After xor rank is %d and mask is %d\n",rank,mask); if(and(my_id, mask) == 0){ if(and(my_id,(int) pow((double)2,i)) == 0){ dest = xor(my_id,(int) pow((double)2,i)); printf("rank %d destination %d\n",rank,dest); MPI_Send(&amp;X,8,MPI_INT,dest,tag,MPI_COMM_WORLD);; //MPI_Send(&amp;X,1,MPI_INT,dest,tag,MPI_COMM_WORLD); //printf("After sending from rank %d and destination is %d\n",my_id,dest); } else{ //printf("going to receive in a sec...\n"); source = xor(my_id,(int)pow((double)2,i)); MPI_Recv(&amp;X,8,MPI_INT,source,tag,MPI_COMM_WORLD,&amp;status); //MPI_Recv(&amp;X,1,MPI_INT,source,tag,MPI_COMM_WORLD,&amp;status); //printf("in rank %d with data %d\n",rank,X); } } } } int main(int argc, char **argv){ MPI_Init(&amp;argc,&amp;argv); MPI_Comm_size(MPI_COMM_WORLD,&amp;world_size);; MPI_Comm_rank(MPI_COMM_WORLD,&amp;rank); if(rank == master){ //a[ARR_SIZE] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}; // q = 4; } hypercube(3,rank,a); return 0; } </code></pre> <p>Is there anything that I am not taking care of??</p>
3
1,037
Unable to Use String Result From AJAX Request
<p>The issue I am having is that I cannot seem to USE the result passed back to the original <code>JS</code> file from the <code>PHP</code> file called from the request. This is the result and handler:</p> <pre><code>if(creds_verification() == true){ $.ajax({ url:"scripts/scripts.php", //the page containing php script type: "post", //request type, dataType: 'json', data: {url: URL, user: USER, password: PASS}, success:function(result){ var verdict = result if(verdict == "Yes"){ Call another external function }else{ console.log(results.abc) } } }); } </code></pre> <p>The console is constantly printing "Yes", aka the result of <code>results.abc</code>... why would this happen? It SHOULD be executing the next function...</p> <p><strong>Added Info</strong> <code>PHP</code> script running shell command and <code>echo</code>ing the result:</p> <p><strong>scripts.php</strong></p> <pre><code> &lt;?php $URL = $_POST['url']; $USER = $_POST['user']; $PASSWORD = $_POST['password']; echo json_encode(array("abc" =&gt; shell_exec("PATH.../phantomjs PATH/phantom/examples/test.js 2&gt;&amp;1 $URL $USER $PASSWORD"))); ?&gt; </code></pre> <p>And the <code>JS</code> file this is calling from the shell command:</p> <p><strong>test.js</strong></p> <pre><code>var system = require('system') var page = require('webpage').create() var script = document.createElement('script'); script.src = 'http://code.jquery.com/jquery-1.11.0.min.js'; script.type = 'text/javascript'; document.getElementsByTagName('head')[0].appendChild(script); var URL = system.args[1] var USER = system.args[2] var PASS = system.args[3] var steps = [ function() { page.open('http://'+URL+'/login.html') }, function() { page.evaluate(function(USER, PASS) { document.querySelector('input[name="log"]').value = USER document.querySelector('input[name="pwd"]').value = PASS document.querySelector('form').submit() }, USER, PASS) }, function(){ var newURL = page.url if(newURL == 'http://'+URL+'/user.html'){ console.log('Yes') }else{ console.log('No?') } } ] var stepindex = 0 var loading = false setInterval(executeRequestsStepByStep, 5000) function executeRequestsStepByStep(){ if (loading == false &amp;&amp; steps[stepindex]) { steps[stepindex]() stepindex++ } if (!steps[stepindex]) { phantom.exit() } } page.onLoadStarted = function() { loading = true } page.onLoadFinished = function() { loading = false } </code></pre>
3
1,033
Commands to get offline logs from wp7 using WPConnect?
<p>I know that we can get offline logs from WP7 devices using WPConnect tool. But i have forgotten the commands and also forgotten the site address from where i had learnt it. Does anyone know what are those commands. I have the following code to log offline exceptions, but i don't know how to retrieve the log file.. Please help.</p> <pre><code> #region Offline Error Logger /// &lt;summary&gt; /// Logs Exception for the app when the device is not connected to the PC.This file can later be retrieved for the purpose of Bug fixing /// &lt;/summary&gt; /// &lt;param name="strMsg"&gt;Exception message&lt;/param&gt; private static void LogOffline(string strMsg) { </code></pre> <h1>if LOG_ENABLED</h1> <pre><code> try { using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { string dirName = "SOSLog"; string logFileName = "SOSLog.txt"; string fullLogFileName = System.IO.Path.Combine(dirName, logFileName); // TODO: Synchronize this method with MainPage using Mutex string directoryName = System.IO.Path.GetDirectoryName(fullLogFileName); if (!string.IsNullOrEmpty(directoryName) &amp;&amp; !myIsolatedStorage.DirectoryExists(directoryName)) { myIsolatedStorage.CreateDirectory(directoryName); Debug.WriteLine("Created directory"); } if (myIsolatedStorage.FileExists(fullLogFileName)) { using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(fullLogFileName, FileMode.Append, FileAccess.Write)) { using (StreamWriter writer = new StreamWriter(fileStream)) { writer.WriteLine(strMsg); writer.Close(); } } } else { using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(fullLogFileName, FileMode.Create, FileAccess.Write)) { using (StreamWriter writer = new StreamWriter(fileStream)) { writer.WriteLine(strMsg); writer.Close(); } } } } } catch (Exception ex) { Debug.WriteLine("Exception while logging: " + ex.StackTrace); } </code></pre> <h1>endif</h1> <pre><code> } #endregion </code></pre>
3
1,394
Array size issue for converting String to Unicode
<p>I have a string "text" in one class which calls on a method in another class to convert text in various ways. In this method though I am left with an "ArrayIndexOutOfBoundsException" error.</p> <pre><code>public String toUnicode() { char unicodeTextArray[] = new char[text.length()]; if (text == null || text.isEmpty()) { return ""; } String unicodeTextArrayString[] = new String[text.length()]; for (int i = 0; i &lt; text.length(); i++) { unicodeTextArray[i] = text.charAt(i); if (unicodeTextArray[i] &lt; 0x10) { unicodeTextArrayString[i] = "\\u000" + Integer.toHexString(unicodeTextArray[i]); } else if (unicodeTextArray[i] &lt; 0x100) { unicodeTextArrayString[i] = "\\u00" + Integer.toHexString(unicodeTextArray[i]); } else if (unicodeTextArray[i] &lt; 0x1000) { unicodeTextArrayString[i] = "\\u0" + Integer.toHexString(unicodeTextArray[i]); } unicodeTextArrayString[i] = "\\u" + Integer.toHexString(unicodeTextArray[i]); } String unicode = unicodeTextArrayString[text.length()]; return unicode; } </code></pre> <p>Changing one line to an arbitrarily large number such as:</p> <pre><code>String unicodeTextArrayString[] = new String[9999]; </code></pre> <p>Results in no error, but it returns null. </p> <p>I thought about setting an int variable to increase the length of the array, but * 4 was still too small of an array size and it seems like if I go too large it just returns null.</p> <p>How could I go about getting the correct length of the array?</p> <p>EDIT: I found a non-array approach that works, but I would still like to know if there is a way to make the above array approach work in some way.</p> <pre><code>public String toUnicode() { String unicodeString = ""; for (int i = 0; i &lt; text.length(); i++) { char c = text.charAt(i); String s = String.format ("\\u%04x", (int)c); unicodeString = unicodeString + s; } return unicodeString; } </code></pre> <p>EDIT 2: In case anyone reading this is curious, to get the decimal value of the unicode:</p> <pre><code> public String toUnicode() { String unicodeString = ""; for (int i = 0; i &lt; text.length(); i++) { char c = text.charAt(i); int unicodeDecimal = c; unicodeString = unicodeString + unicodeDecimal + " "; } return unicodeString; } </code></pre> <p>EDIT 3: I ended up deciding to use the following, which separates unicode decimals by space, and checks for the unicode value 10 (which means new line) and outputs a new line into the string instead of that value.</p> <pre><code> public String toUnicode() { String unicodeString = ""; for (int i = 0; i &lt; text.length(); i++) { char c = text.charAt(i); int unicodeDecimal = c; if (unicodeDecimal == 10) { unicodeString = unicodeString + "\n"; } else { unicodeString = unicodeString + unicodeDecimal + " "; } } return unicodeString; } </code></pre>
3
1,394
QML Progress Bar doesn't move
<p>I am using QT v5.12.6 and in my application i am planning to use Progress Bar during application bootup for around 15secs. In this 15secs operations like:</p> <ol> <li>QML components creation.</li> <li>connection with the server.</li> <li>Other bootup operations will be running in the background.</li> </ol> <p>Once, all the bootup operation is done i will hide my splash screen which is just a Rectangle which includes Loading text with a progress bar. For this 15 secs i will be incrementing the progress bar but the progress bar doesn't increment/move for some 10 secs. It looks like it is hanged, but if i use a busy indicator it starts to rotate. Unfortunately, i can't use busy indicator component as i need a look and feel like a progress bar.</p> <p>My application runs on a embedded platform which has low end processor and very less RAM speed. I am assuming this problem is due to the Load on the UI as many components is getting created.</p> <p>Is there any difference between busy indicator and Progress bar and also any suggestions on how to handle UI load on the bootup ?</p> <p><strong>Edit 1:</strong> Added an example. I have tried my level best to mimic the problem. In this example both the busyindicator and Progress bar is getting stuck for sometime. But in the embedded device Busy indicator works but no idea how. After running the application Please click on <strong>Click Me</strong> button.</p> <pre><code>import QtQuick 2.12 import QtQuick.Window 2.12 import QtQuick.Controls 2.3 Window { property int pbValue:0 visible: true width: 500 height: 400 title: qsTr(&quot;Hello World&quot;) Rectangle{ id: mySplashScreen anchors.fill: parent ProgressBar{ id: pBar height: 20 width: parent.width anchors.bottom: parent.bottom from:0 value : pbValue to:30 } BusyIndicator{ anchors.right: parent.right running: (pbValue &lt; pBar.to +1) } Button{ text: &quot;click me&quot; onClicked: { //Create component equivalent to my application which has &quot;n&quot; //number of components like buttons, combobox, chart view etc. //Here just creating the rectangle more number of times. for(var i = 0 ; i &lt; 15000 ;i++) //HINT : Increase/decrease the value if problem is not seen { var comp = mycomp.createObject(mySplashScreen) } } } } Timer{ id:timer interval: 250 running: (pbValue &lt; pBar.to +1) onTriggered: { pbValue += 1; } } Component{ id:mycomp Rectangle{ width: 200 height: 200 color: &quot;green&quot; } } } </code></pre>
3
1,168
Scroll background container in Flutter
<p>I am trying to build scrollable screen, where brown background Container must scroll with List of elements when black container near this container. How can I do it? I thought about Positioned, but I can't build items above SliverAppbar even if I build it in different Stack.</p> <p>May I build body above SliverAppbar or how can I realise this?</p> <p><a href="https://i.stack.imgur.com/zSy7M.png" rel="nofollow noreferrer"></a></p> <pre><code>return Scaffold( body: Stack( children: [ Container( height: MediaQuery.of(context).size.height * 0.45, decoration: const BoxDecoration( color: AppColors.mainBrown, borderRadius: BorderRadius.vertical(bottom: Radius.circular(30)), ), ), CustomScrollView( slivers: [ const SliverAppBar( expandedHeight: 70, backgroundColor: Colors.transparent, elevation: 0, shadowColor: Colors.transparent, titleSpacing: 22, title: Text('AppBar'), ), SliverPadding( padding: const EdgeInsets.symmetric(horizontal: 30), sliver: SliverList( delegate: SliverChildListDelegate([ Card( child: Container( color: Colors.brown, height: 200, ), ), Card( child: Container( color: Colors.yellow, height: 250, ), ), Card( child: Container( color: Colors.black, height: 300, ), ), Card( child: Container( color: Colors.red, height: 50, ), ), Card( child: Container( color: Colors.green, height: 100, ), ), Card( child: Container( color: Colors.blue, height: 150, ), ), ]), ), ) ], ), ], ), ); </code></pre>
3
1,341
django with docker dosen't see pillow
<p>I'm trying to deploy my project on django. I almost did it but django can't see installed pillow in docker container. I'm sure that it's installed pip sends me this:</p> <pre><code>sudo docker-compose -f docker-compose.prod.yml exec web pip install pillow Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: pillow in /usr/local/lib/python3.8/site-packages (8.1.0) </code></pre> <p>But when i'm trying to migrate db i see this:</p> <pre><code>ERRORS: history_main.Exhibit.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command &quot;python -m pip install Pillow&quot;. history_main.MainUser.avatar: (fields.E210) Cannot use ImageField because Pillow is not installed. </code></pre> <p>Here are parts of Dockerfile where Pillow tries to install:</p> <pre><code>RUN apk update \ &amp;&amp; apk add postgresql-dev gcc python3-dev musl-dev jpeg-dev zlib-dev build-base RUN pip install --upgrade pip COPY ./req.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r req.txt </code></pre> <p>...</p> <pre><code>RUN apk update &amp;&amp; apk add libpq COPY --from=builder /usr/src/app/wheels /wheels COPY --from=builder /usr/src/app/req.txt . RUN pip install --no-cache /wheels/* </code></pre> <p>docker-compose:</p> <pre><code>version: '3.7' services: web: build: context: ./app dockerfile: Dockerfile.prod command: gunicorn hello_django.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles expose: - 8000 env_file: - ./.env.prod depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db nginx: build: ./nginx volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles ports: - 1337:80 depends_on: - web volumes: postgres_data: static_volume: media_volume: </code></pre> <p>dockerfile for web:</p> <pre><code>########### # BUILDER # ########### # pull official base image FROM python:3.8.3-alpine as builder # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ &amp;&amp; apk add postgresql-dev gcc python3-dev musl-dev # lint RUN pip install --upgrade pip RUN pip install flake8 COPY . . RUN flake8 --ignore=E501,F401 . # install dependencies COPY ./req.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r req.txt ######### # FINAL # ######### # pull official base image FROM python:3.8.3-alpine # create directory for the app user RUN mkdir -p /home/app # create the app user RUN addgroup -S app &amp;&amp; adduser -S app -G app # create the appropriate directories ENV HOME=/home/app ENV APP_HOME=/home/app/web RUN mkdir $APP_HOME WORKDIR $APP_HOME # install dependencies RUN apk update &amp;&amp; apk add libpq COPY --from=builder /usr/src/app/wheels /wheels COPY --from=builder /usr/src/app/req.txt . RUN pip install --no-cache /wheels/* # copy entrypoint-prod.sh COPY ./entrypoint.prod.sh $APP_HOME # copy project COPY . $APP_HOME # chown all the files to the app user RUN chown -R app:app $APP_HOME # change to the app user USER app # run entrypoint.prod.sh ENTRYPOINT [&quot;/home/app/web/entrypoint.prod.sh&quot;] </code></pre>
3
1,422
What is the difference between "Persistent Class" and "Entity" in JPA or in Hibernate?
<p>First things first:</p> <ol> <li>I'm aware of <a href="https://stackoverflow.com/questions/28372601/what-is-the-difference-between-entity-and-persistent-class">this</a> question, which, at the high level of abstraction, asks same what I ask here; however, I find it (and its answer) lacking, therefore, I would like to elaborate on this topic here;</li> <li>I would kindly ask anyone, who has a good understanding of the <em>formal definitions</em> in the JPA and Hibernate, to help me clarify this mess.</li> </ol> <p>Disclaimer: I am not looking for the basic explanations of what the Entity is and how to use it. I am using Hibernate/JPA for quite some time now.</p> <p>My question is more about <em>formal definitions</em>, in order to clarify the distinctions of the formal semantics (definitions) between <em>Entity</em> and <em>Persistent Class</em>, to make it crystal-clear how one differs from another and how they are defined.</p> <p>Initially, I expected the answer to be found in <a href="https://download.oracle.com/otn-pub/jcp/persistence-2_2-mrel-spec/JavaPersistence.pdf" rel="nofollow noreferrer">JSR 338: JPA Specification 2.2</a> and <a href="https://docs.jboss.org/hibernate/orm/5.0/manual/en-US/html/" rel="nofollow noreferrer">Hibernate 5.0.0 Reference Documentation</a>, but I got quite confused, as I was left with a feeling, that, in this context, both documents are lacking, leaving a big room for these concepts/definitions to overlap and introduce some speculations.</p> <hr /> <h2>Let's start with JSR 338: JPA 2.2 Specification:</h2> <p>For some (very strange to me) reason, in this entire specification, keyword phrases &quot;Persistent Object&quot; and &quot;Persistent Class&quot; are not found, to wit, they are found only once and twice respectively:</p> <blockquote> <ul> <li><em>Persistent Object</em> - found in the Javadoc comment, saying nothing interesting (page 221)</li> <li><em>Persistent Class</em> - found in the xsd documentation, again, saying nothing much (pages: 378, 529)</li> </ul> </blockquote> <p>and, unfortunately, that is it in this specification, nothing more at all.</p> <p>The <em>Entity Class</em>, on the other hand, is defined as follows:</p> <blockquote> <p>An entity is a lightweight persistent domain object. The primary programming artifact is the entity class. An entity class may make use of auxiliary classes that serve as helper classes or that are used to represent the state of the entity.</p> </blockquote> <p>which, again, I find extremely lacking for the formal specification document, but at least, this says that it is a <em>persistent domain object</em>.</p> <p>In the same document, <em>Entity</em> is also defined as a Class (2.1 The Entity Class, page 23).</p> <p>Even though this might not seem important, it's quite confusing whether it's defined as a <em>Persistent Object</em> or as a <em>Class</em>.</p> <p><strong>My conclusion based on this specification document:</strong></p> <ol> <li><em>Persistent Class/Object</em> is not defined in the JPA 2.2 Specification at all;</li> <li><em>Entity</em> is defined as <em>persistent object</em>, <strong>and(!)</strong>, as a <em>Class</em>, which is really unclear to me;</li> </ol> <p>In my conceptual understanding, <em>Persistent Object</em>, sounds very much as an object, which is persist<em>able</em> <strong>if(!)</strong> it will be mapped correspondingly; hence, <em>Persistent Class</em> - as a <em>Class</em>, instances of which are possible to get persisted (i.e. they can be stored into database layer, by conforming to POJO concept), if the class is mapped accordingly. I.e. <em>Persistent Class</em> is a persist<em>able</em> class, and it transforms to <em>Entity</em>, if it has its corresponding mapping definition (either with .hbm.xml or JPA annotations).</p> <hr /> <h2>Hibernate 5 Reference Documentation</h2> <p>On the other hand, Hibernate <a href="https://docs.jboss.org/hibernate/orm/5.0/manual/en-US/html/ch04.html" rel="nofollow noreferrer">defines</a> <em>Persistent Classes</em>, and it does this as follows:</p> <blockquote> <p>Persistent classes are classes in an application that implement the entities of the business problem (e.g. Customer and Order in an E-commerce application). The term &quot;persistent&quot; here means that the classes are able to be persisted, not that they are in the persistent state.</p> </blockquote> <p>Am I getting this correct, that <em>Persistent Classes implement the entity</em> means, that my upper understanding is correct, and <em>Persistent Class</em> is just a Java class, which implements the <em>Entity</em> model (without mapping), and in conjunction with its mapping (.hbm.xml or JPA) it becomes an <em>Entity</em>? is <em>Persistent Class + Mapping Definition = Entity</em> correct?</p> <hr /> <p>I would also plug here in some snippets from the <a href="https://www.manning.com/books/java-persistence-with-hibernate-second-edition" rel="nofollow noreferrer">Java Persistence with Hibernate, Second Edition</a> book:</p> <blockquote> <p>You wrote a persistent class and its mapping with annotations. - (Summary 2.4);</p> </blockquote> <p><em>kind of, differentiates persistent class from its mapping, and that, again, sort of supports the idea, that persistent class and its mapping are distinct concepts, which logically brings the point, that persistent class alone, is not an Entity.</em></p> <blockquote> <p>The persistent classes are unaware of—and have no dependency on—the persistence mechanism. - (Chapter 3.2);</p> </blockquote> <p><em>clearly states, that Persistent Classes are unaware of the persistence mechanism.</em></p> <blockquote> <p>You can reuse persistent classes outside the context of persistence, in unit tests or in the presentation layer, for example. You can create instances in any runtime environment with the regular Java new operator, preserving testability and reusability. - (Chapter 3.2).</p> </blockquote> <p><em>also supports the idea, that Persistent Class is not necessarily a mapped Entity.</em></p> <p><strong>My conclusion:</strong><br>(based on my initial understanding, which seems to be supported by &quot;Hibernate Reference Documentation&quot; and &quot;Java Persistence with Hibernate, Second Edition&quot; book.)</p> <p><em>Persistent Classes</em> are Java classes, which (if needed!) would be conforming with the JPA Specification (according to which, they need to be POJOs and they can be mapped), but they are not Entities if they are not mapped, and they can be used in the outside-of-JPA context, to just operate on them as on ordinary Java objects, or even to present them at the Presentation Layer.</p> <hr /> <h2>Finally:</h2> <p>As you can see, my question is a bit of a mixture of different resources, showing my evident confusion, as I cannot clearly define the <em>formal</em>, so called <em>scientifically adopted</em> definitions for these two concepts.</p> <p>Can we clearly define what is the <em>Persistent Class</em>, what is <em>Entity</em>, and what is the the <em>semantic</em> and <em>definitive</em> difference/overlapping between them in terms of JPA and Hibernate?</p>
3
2,095
Angular 2 - http.get never being call
<p>Im learning Angular 4 and have run into a problem that I cannot seem to find a solution to. Here is the context: I have a simple app that displays info about US Presidents. The backend is a rest API provided by webapi...this works fine. The front end is an Angular app.</p> <p>Ive distilled the problem down to 3 components, 1 data service and 1 model. Here is the model:</p> <pre><code>export class President { constructor( public id: number, public presidentName: string, public presidentNumber: number, public yearsServed: string, public partyAffiliation: string, public spouse: string) {} } </code></pre> <p>The 3 components are 1. SearchComponent 2. HomeComponent 3. PresidentComponent</p> <p>When the app bootstraps, it loads the ApplicationComponent - it is the root component:</p> <pre><code>import { Component, ViewEncapsulation } from '@angular/core'; @Component({ selector: 'my-app', template: ` &lt;search-component&gt;&lt;/search-component&gt; &lt;home-component&gt;&lt;/home-component&gt; ` }) export class ApplicationComponent {} </code></pre> <p>PresidentComponent is a child component of HomeComponent. When home component loads, it makes an http call to the api to get a list of presidents and renders 1 presidentComponent for each row returned. This works fine.</p> <p>What Im trying to do is implement a search feature where the dataService exposes an EventEmitter and provides the search method as shown here:</p> <pre><code>import { Injectable, EventEmitter, Output } from '@angular/core' import { President } from '../models/President' import { Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import 'rxjs/add/operator/map'; import { Observable } from 'rxjs/Observable'; @Injectable() export class DataService { constructor(private http: Http) { } searchEvent: EventEmitter&lt;any&gt; = new EventEmitter(); // simple property for the url to the api get presidentUrl { return "http://localhost:51330/api/presidents"; } search(params: any): Observable&lt;President[]&gt; { let encParams = encodeParams(params); console.log(encParams); return this.http .get(this.presidentUrl, {search: encParams}) .map(response =&gt; response.json()); } getParties(): String[] { return ['Republican', 'Democrat', 'Federalist', 'Whig', 'Democratic-Republican', 'None']; } getPresidents(): Observable&lt;President[]&gt; { return this.http.get(this.presidentUrl) .map(response =&gt; response.json()); } } /** * Encodes the object into a valid query string. * this function is from the book Angular2 Development with TypeScript */ function encodeParams(params: any): URLSearchParams { return Object.keys(params) .filter(key =&gt; params[key]) .reduce((accum: URLSearchParams, key: string) =&gt; { accum.append(key, params[key]); return accum; }, new URLSearchParams()); } </code></pre> <p>The Search Component houses the search form and when the search button is clicked, it executes the onSearch() function and calls emit on the data service:</p> <pre><code>onSearch(){ if(this.formModel.valid){ console.log('emitting event from search.ts'); this.dataService.searchEvent.emit(this.formModel.value); } } </code></pre> <p>Then, in the HomeComponent, I want to subscribe to this event and execute a search via the dataservice when it fires:</p> <pre><code> ngOnInit(): void { //when component loads, get list of presidents this.dataService.getPresidents() .subscribe( presidents =&gt; { console.log('sub'); this.presidents = presidents; }, error =&gt; console.error(error) ) //when search event is fired, do a search this.dataService.searchEvent .subscribe( params =&gt; { console.log('in home.ts subscribe ' + JSON.stringify(params)); this.result = this.dataService.search(params); }, err =&gt; console.log("cant get presidents. error code: %s, URL: %s"), () =&gt; console.log('done') ); } </code></pre> <p>When I run this in the browser, everything works except the http call is never executed. If I subscribe() to the http.get call in the dataservice itself, it executes but why should I have to do that when I have a subscription being setup on the HomeComponent? I want to handle the Observable in the HomeComponent and update the list of presidents that is being displayed in the UI based on the search result. Any advice is greatly appreciated.</p>
3
1,732
JPQL (Hibernate implementation) select with join issues
<p>I'm having a bit of a rough time with JPQL (using Hibernate).</p> <p>I have 2 Entities:</p> <pre><code>package org.oscarehr.common.model; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.OneToMany; import javax.persistence.PrePersist; import javax.persistence.JoinColumn; import javax.persistence.CascadeType; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; @Entity @Table(name="spireAccessionNumberMap") public class SpireAccessionNumberMap extends AbstractModel&lt;Integer&gt; { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name="uaccn") private Integer uaccn; @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER) @JoinColumn(name="uaccn_id", referencedColumnName="id") private List&lt;SpireCommonAccessionNumber&gt; commonAccessionNumbers = new ArrayList&lt;SpireCommonAccessionNumber&gt;(); public SpireAccessionNumberMap() { } public SpireAccessionNumberMap(Integer uniqueAccn) { this.uaccn = uniqueAccn; } //@Override public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUniqueAccessionNumber() { return uaccn; } public void setUniqueAccessionNumber(Integer uaccn) { this.uaccn = uaccn; } public List&lt;SpireCommonAccessionNumber&gt; getCommonAccessionNumbers() { return commonAccessionNumbers; } @PrePersist public void prePersist() { Iterator&lt;SpireCommonAccessionNumber&gt; i = this.commonAccessionNumbers.iterator(); SpireCommonAccessionNumber commonAccessionNumber; while(i.hasNext()) { commonAccessionNumber = i.next(); commonAccessionNumber.setUniqueAccessionId(this.uaccn); } } } </code></pre> <p>and</p> <pre><code>package org.oscarehr.common.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; @Entity @Table(name="spireCommonAccessionNumber") public class SpireCommonAccessionNumber extends AbstractModel&lt;Integer&gt; { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name="caccn") private String caccn; @ManyToOne @JoinColumn(name="uaccn_id", referencedColumnName="id") private Integer uaccn_id; //@Override public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCommonAccessionNumber() { return caccn; } public void setCommonAccessionNumber(String caccn) { this.caccn = caccn; } public Integer getUniqueAccessionId() { return uaccn_id; } public void setUniqueAccessionId(Integer uaccn_id) { this.uaccn_id = uaccn_id; } } </code></pre> <p>Basically, I have the 'map' object, which has a unique number associated with it. The map object has a 'link' to 1 or more 'commonNumber' objects, which store a 'common' number.</p> <p>The idea is to be able to map lots of common numbers to a unique number using the JPQL and 'Dao's.</p> <p>However, when I deploy my java WAR file, I get this error:</p> <pre><code>2013-01-04 13:42:12,344 INFO [Version:14] Hibernate Commons Annotations 3.1.0.GA 2013-01-04 13:42:12,347 INFO [Version:16] Hibernate EntityManager 3.4.0.GA 2013-01-04 13:42:17,753 ERROR [ContextLoader:215] Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [spring_jpa.xml]: Invocati on of init method failed; nested exception is org.hibernate.AnnotationException: @OneToOne or @ManyToOne on org.oscarehr.common.model.SpireCommonAccessionNumber.uaccn_ id references an unknown entity: java.lang.Integer at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:567) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464) at org.oscarehr.common.web.OscarSpringContextLoader.createWebApplicationContext(OscarSpringContextLoader.java:97) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4206) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4705) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:799) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:779) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:601) at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:943) at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:778) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:504) at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1385) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:306) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142) at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1389) at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1653) at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1662) at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1642) at java.lang.Thread.run(Thread.java:679) Caused by: org.hibernate.AnnotationException: @OneToOne or @ManyToOne on org.oscarehr.common.model.SpireCommonAccessionNumber.uaccn_id references an unknown entity: java.lang.Integer at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:81) at org.hibernate.cfg.AnnotationConfiguration.processEndOfQueue(AnnotationConfiguration.java:456) at org.hibernate.cfg.AnnotationConfiguration.processFkSecondPassInOrder(AnnotationConfiguration.java:438) at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:309) at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1148) at org.hibernate.ejb.Ejb3Configuration.buildMappings(Ejb3Configuration.java:1226) at org.hibernate.ejb.EventListenerConfigurator.configure(EventListenerConfigurator.java:173) at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:854) at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:425) at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:131) at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:257) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452) ... 28 more </code></pre> <p>I'm at a bit of a loss here...I've tried fiddling around with different ways to map the 'common' object to the 'map' object, but I keep getting errors.</p> <p>Would anyone be able to shed some light on this for me?</p>
3
3,417
Geolocation directs to building entrance and not defined LatLng
<p>I am currently adapting and cleaning up a very simple Google Maps application for users to get walking directions from their current location (determined by GeoLocation) to preset markers designating artworks that are defined with specific LatLng values to the sixth decimal.</p> <p>There is still a lot of extraneous code in the example that needs to be removed, but the core function is working as expected - almost.</p> <p>When the user selects a destination from the values supplied in a dropdown menu and hits enter, a lined path appears from where they are to the selected destination - using the calcRoute function. </p> <p>However, the path is consistently directing the user to the nearest building entrance - which in some cases is several hundred feet away from the LatLng defined in the code. This does not appear to be random inaccuracy, as the path always ends at a building entrance.</p> <p>I am sure this is a very simple mistake I am making, but I haven't found any posts that seem to address this odd behavior.</p> <p>I am using Windows 8 and Chrome at the moment for the base development in an attempt to get a working version and then test on other browsers. I appreciate any advice, and will supply all the example code if needed. Here is a sample of some of the typical lines in this app:</p> <pre><code>&lt;script src="https://maps.googleapis.com/maps/api/js?v=3.exp&amp;signed_in=true"&gt; &lt;/script&gt; &lt;script&gt; var locTreeWrapIII = new google.maps.LatLng(48.006640, -122.203680); &lt;/script&gt; // Tree Wrap III var markerTreeWrapIII = new google.maps.Marker({ map: map, position: locTreeWrapIII, title: 'Tree Wrap III' }); var infoTreeWrapIII = new google.maps.InfoWindow({ // info window maxWidth: 400, content: '&lt;img alt="" src="https:\/thumbnail-clothespins.jpg" /&gt;' + '&lt;strong&gt;' + markerTreeWrapIII.title + '&lt;\/strong&gt;&lt;br \/&gt;&lt;br \/&gt;&lt;br \/&gt; &lt;a href="http:\/\/xx\/tree-wrap-iii"&gt;Read more about Tree Wrap III&lt;/a&gt;' }); google.maps.event.addListener(markerTreeWrapIII, "click", function () { document.getElementById('end').value = "(48.006500,-122.203500)"; infoTreeWrapIII.open(map, markerTreeWrapIII); infoTreeWrapIII.setZIndex(999); }); google.maps.event.addListener(markerTreeWrapIII, "dblclick", function () { map.panTo(locTreeWrapIII); }); google.maps.event.addListener(infoTreeWrapIII, "closeclick", function () { infoTreeWrapIII.setZIndex(1); infoTreeWrapIII.close(); }); function calcRoute() { // Retrieve the start and end locations and create // a DirectionsRequest using WALKING directions. var start = document.getElementById('start').value; var end = document.getElementById('end').value; var request = { origin: start, destination: end, travelMode: google.maps.TravelMode.WALKING }; // Route the directions and pass the response to a // function to create markers for each step. directionsService.route(request, function (response, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response); } }); } function attachInstructionText(marker, text) { google.maps.event.addListener(marker, 'click', function () { // Open an info window when the marker is clicked on, // containing the text of the step. stepDisplay.setContent(text); stepDisplay.open(map, marker); }); } </code></pre>
3
1,183
JOGL Native Crash
<p>I am running a JOGL based application, and it has been crashing when I perform certain drawing operations. However, The line it crashes on is a call to <code>gl.glGenLists(1)</code>, so I'm not really sure how this could cause an error in the underlying application, since this line is a trivial line (unless the stack is in some sort of bad state - is that possible?).</p> <p>I also tried updating my video card drivers and now it just freezes in the same place instead of crashing.</p> <p>The relevant part of the crash report is below. Any help would be appreciated. I'm running an NVIDIA Quadro NVS 160M video card. Thanks.</p> <pre><code># # A fatal error has been detected by the Java Runtime Environment: # # EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x6dd7ccac, pid=5520, tid=5684 # # JRE version: 6.0_16-b01 # Java VM: Java HotSpot(TM) Client VM (14.2-b01 mixed mode windows-x86 ) # Problematic frame: # C [nvoglnt.dll+0x23ccac] # # If you would like to submit a bug report, please visit: # http://java.sun.com/webapps/bugreport/crash.jsp # The crash happened outside the Java Virtual Machine in native code. # See problematic frame for where to report the bug. # --------------- T H R E A D --------------- Current thread (0x692c4c00): JavaThread "AWT-EventQueue-0" [_thread_in_native, id=5684, stack(0x696f0000,0x69740000)] siginfo: ExceptionCode=0xc0000005, writing address 0x00040008 Registers: EAX=0x6d360798, EBX=0x6e562ffc, ECX=0x00040000, EDX=0xffffffff ESP=0x6973ee1c, EBP=0x0000000d, ESI=0x6d360650, EDI=0x6d362311 EIP=0x6dd7ccac, EFLAGS=0x00010246 Top of Stack: (sp=0x6973ee1c) 0x6973ee1c: 00001343 00000014 00001344 6e563040 0x6973ee2c: 00000000 6d362310 00000040 7ffad000 0x6973ee3c: 6dd7cdb8 6e562ffc 00001343 6e3c7540 0x6973ee4c: 6dc792a8 00000014 6dbdb13b 00000001 0x6973ee5c: 6e3c7540 6d620000 6973ee90 6dc06fb8 0x6973ee6c: 6d620000 6e3c7540 00000001 692c4c00 0x6973ee7c: 63e576a0 63d38030 6b6c4c0e 00000001 0x6973ee8c: 0ab4f368 6973eeb8 010669c7 692c4d10 Instructions: (pc=0x6dd7ccac) 0x6dd7cc9c: 00 8b 4b 08 8b 7b 04 89 79 04 8b 4b 04 8b 7b 08 0x6dd7ccac: 89 79 08 0f 84 8c 00 00 00 8b 4c 24 14 8b 7c d1 Stack: [0x696f0000,0x69740000], sp=0x6973ee1c, free space=315k Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code) C [nvoglnt.dll+0x23ccac] Java frames: (J=compiled Java code, j=interpreted, Vv=VM code) J com.sun.opengl.impl.GLImpl.glGenLists0(I)I ...I omitted the rest of the stack, as this is the offending line ... </code></pre>
3
1,032
discord.py bot hosted on heroku wont go online
<p>I decided to use heroku to run my bot 24/7. I deployed, saw my dyno running, no errors and it was even switched on. I expected the bot to come online because of the deploy but it just stayed offline.</p> <p>Here is my bot code:</p> <pre><code>import discord import os import asyncio import random from discord.ext import commands, tasks from itertools import cycle TOKEN = 'XXXXX' client = commands.Bot(command_prefix = '/') client.remove_command('help') status = cycle(['Helping my Creator!', 'Moderating this server. smh']) messages = 0 @client.event async def on_ready(): change_status.start() print('Bot has connected.') @client.event async def on_message(message): global messages messages +-1 bad_words = [(just a list of bad words)] for word in bad_words: if message.content.count(word) &gt; 0: print('Someone said a bad word') await message.channel.purge(limit = 1) await client.process_commands(message) @tasks.loop(minutes = 5) async def change_status(): await client.change_presence(activity = discord.Game(next(status))) @client.command() async def cheese(ctx): responses = ["Here's some Parmesan.:cheese:", "Here's some Pecorino.:cheese:", "Here's some Manchego.:cheese:", "Here's some Grana-Padano.:cheese:", "Here's some Cheddar.:cheese:", "Here's some Gouda.:cheese:", "Here's some Harvati.:cheese:", "Here's some Gruyere.:cheese:", "Here's some Gorgonzola.:cheese:", "Here's some Stilton.:cheese:", "Here's some Roquefort.:cheese:", "Here's some Danish Blue.:cheese:", "Here's some Brie.:cheese:", "Here's some Camembert.:cheese:", "Here's some Double Creme White.:cheese:", "Here's some Cream Cheese.:cheese:", "Here's some Feta.:cheese:", "Here's some Mozzarella.:cheese:", "Here's some Burrata.:cheese:", "Here's some Chevre.:cheese:", "Here's some Goat Brie.:cheese:", "Here's some Blue Goat Cheese.:cheese:"] await ctx.send(random.choice(responses)) @client.command() async def userinfo(ctx, member: discord.Member = None): member = ctx.author if not member else member embed = discord.Embed(colour = member.color, timestamp = ctx.message.created_at) embed.set_author(name = f"User info - {member}") embed.set_thumbnail(url = member.avatar_url) embed.set_footer(text = f"Requested by {ctx.author}", icon_url = ctx.author.avatar_url) embed.add_field(name = "ID:", value = member.id) embed.add_field(name = "Guild name:", value = member.display_name) embed.add_field(name = "Created at:", value member.created_at.strftime("%a, %d %B %Y, %I:%M %p UTC")) embed.add_field(name = "Joined at:", value = member.joined_at.strftime("%a, %d %B %Y, %I:%M %p UTC")) embed.add_field(name = "Bot?", value = member.bot) await ctx.send(embed = embed) client.run(TOKEN) </code></pre> <p>Here is my procfile:</p> <pre><code>worker: python3 modbotv4.py </code></pre> <p>My requirements.txt file:</p> <pre><code>git+https://github.com/Rapptz/discord.py dnspython==1.16.0 PyNaCl==1.3.0 async-timeout==3.0.1 </code></pre> <p>And my runtime.txt file:</p> <pre><code>python-3.8.3 </code></pre> <p>If there is anything I should add in any of the files in order to make my bot go online, please tell me.</p>
3
1,596
Pytorch : Neural network is not learning at all
<p>I'm new to deep learning so I might just miss something stupid.</p> <p>I'm training several neural networks on trees. I'm trying to generate trees with my neural networks, and I have a reward function to select the best trees after each generation. I try to learn on the 100 best trees, but when I try to learn, my loss is computed correctly but it's constant even after several <code>optimizer.step()</code>. I honestly have no idea why it's not working. I'm using <code>torch.nn.CrossEntorpyLoss</code> and <code>torch.optim.SGD</code>. Here's my entire code but I think the problem is in the <code>learn</code> function. I can give further explanation if necessary.</p> <pre><code>import torch import random as rd import networkx as nx import numpy as np import heapq from time import time import matplotlib.pyplot as plt n = 19 # Taille de l'arbre n_edg = 171 # Taille des vecteurs iters = 10000 # Nombre d'itérations bests = 100 # Nombre de graphes sur lesquels on apprend const = 1 + (n - 1) ** 0.5 # Constante du problème def create_net(in_size, out_size): l1 = torch.nn.Linear(in_size, 64) r1 = torch.nn.ReLU() l2 = torch.nn.Linear(64, 8) r2 = torch.nn.ReLU() l3 = torch.nn.Linear(8, out_size) s = torch.nn.Softmax(0) return torch.nn.Sequential(l1, r1, l2, r2, l3, s) net_list = [create_net(i * (i - 1) // 2, i) for i in range(2, n)] def from_edge_vec(g): G = nx.Graph() G.add_nodes_from(range(n)) G.add_edge(0, 1) index = 0 for i in range(n - 1): for j in range(i + 1): if g[index]: G.add_edge(i + 1, j) index += 1 return G def reward(g, G): return g, np.max(nx.adjacency_spectrum(G)) + len(nx.max_weight_matching(G)) - const def sortSecond(elt): return elt[1] def meanSecond(list): acc = 0 for _, r in list: acc += r return acc / len(list) def step(): v = torch.zeros(iters, n_edg) v[:, 0] = 1 max_index = 1 for i in range(n - 2): out = net_list[i](v[:, :max_index]) val = torch.multinomial(out, 1) for j in range(iters): v[j, max_index + val[j]] = 1 max_index += i + 2 l = map(from_edge_vec, v) acc = map(reward, v, l) learn_graphs = heapq.nsmallest(bests, acc, key = sortSecond) return learn_graphs def learn(graph_list): criterion = torch.nn.CrossEntropyLoss() prog_v = torch.zeros(bests, n_edg) prog_v[:, 0] = 1 max_index = 1 for i in range(n - 2): net = net_list[i] optimizer = torch.optim.SGD(net.parameters(), lr=1e-2) label = torch.empty(bests, dtype = torch.long) for j in range(bests): label[j] = torch.argmax(graph_list[j][0][max_index:max_index + i + 2]) loss = 1 # while loss &gt; 0.1: for _ in range(5): out = net(prog_v[:, :max_index]) # print(label) # print(prog_v) loss = criterion(out, label) print(loss) optimizer.zero_grad() loss.backward() optimizer.step() for j in range(bests): prog_v[j, max_index + label[j]] = 1 max_index += i + 2 mean_result = [] best = [None, 100] t = time() for epoch in range(3): res = step() if res[0][1] &lt; best[1]: best = res[0] mean_result.append(meanSecond(res)) learn(res) print(epoch) print(time() - t) print(mean_result) print(best) nx.draw(from_edge_vec(best[0])) plt.show() </code></pre>
3
1,594
Pandas IndexingError - Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match)
<p><strong>Background:</strong> I have a function that calls a pandas dataframe called <code>df</code>. I do various manipulation and clean-up on the <code>df</code> before it becomes <code>exceptions_report</code> (still a pandas dataframe).</p> <p><strong>Issue:</strong> In my code, I am trying to drop rows that don't meet 2x criteria. My whole program seems to throw back the following <code>IndexingError</code>-</p> <pre><code>&lt;ipython-input-725-33f542debed3&gt;:7: FutureWarning: The default value of regex will change from True to False in a future version. df.columns = df.columns.str.replace(r'columns.', '') &lt;ipython-input-726-412358be9bd2&gt;:51: UserWarning: Boolean Series key will be reindexed to match DataFrame index. df = df[~mask2].drop(columns=&quot;value&quot;) --------------------------------------------------------------------------- IndexingError Traceback (most recent call last) &lt;ipython-input-727-b420b41509b7&gt; in &lt;module&gt; 36 print(&quot;-----------------------------\n&quot;,&quot;EXCEPTION REPORT:&quot;, excep_row_count, &quot;rows&quot;, &quot;\n-----------------------------&quot;) 37 ---&gt; 38 xlsx_writer() &lt;ipython-input-727-b420b41509b7&gt; in xlsx_writer() 1 # Function that writes Exceptions Report and API Response as a consolidated .xlsx file. 2 def xlsx_writer(): ----&gt; 3 df_raw, exceptions_df = ownership_qc() 4 5 # Creating and defining filename for exceptions report &lt;ipython-input-726-412358be9bd2&gt; in ownership_qc() 49 # Remove lines that match all conditions 50 mask2 = (~exceptions_df[&quot;value&quot;].isna() &amp; (exceptions_df[&quot;Entity ID %&quot;] == exceptions_df[&quot;value&quot;]) &amp; (exceptions_df[&quot;Account # %&quot;] == exceptions_df[&quot;value&quot;])) ---&gt; 51 df = df[~mask2].drop(columns=&quot;value&quot;) 52 53 return df_raw, exceptions_df ~\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key) 3013 # Do we have a (boolean) 1d indexer? 3014 if com.is_bool_indexer(key): -&gt; 3015 return self._getitem_bool_array(key) 3016 3017 # We are left with two options: a single key, and a collection of keys, ~\Anaconda3\lib\site-packages\pandas\core\frame.py in _getitem_bool_array(self, key) 3066 # check_bool_indexer will throw exception if Series key cannot 3067 # be reindexed to match DataFrame rows -&gt; 3068 key = check_bool_indexer(self.index, key) 3069 indexer = key.nonzero()[0] 3070 return self._take_with_is_copy(indexer, axis=0) ~\Anaconda3\lib\site-packages\pandas\core\indexing.py in check_bool_indexer(index, key) 2267 mask = isna(result._values) 2268 if mask.any(): -&gt; 2269 raise IndexingError( 2270 &quot;Unalignable boolean Series provided as &quot; 2271 &quot;indexer (index of the boolean Series and of &quot; IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match). </code></pre> <p>As you can see, the code which is being referenced for this error was written to only drop rows from <code>exceptions_df</code> <strong>which do meet 2x criteria</strong>-</p> <ol> <li>Ownership Audit Note ⊃ (contains) &quot;Reviewed&quot;</li> <li>Ownership Audit Note contains a xx.xx% value that is == <code>Entity ID %</code> and <code>Account # %</code> columns.</li> </ol> <p><strong>Function with the bad code:</strong> The following function contains the code that is throwing back the <code>IndexingError</code>. This objective of this function is to perform manipulation of <code>df</code> (which then becomes <code>exceptions_df</code>) before returning it, ready for writing to an .xlsx file in another function.</p> <pre><code># Function to compute ownership exceptions def ownership_qc(): # Calling function that returns dataframe df = unpack_response() # Making a copy of df (normalized API response) to be written by def_xlsx_writer() function to same .xslsx as exceptions_df df_raw = df.copy() # Set Holding Account Number column values as dashes, if empty. Note: required to ensure Ownership Calculations work correctly. df.loc[df[&quot;Holding Account Number&quot;].isnull(),'Holding Account Number'] = &quot;-&quot; # Setting % Ownership column as a percentage. df[&quot;% Ownership&quot;] = 100 * df[&quot;% Ownership&quot;].round(2) # Setting QC Column values, ready for output calculations df['Entity ID %'] = '0.00' df['Account # %'] = '0.00' # Changing float64 columns to strings, for referencing purposes df['Ownership Audit Note'] = df['Ownership Audit Note'].astype(str) # Ownership Calculations df['Entity ID %'] = df.groupby('Entity ID')['% Ownership'].transform(sum).round(2) df['Account # %'] = df.groupby('Holding Account Number')['% Ownership'].transform(sum).round(2) # Dropping obsolete columns exceptions_df = df.drop(['Model Type', 'Valuation (USD)', 'Top Level Legal Entity', 'Financial Service', 'Account Close Date'], axis=1) # Dropping any 'Direct Owned' rows exceptions_df = exceptions_df[(~(exceptions_df['Holding Account'].str.contains('Directly Owned')))] # Scenario 1 - If 'Ownership Audit Note' contains &quot;Reviewed&quot; and 'Ownership Audit Note' contains a percentage value (xx.xx%) which is also == 'Entity ID %' and 'Account # %' then drop row. # Remove lines that match all conditions mask1 = exceptions_df[&quot;Ownership Audit Note&quot;].str.lower().str.contains(&quot;Reviewed&quot;) exceptions_df[&quot;value&quot;] = exceptions_df.loc[mask1, &quot;Ownership Audit Note&quot;].str.extract(pat=r&quot;\[\D*(\d+\.?\d*)%\]&quot;) exceptions_df[&quot;value&quot;] = exceptions_df[&quot;value&quot;].astype(&quot;float&quot;) # Remove lines that match all conditions mask2 = (~exceptions_df[&quot;value&quot;].isna() &amp; (exceptions_df[&quot;Entity ID %&quot;] == exceptions_df[&quot;value&quot;]) &amp; (exceptions_df[&quot;Account # %&quot;] == exceptions_df[&quot;value&quot;])) # THE BELOW CODE SEGMENT IS THROWING BACK THE IndexingError exception. df = df[~mask2].drop(columns=&quot;value&quot;) return df_raw, exceptions_df </code></pre> <p><strong>Things to note:</strong> I have tried and been able to run the problem piece of code with a much smaller <code>df</code>, so I know something else in this function is causing the issue.</p> <p>Does anyone have any suggestions or hints as to where I have gone wrong?</p>
3
2,555
Providing access to EFS from ECS task
<p>I am struggling to get an ECS task to be able to see an EFS volume. The terraform config is:</p> <p><strong>EFS DEFINITION</strong></p> <pre><code>resource &quot;aws_efs_file_system&quot; &quot;persistent&quot; { encrypted = true } resource &quot;aws_efs_access_point&quot; &quot;access&quot; { file_system_id = aws_efs_file_system.persistent.id } resource &quot;aws_efs_mount_target&quot; &quot;mount&quot; { for_each = {for net in aws_subnet.private : net.id =&gt; {id = net.id}} file_system_id = aws_efs_file_system.persistent.id subnet_id = each.value.id security_groups = [aws_security_group.efs.id] } </code></pre> <hr /> <p><strong>TASK DEFINITION</strong></p> <pre><code>resource &quot;aws_ecs_task_definition&quot; &quot;app&quot; { family = &quot;backend-app-task&quot; execution_role_arn = aws_iam_role.ecs_task_execution_role.arn task_role_arn = aws_iam_role.ecs_task_role.arn network_mode = &quot;awsvpc&quot; requires_compatibilities = [&quot;FARGATE&quot;] cpu = var.fargate_cpu memory = var.fargate_memory container_definitions = data.template_file.backendapp.rendered volume { name = &quot;persistent&quot; efs_volume_configuration { file_system_id = aws_efs_file_system.persistent.id root_directory = &quot;/opt/data&quot; transit_encryption = &quot;ENABLED&quot; transit_encryption_port = 2999 authorization_config { access_point_id = aws_efs_access_point.access.id iam = &quot;ENABLED&quot; } } } } </code></pre> <hr /> <p><strong>SECURITY GROUP</strong></p> <pre><code>resource &quot;aws_security_group&quot; &quot;efs&quot; { name = &quot;efs-security-group&quot; vpc_id = aws_vpc.main.id ingress { protocol = &quot;tcp&quot; from_port = 2999 to_port = 2999 security_groups = [aws_security_group.ecs_tasks.id] cidr_blocks = [for net in aws_subnet.private : net.cidr_block] } } </code></pre> <hr /> <p><strong>TASK ROLE</strong></p> <pre><code>resource &quot;aws_iam_role&quot; &quot;ecs_task_role&quot; { name = &quot;ecsTaskRole&quot; assume_role_policy = data.aws_iam_policy_document.ecs_task_execution_role_base.json managed_policy_arns = [&quot;arn:aws:iam::aws:policy/AmazonElasticFileSystemFullAccess&quot;,&quot;arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy&quot;, aws_iam_policy.ecs_exec_policy.arn] } </code></pre> <p>As I understand the AWS docs, the IAM role should have access, and the security group should be passing traffic, but the error suggests that the task cannot resolve the EFS instance.</p> <p>The error message is:</p> <pre><code>ResourceInitializationError: failed to invoke EFS utils commands to set up EFS volumes: stderr: Failed to resolve &quot;fs-0000000000000.efs.eu-west-2.amazonaws.com&quot; - check that your file system ID is correct. </code></pre> <p>I've manually confirmed in the console that the EFS id is correct, so I can only conclude that it cannot resolve due to a network/permissions issue.</p> <p>-- EDIT -- <strong>ECS SERVICE DEFINITION</strong></p> <pre><code>resource &quot;aws_ecs_service&quot; &quot;main&quot; { name = &quot;backendservice&quot; cluster = aws_ecs_cluster.main.id task_definition = aws_ecs_task_definition.app.arn desired_count = var.app_count launch_type = &quot;FARGATE&quot; enable_execute_command = true network_configuration { security_groups = [aws_security_group.ecs_tasks.id] subnets = aws_subnet.private.*.id assign_public_ip = true } load_balancer { target_group_arn = aws_alb_target_group.app.id container_name = &quot;server&quot; container_port = var.app_port } depends_on = [aws_alb_listener.backend] } </code></pre> <p><strong>ECS TASK SECURITY GROUP</strong></p> <pre><code>resource &quot;aws_security_group&quot; &quot;ecs_tasks&quot; { name = &quot;backend-ecs-tasks-security-group&quot; description = &quot;allow inbound access from the ALB only&quot; vpc_id = aws_vpc.main.id ingress { protocol = &quot;tcp&quot; from_port = var.app_port to_port = var.app_port security_groups = [aws_security_group.lb.id] } egress { protocol = &quot;-1&quot; from_port = 0 to_port = 0 cidr_blocks = [&quot;0.0.0.0/0&quot;] } } </code></pre> <p><strong>VPC DEFINITION (minus internet gateway)</strong></p> <pre><code>data &quot;aws_availability_zones&quot; &quot;available&quot; { } resource &quot;aws_vpc&quot; &quot;main&quot; { cidr_block = &quot;172.17.0.0/16&quot; } # Create var.az_count private subnets, each in a different AZ resource &quot;aws_subnet&quot; &quot;private&quot; { count = var.az_count cidr_block = cidrsubnet(aws_vpc.main.cidr_block, 8, count.index) availability_zone = data.aws_availability_zones.available.names[count.index] vpc_id = aws_vpc.main.id } resource &quot;aws_subnet&quot; &quot;public&quot; { count = var.az_count cidr_block = cidrsubnet(aws_vpc.main.cidr_block, 8, var.az_count + count.index) availability_zone = data.aws_availability_zones.available.names[count.index] vpc_id = aws_vpc.main.id map_public_ip_on_launch = true } </code></pre> <hr /> <h2>EDIT</h2> <p>It turned out the mountPoints block was missing from the container template. I have now added it, but the outcome is the same.</p>
3
2,518
error when trying to click on element that was hidden and then made visible again
<p>When I click a button I am using axios to send some data to my node.js backend and when the button is clicked I hide it and show a spinner. If something goes wrong, I hide the spinner and show the buttons again. That works fine. But if I click on the button after it is visible again I get an error that says :</p> <blockquote> <p>Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null at renderLoader (26786sdg72635287hd) at HTMLAnchorElement.document.querySelector.addEventListener.e</p> </blockquote> <p>HTML: </p> <pre><code>&lt;div class="spinner"&gt;&lt;/div&gt; </code></pre> <p>JAVASCRIPT</p> <pre><code> const renderLoader = parent =&gt; { const loader = ` &lt;div class="loader"&gt; &lt;svg&gt; &lt;use href="/images/icons.svg#icon-cw"&gt;&lt;/use&gt; &lt;/svg&gt; &lt;/div&gt; `; parent.insertAdjacentHTML('afterbegin', loader); }; const clearLoader = () =&gt; { const loader = document.querySelector('.spinner'); if (loader) { loader.parentElement.removeChild(loader); } }; document.querySelector('.approve').addEventListener('click', e =&gt; { e.preventDefault(); const csrf = document.querySelector('[name=_csrf]').value; const productId = document.querySelector('[name=productId]').value; document.querySelector('.approve').style.visibility = 'hidden'; document.querySelector('.reject').style.visibility = 'hidden'; renderLoader(document.querySelector('.spinner')); axios.post('/account/approve/' + productId, { status: 'approved' }, { headers: { 'csrf-token': csrf } }) .then(response =&gt; { const approveBox = document.querySelector('.dashboard-list-box'); const successMessage = document.querySelector('.success'); approveBox.classList.add('fade-out'); successMessage.classList.add('notification'); successMessage.innerHTML = response.data.message; clearLoader(); }) .catch(err =&gt; { clearLoader(); document.querySelector('.approve').style.visibility = 'visible'; document.querySelector('.reject').style.visibility = 'visible'; }); }); </code></pre>
3
1,169
My GitHub Action's GitHub API calls start failing after a period of time
<p>Yesterday I successfully ran this GitHub action several times, but now it is failing with an HTTP Not Found error. If I make the same REST call to the URL in Postman <a href="https://api.github.com/repos/RobotOpsPlayground/scottTest5/issues/4" rel="nofollow noreferrer">https://api.github.com/repos/RobotOpsPlayground/scottTest5/issues/4</a> I get back the expected JSON results. I do not understand what has changed, does anyone have an idea?</p> <p>So far, I have recreated and am using a new GitHub personal token, which has the same permissions as the one that was working. I have copied the code into a new repo and encountered the same problem.</p> <p>This is the output from the action's execution:</p> <pre class="lang-none prettyprint-override"><code>Run ./.github/actions/route_issue/ with: myToken: *** myOwner: RobotOpsPlayground myRepo: RobotOpsPlayground/scottTest5 myKnownLabels: repo-request, team-request, member-request, triage myDefaultLabel: triage myIssueNumber: 0 issueNumber 4 owner RobotOpsPlayground repo RobotOpsPlayground/scottTest5 token *** getting /repos/RobotOpsPlayground/scottTest5/issues/4 details from github &quot;GET /repos/RobotOpsPlayground/scottTest5/issues/4 sync function called for /repos/:repo/issues/:issueNumber failing due to HttpError: Not Found -- Not Found Error: Not Found </code></pre> <p>And here is the action.yaml</p> <pre class="lang-yaml prettyprint-override"><code>name: 'route_issue' description: 'pull some info from an issue' inputs: myToken: description: 'github token' required: true myOwner: description: 'github owner|organization' required: true default: 'RobotOpsPlayground' myRepo: description: 'github repo' required: true </code></pre> <p>And a part of the action's index.js</p> <pre class="lang-js prettyprint-override"><code>async function run() { const myToken = core.getInput('myToken'); const myOwner = core.getInput('myOwner'); const myRepo = core.getInput('myRepo'); const myIssueNumber = github.context.issue.number; // get issue details by looking up its issue number console.log(`getting /repos/${myRepo}/issues/${myIssueNumber} details from github `); let req = { method: 'GET', url: '/repos/:repo/issues/:issueNumber', headers: { authorization: `token ${myToken}` }, repo: myRepo, issueNumber: myIssueNumber, log: &quot;debug&quot; }; const result = await request req console.log(&quot;past getting issue&quot;) issue = result['data']; console.log(`my issue ${issue}`) if (issue.state !== 'open') { console.log(&quot;issue was not open&quot;) } else { console.log(&quot;processing issue&quot;); } } </code></pre> <p>And the GitHub workflow</p> <pre class="lang-yaml prettyprint-override"><code>name: route_issue on: issues: types: [opened] jobs: route_issue: runs-on: self-hosted outputs: issueNumber: ${{ steps.route_issue.outputs.issueNumber }} requestType: ${{ steps.route_issue.outputs.requestType }} steps: - id: checkout uses: actions/checkout@v2 - id: route_issue uses: ./.github/actions/route_issue/ with: myToken: ${{ secrets.GH_TOKEN3 }} myOwner: ${{ github.repository_owner }} myRepo: ${{ github.repository }} </code></pre>
3
1,216
Getting error message when run react-native application on Xcode 10.0
<p>I am new for IOS application development I am trying to run react native application on MAC (Virtual box) but stuck after launch screen.</p> <p>Getting error at this line of code. <a href="https://i.stack.imgur.com/Mm8TW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Mm8TW.jpg" alt="enter image description here"></a></p> <p>showing below message on report navigator.</p> <p>2018-09-26 05:03:23.637243+0530 Leaderboard[56620:700325] - [I-ACS036002] Analytics screen reporting is enabled. Call +[FIRAnalytics setScreenName:setScreenClass:] to set the screen name or override the default screen class name. To disable screen reporting, set the flag FirebaseScreenReportingEnabled to NO (boolean) in the Info.plist 2018-09-26 05:03:24.334073+0530 Leaderboard[56620:699937] +[CATransaction synchronize] called within transaction 2018-09-26 05:03:25.352 [info][tid:main][RCTCxxBridge.mm:216] Initializing (parent: , executor: (null)) 2018-09-26 05:03:25.385767+0530 Leaderboard[56620:699937] Initializing (parent: , executor: (null)) 2018-09-26 05:03:25.749 [info][tid:main][RCTRootView.m:293] Running application Leaderboard ({ initialProps = { }; rootTag = 1; }) 2018-09-26 05:03:25.831679+0530 Leaderboard[56620:699937] Running application Leaderboard ({ initialProps = { }; rootTag = 1; }) 2018-09-26 05:03:26.353502+0530 Leaderboard[56620:699937] <strong>* Terminating app due to uncaught exception 'com.firebase.core', reason: '<code>[FIRApp configure];</code> (<code>FirebaseApp.configure()</code> in Swift) could not find a valid GoogleService-Info.plist in your project. Please download one from <a href="https://console.firebase.google.com/" rel="nofollow noreferrer">https://console.firebase.google.com/</a>.' *</strong> First throw call stack: ( 0 CoreFoundation 0x00000001052a91e6 <strong>exceptionPreprocess + 294 1 libobjc.A.dylib 0x000000010371e031 objc_exception_throw + 48 2 CoreFoundation 0x000000010531e975 +[NSException raise:format:] + 197 3 Leaderboard 0x0000000101e80451 +[FIRApp configure] + 481 4 Leaderboard 0x0000000101e7fb07 -[AppDelegate application:didFinishLaunchingWithOptions:] + 871 5 UIKit 0x0000000107ee96fb -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 278 6 UIKit 0x0000000107eeb172 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 4123 7 UIKit 0x0000000107ef05cb -[UIApplication _runWithMainScene:transitionContext:completion:] + 1677 8 UIKit 0x00000001082b2f7e __111-[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:]_block_invoke + 866 9 UIKit 0x0000000108685a39 +[_UICanvas _enqueuePostSettingUpdateTransactionBlock:] + 153 10 UIKit 0x00000001082b2bba -[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:] + 236 11 UIKit 0x00000001082b33db -[__UICanvasLifecycleMonitor_Compatability activateEventsOnly:withContext:completion:] + 675 12 UIKit 0x0000000108c24614 __82-[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:]_block_invoke + 299 13 UIKit 0x0000000108c244ae -[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:] + 433 14 UIKit 0x000000010890875d __125-[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:]_block_invoke + 221 15 UIKit 0x0000000108b034b7 _performActionsWithDelayForTransitionContext + 100 16 UIKit 0x0000000108908627 -[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:] + 223 17 UIKit 0x00000001086850e0 -[_UICanvas scene:didUpdateWithDiff:transitionContext:completion:] + 392 18 UIKit 0x0000000107eeeeac -[UIApplication workspace:didCreateScene:withTransitionContext:completion:] + 515 19 UIKit 0x00000001084c1bcb -[UIApplicationSceneClientAgent scene:didInitializeWithEvent:completion:] + 361 20 FrontBoardServices 0x000000010e05a2f3 -[FBSSceneImpl _didCreateWithTransitionContext:completion:] + 331 21 FrontBoardServices 0x000000010e062cfa __56-[FBSWorkspace client:handleCreateScene:withCompletion:]_block_invoke_2 + 225 22 libdispatch.dylib 0x000000010695a7ec _dispatch_client_callout + 8 23 libdispatch.dylib 0x000000010695fdb8 _dispatch_block_invoke_direct + 592 24 FrontBoardServices 0x000000010e08e470 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK</strong> + 24 25 FrontBoardServices 0x000000010e08e12e -[FBSSerialQueue _performNext] + 439 26 FrontBoardServices 0x000000010e08e68e -[FBSSerialQueue _performNextFromRunLoopSource] + 45 27 CoreFoundation 0x000000010524bbb1 <strong>CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION</strong> + 17 28 CoreFoundation 0x00000001052304af __CFRunLoopDoSources0 + 271 29 CoreFoundation 0x000000010522fa6f __CFRunLoopRun + 1263 30 CoreFoundation 0x000000010522f30b CFRunLoopRunSpecific + 635 31 GraphicsServices 0x000000010d42ea73 GSEventRunModal + 62 32 UIKit 0x0000000107ef2057 UIApplicationMain + 159 33 Leaderboard 0x0000000101e7fc90 main + 112 34 libdyld.dylib 0x000000010a98c955 start + 1 35 ??? 0x0000000000000001 0x0 + 1 ) libc++abi.dylib: terminating with uncaught exception of type NSException (lldb) </p>
3
2,865
Can't get property from object when redirecting with "Header" function
<p>I'm trying to display a inserted product after it is inserted. It looks like the object is empty.</p> <p>This is what I use to redirect ('Inventario' controller)</p> <pre><code>public function insertarAction(){ // insertarProducto returns true or false if($this-&gt;producto-&gt;insertarProducto()) { Flash::addMessage('Prenda ingresada correctamente'); $this-&gt;redirect('/inventario/ingreso-correcto'); } else { Flash::addMessage('Error al ingresar prenda', FLASH::WARNING); View::renderTemplate('Inventario/nuevo.html',[ 'user' =&gt; Auth::getUser(), 'producto' =&gt; $this-&gt;producto, 'controller' =&gt; 'inventario' ]); } } </code></pre> <p>This redirects me to the html I need but without the 'producto' object.</p> <p>I created the product object in a <code>before</code> method that runs before the other methods are called. </p> <p>This is what 'redirect' function does (it is on my core/controller class):</p> <pre><code>public function redirect($url){ header('Location: http://' . $_SERVER['HTTP_HOST'] . $url, true, 303); exit; } </code></pre> <p>This is the ingreso-correcto HTML:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;th&gt;Codigo&lt;/th&gt; &lt;td&gt;{{ producto.codigo }}&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;Color&lt;/th&gt; &lt;td&gt;{{ producto.color }}&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;Cantidad en stock&lt;/th&gt; &lt;td&gt;{{ producto.cantidad }}&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;Descripcion de producto&lt;/th&gt; &lt;td&gt;{{ producto.descripcion }}&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;Precio&lt;/th&gt; &lt;td&gt;{{ producto.precio }}&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;Costo&lt;/th&gt; &lt;td&gt;{{ producto.costo }}&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;Descuento&lt;/th&gt; &lt;td&gt;{{ producto.descuento }}&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;Coleccion&lt;/th&gt; &lt;td&gt;{{ producto.coleccion }}&lt;/td&gt; &lt;/tr&gt; &lt;th&gt;Ganancia&lt;/th&gt; &lt;td&gt;{{ producto.ganancia }}&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>How can I get the <code>producto</code> object after i've used the <code>redirect</code> method?</p>
3
1,281
Jquery menu active select to Vue JS
<p>i want to stop using jquery and rely on Vue for front end for a menu where i need to add active class and menu-open to the right nested list items as you can see in the jQuery, which i have no idea how to achieve.</p> <pre><code>$(document).ready(function () { var url = window.location; // Adds active on inner anchor and treeview anchor and treeview menu-open state to li $('ul.nav a').filter(function () { return this.href == url; }).addClass('active').parent().parent().siblings().addClass('active').addClass('text-dark').parent().addClass('menu-open'); }); </code></pre> <p>here is the menu already with app id</p> <pre><code>&lt;ul id="app" class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false"&gt; &lt;!-- Add icons to the links using the .nav-icon class with font-awesome or any other icon font library --&gt; &lt;li class="nav-header text-center pb-1 text-white "&gt;&lt;strong&gt;Menu de Navegação&lt;/strong&gt;&lt;/li&gt; &lt;li class="nav-item has-treeview"&gt; &lt;a href="#" class="nav-link custom-sidebar-link"&gt; &lt;i class="nav-icon fas fas fa-users text-white"&gt;&lt;/i&gt; &lt;p class="text-white"&gt; Utilizadores &lt;i class="right fa fa-angle-left text-white"&gt;&lt;/i&gt; &lt;/p&gt; &lt;/a&gt; &lt;ul class="nav nav-treeview"&gt; &lt;li class="nav-item custom-sidebar-link"&gt; &lt;a asp-page="/Account/Manage/Users/Create" class="nav-link custom-nav-inner-link"&gt; &lt;i class="nav-icon fas fa-caret-right"&gt;&lt;/i&gt; &lt;p&gt;Criar&lt;/p&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="nav-item custom-sidebar-link"&gt; &lt;a asp-page="/Account/Manage/Users/Index" class="nav-link custom-nav-inner-link"&gt; &lt;i class="nav-icon fas fa-caret-right"&gt;&lt;/i&gt; &lt;p&gt;Consultar&lt;/p&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="nav-item has-treeview"&gt; &lt;a href="#" class="nav-link custom-sidebar-link"&gt; &lt;i class="nav-icon fas fa-layer-group text-white"&gt;&lt;/i&gt; &lt;p class="text-white"&gt; Departamentos &lt;i class="right fa fa-angle-left text-white"&gt;&lt;/i&gt; &lt;/p&gt; &lt;/a&gt; &lt;ul class="nav nav-treeview"&gt; &lt;li class="nav-item custom-sidebar-link"&gt; &lt;a asp-page="/Account/Manage/Departamentos/Create" class="nav-link custom-nav-inner-link"&gt; &lt;i class="nav-icon fas fa-caret-right"&gt;&lt;/i&gt; &lt;p&gt;Criar&lt;/p&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="nav-item custom-sidebar-link"&gt; &lt;a asp-page="/Account/Manage/Departamentos/Index" class="nav-link custom-nav-inner-link"&gt; &lt;i class="nav-icon fas fa-caret-right"&gt;&lt;/i&gt; &lt;p&gt;Consultar&lt;/p&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="nav-item has-treeview"&gt; &lt;a href="#" class="nav-link custom-sidebar-link"&gt; &lt;i class="nav-icon fas fa-shield-alt text-white"&gt;&lt;/i&gt; &lt;p class="text-white"&gt; Acessos &lt;i class="right fa fa-angle-left text-white"&gt;&lt;/i&gt; &lt;/p&gt; &lt;/a&gt; &lt;ul class="nav nav-treeview"&gt; &lt;li class="nav-item"&gt; &lt;a asp-page="/Account/Manage/Roles/Create" class="nav-link custom-nav-inner-link"&gt; &lt;i class="nav-icon fas fa-caret-right"&gt;&lt;/i&gt; &lt;p&gt;Criar&lt;/p&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="nav-item custom-sidebar-link"&gt; &lt;a asp-page="/Account/Manage/Roles/Index" class="nav-link custom-nav-inner-link"&gt; &lt;i class="nav-icon fas fa-caret-right"&gt;&lt;/i&gt; &lt;p&gt;Consultar&lt;/p&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="nav-item has-treeview"&gt; &lt;a href="#" class="nav-link custom-sidebar-link"&gt; &lt;i class="nav-icon fab fa-app-store-ios text-white"&gt;&lt;/i&gt; &lt;p class="text-white"&gt; Aplicações &lt;i class="right fa fa-angle-left text-white"&gt;&lt;/i&gt; &lt;/p&gt; &lt;/a&gt; &lt;ul class="nav nav-treeview"&gt; &lt;li class="nav-item"&gt; &lt;a asp-page="/Account/Manage/Apps/Create" class="nav-link custom-nav-inner-link"&gt; &lt;i class="nav-icon fas fa-caret-right"&gt;&lt;/i&gt; &lt;p&gt;Criar&lt;/p&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="nav-item custom-sidebar-link"&gt; &lt;a asp-page="/Account/Manage/Apps/Index" class="nav-link custom-nav-inner-link"&gt; &lt;i class="nav-icon fas fa-caret-right"&gt;&lt;/i&gt; &lt;p&gt;Consultar&lt;/p&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; </code></pre> <p></p> <p>however i wanted to use v-for so i don't have to bind click on every list item except i never used it before.</p> <p>If any vue expert knows a better way to do this with least code please advise me</p>
3
2,860
How to process a recursive GADT with kind :: '[SomeDataKind]
<p>I think this is the furthest into the Haskell type system extensions that I've even been and I've run into an error that I haven't been able to figure out. Apologies in advance for the length, it's the shortest example I could create that still illustrates the issue I'm having. I have a recursive GADT whose kind is a promoted list, something like the following:</p> <p><strong>GADT Definition</strong></p> <pre><code>{-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE TypeOperators #-} data DataKind = A | B | C -- 'parts' should always contain at least 1 element which is enforced by the GADT. -- Lets call the first piece of data 'val' and the second 'subdata'. -- All data constructors have these 2 fields, although some may have -- additional fields which I've omitted for simplicity. data SomeData (parts :: [DataKind]) where MkA :: Maybe Char -&gt; Maybe (SomeData subparts) -&gt; SomeData ('A ': subparts) MkB :: Maybe Char -&gt; Maybe (SomeData subparts) -&gt; SomeData ('B ': subparts) MkC :: Maybe Char -&gt; Maybe (SomeData subparts) -&gt; SomeData ('C ': subparts) deriving instance Show (SomeData parts) </code></pre> <p><strong>Problem</strong></p> <p>What I'm trying to do is traverse the data and perform some operations, for instance propagate the first <code>Just</code> <code>Char</code> found up to the top.</p> <p><strong>Annoying missing features - needed for the next section</strong></p> <p>Now, because there is apparently no record syntax support for GADTs (<a href="https://ghc.haskell.org/trac/ghc/ticket/2595" rel="nofollow noreferrer">https://ghc.haskell.org/trac/ghc/ticket/2595</a>) you need to write them manually, so here they are:</p> <pre><code>getVal :: SomeData parts -&gt; Maybe Char getVal (MkA val _) = val getVal (MkB val _) = val getVal (MkC val _) = val -- The lack of record syntax for GADTs is annoying. updateVal :: Maybe Char -&gt; SomeData parts -&gt; SomeData parts updateVal val (MkA _val sub) = MkA val sub updateVal val (MkB _val sub) = MkB val sub updateVal val (MkC _val sub) = MkC val sub -- really annoying... getSubData :: SomeData (p ': rest) -&gt; Maybe (SomeData rest) getSubData (MkA _ sub) = sub getSubData (MkB _ sub) = sub getSubData (MkC _ sub) = sub </code></pre> <p><strong>Test Data</strong></p> <p>So, the thing I want to do. Walk down the structure from the top until I find a value that is <code>Just</code>. So given the following initial values:</p> <pre><code>a :: SomeData '[ 'A ] a = MkA (Just 'A') Nothing b :: SomeData '[ 'B ] b = MkB (Just 'B') Nothing c :: SomeData '[ 'C ] c = MkC (Just 'C') Nothing bc :: SomeData '[ 'B, 'C ] bc = MkB Nothing (Just c) abc :: SomeData '[ 'A, 'B, 'C ] abc = MkA Nothing (Just bc) </code></pre> <p><strong>Expected Result</strong></p> <p>I would like have something like this:</p> <pre><code>&gt; abc MkA Nothing (Just (MkB Nothing (Just (MkC (Just 'C') Nothing)))) &gt; propogate abc MkA (Just 'C') (Just (MkB (Just 'C') (Just (MkC (Just 'C') Nothing)))) </code></pre> <p><strong>Previous Attempts</strong></p> <p>I took a few stabs at it, first with a regular function:</p> <pre><code>propogate sd = case getVal sd of Just _val -&gt; sd Nothing -&gt; let newSubData = fmap propogate (getSubData sd) newVal = join . fmap getVal $ newSubData in updateVal newVal sd </code></pre> <p>This gives the error:</p> <pre><code>Broken.hs:(70,1)-(81,35): error: … • Occurs check: cannot construct the infinite type: rest ~ p : rest Expected type: SomeData rest -&gt; SomeData (p : rest) Actual type: SomeData (p : rest) -&gt; SomeData (p : rest) • Relevant bindings include propogate :: SomeData rest -&gt; SomeData (p : rest) (bound at Broken.hs:70:1) Compilation failed. </code></pre> <p>I also tried a typeclass and attempting to match on the structure:</p> <pre><code>class Propogate sd where propogateTypeClass :: sd -&gt; sd -- Base case: We only have 1 element in the promoted type list. instance Propogate (SomeData parts) where propogateTypeClass sd = sd -- Recursie case: More than 1 element in the promoted type list. instance Propogate (SomeData (p ': parts)) where propogateTypeClass sd = case getVal sd of Just _val -&gt; sd Nothing -&gt; let -- newSubData :: Maybe subparts -- Recurse on the subdata if it exists. newSubData = fmap propogateTypeClass (getSubData sd) newVal = join . fmap getVal $ newSubData in updateVal newVal sd </code></pre> <p>This results in the error:</p> <pre><code>Broken.hs:125:5-26: error: … • Overlapping instances for Propogate (SomeData '['A, 'B, 'C]) arising from a use of ‘propogateTypeClass’ Matching instances: instance Propogate (SomeData parts) -- Defined at Broken.hs:91:10 instance Propogate (SomeData (p : parts)) -- Defined at Broken.hs:95:10 • In the expression: propogateTypeClass abc In an equation for ‘x’: x = propogateTypeClass abc Compilation failed. </code></pre> <p>I've also tried combinations of matching on <code>SomeData '[]</code> and <code>SomeData '[p]</code> to no avail.</p> <p>I'm hoping I'm missing something simple but I haven't found documentation anywhere on how to process a structure like this and I'm at the limits of my understand if the Haskell type system, for now anyways :). Once again, sorry for the long post and any help would be greatly appreciated :)</p>
3
2,218
Closing server using select function
<p>So, I am new to socket programming in C and am using the <code>select</code> function to communicate with multiple clients on a server. The server essentially just echos a buffer back to a client based on a requirest. I have used <a href="http://beej.us/guide/bgnet/html/multi/index.html" rel="nofollow noreferrer">Beej's guide to network programming</a> as the model for my server. What is not clear to me is whether I am exiting the server properly when a command is sent to exit. The code for handling the <code>select</code> function looks like:</p> <pre><code>for (;;) { read_fds = master; // Copy the master fds to the basic read... // Check to see if any flags have been set for reading if (select(fdmax + 1, &amp;read_fds, NULL, NULL, NULL) == -1) { perror("select"); exit(4); } for (i = 0; i &lt;= fdmax; i++) { if (FD_ISSET(i, &amp;read_fds)) { if (i == listener) { // need to add new connnection here addrlen = sizeof remote_addr; newfd = accept(listener, (struct sockaddr *)&amp;remote_addr, &amp;addrlen); if (newfd == -1) { perror("accept"); } else { FD_SET(newfd, &amp;master); if (newfd &gt; fdmax) { fdmax = newfd; } } } // end add new listener else { /*if (i == 0) { printf("Input received from stdin\n"); continue; } */ // handle data from existing client if ((nbytes = recv(i, input_buffer, sizeof input_buffer, 0)) &lt;= 0) { // Remove connection if there is a hangup... if (nbytes == 0) { printf("selectserver: socket%d hung up\n", i); } else { perror("recv"); } close(i); FD_CLR(i, &amp;master); } // no bytes error or port closed - remove from fdset else { if (strchr(input_buffer,'\r') == NULL){ printf("we have a problem\n"); } if (strcmp(input_buffer, "exit")){ printf("Exit requested...\n"); close(listener); exit(0); } for (j = 0; j &lt;= fdmax; j++) { if (FD_ISSET(j, &amp;master)) { if (j != listener &amp;&amp; j != 0) { if (send(j, input_buffer, nbytes, 0) == -1) { error_msg = strerror(errno); printf("%s\n", error_msg); //perror("send"); } } } } } } } } } </code></pre> <p>and the code I am specifically concerned about is </p> <pre><code>if (strcmp(input_buffer, "exit")){ printf("Exit requested...\n"); close(listener); exit(0); } </code></pre> <p>where <code>listener</code> is the file descriptor for the listening socket. Is this the correct way of exiting this loop or is there a better way to handle this? </p>
3
2,206
Python tkinter passing input value within the same class
<p>Most of the code below is just so the problem is accurately replicated, the issue most likely is in the hand-off of <code>filename</code> from<code>askopenfilenameI()</code> to <code>printing(stringToPrint)</code>or the <code>if</code> statement at the end.</p> <h2>Goal</h2> <p>The goal of this program is to simply print the file path to the console when <code>Print File Path</code> button is clicked.</p> <h2>Current state</h2> <p>When the program is executed the window appears correctly and the it lets you select a file in the file system. Once the file is opened, the script seems to call <code>printing</code> method before it executes its own <code>print</code> statement. When I open another file it prints the only the print statement from <code>askopenfilename()</code> (which is correct).</p> <p>However, clicking the <code>Print File Path</code> Button does not seem to get work at any stage.</p> <p>An example output would be:</p> <p>Value on click: <code>no-file</code></p> <p>askopenfilename value: <code>C:/Temp/AFTER_FIRST_OPEN.txt</code></p> <p>askopenfilename value: <code>C:/Temp/AFTER_SECOND_OPEN.txt</code></p> <h2>Code</h2> <pre><code>import Tkinter, Tkconstants, tkFileDialog filename = 'no-file' class TkApp(Tkinter.Frame): def __init__(self, root): Tkinter.Frame.__init__(self, root) # options for buttons button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5} # define buttons Tkinter.Button(self, text='Open File', command=self.askopenfilename).pack(**button_opt) Tkinter.Button(self, text='Print File Path', command=self.printing(filename)).pack(**button_opt) Tkinter.Button(self, text='Quit', command=self.quit).pack(**button_opt) # define options for opening or saving a file self.file_opt = options = {} options['defaultextension'] = '.twb' options['filetypes'] = [('All', '*')] options['initialdir'] = 'C:\\' options['parent'] = root options['title'] = 'Select a File' def askopenfilename(self): &quot;&quot;&quot;Returns an opened file in read mode. This time the dialog just returns a filename and the file is opened by your own code. &quot;&quot;&quot; global filename # get filename filename = tkFileDialog.askopenfilename(**self.file_opt) # open file on your own if filename: print &quot;askopenfilename value: &quot; + filename return filename def printing(self, stringToPrint): print &quot;Value on click: &quot; + stringToPrint def quit(self): root.destroy() if __name__=='__main__': root = Tkinter.Tk() root.title(&quot;Path Printer&quot;) TkApp(root).pack() root.mainloop() </code></pre>
3
1,152
Displaying Div's based on URL using Javascript
<p>I’m new to Javascript and I’m having trouble displaying and hiding some divs based on url’s.</p> <p>I have 4 divs that need to be shown depending on the url. The 4 divs are:</p> <p><strong>Div 1</strong></p> <pre><code>&lt;body onload="callOnPageLoad1()”&gt; &lt;div id="homeName" style="display:block"&gt;&lt;h5&gt;HOME&lt;/h5&gt;&lt;/div&gt; </code></pre> <p>and needs to be displayed only when at:</p> <pre><code>http://www.fitzofdesign.com/ </code></pre> <p><strong>Div 2</strong></p> <pre><code>&lt;body onload="callOnPageLoad2()”&gt; &lt;div id="profilesName" style="display:block"&gt;&lt;h5&gt;PROFILES&lt;/h5&gt;&lt;/div&gt; </code></pre> <p>and needs to be displayed only when at:</p> <pre><code>http://www.fitzofdesign.com/?category=Profiles </code></pre> <p><strong>Div 3</strong></p> <pre><code>&lt;body onload="callOnPageLoad3()”&gt; &lt;div id="retailName" style="display:block"&gt;&lt;h5&gt;RETAIL&lt;/h5&gt;&lt;/div&gt; </code></pre> <p>and needs to be displayed only when at:</p> <pre><code>http://www.fitzofdesign.com/?category=Retail </code></pre> <p><strong>Div 4</strong></p> <pre><code>&lt;body onload="callOnPageLoad4()”&gt; &lt;div id="blogName" style="display:block"&gt;&lt;h5&gt;BLOG&lt;/h5&gt;&lt;/div&gt; </code></pre> <p>and needs to be displayed only when at:</p> <pre><code>http://www.fitzofdesign.com/?category=Blog </code></pre> <p>The JS I’m using is:</p> <pre><code>&lt;script type="text/javascript"&gt; function callOnPageLoad1() { var url = window.location.href; if(url == "http://www.fitzofdesign.com/") { document.getElementById('homeName').style.display = 'block'; document.getElementById('profilesNamed').style.display = 'none'; document.getElementById('retailName').style.display = 'none'; document.getElementById('blogName').style.display = 'none'; } else { document.getElementById('homeName').style.display = 'none'; } } &lt;/script&gt; &lt;script type="text/javascript"&gt; function callOnPageLoad2() { var url = window.location.href; if(url == "http://www.fitzofdesign.com/?category=Profiles") { document.getElementById('homeName').style.display = 'none'; document.getElementById('profilesNamed').style.display = 'block'; document.getElementById('retailName').style.display = 'none'; document.getElementById('blogName').style.display = 'none'; } else { document.getElementById('profilesNamed').style.display = 'none'; } } &lt;/script&gt; &lt;script type="text/javascript"&gt; function callOnPageLoad3() { var url = window.location.href; if(url == "http://www.fitzofdesign.com/?category=Retail") { document.getElementById('homeName').style.display = 'none'; document.getElementById('profilesNamed').style.display = 'none'; document.getElementById('retailName').style.display = 'block'; document.getElementById('blogName').style.display = 'none'; } else { document.getElementById('retailName').style.display = 'none'; } } &lt;/script&gt; &lt;script type="text/javascript"&gt; function callOnPageLoad4() { var url = window.location.href; if(url == "http://www.fitzofdesign.com/?category=Blog") { document.getElementById('homeName').style.display = 'none'; document.getElementById('profilesNamed').style.display = 'none'; document.getElementById('retailName').style.display = 'none'; document.getElementById('blogName').style.display = 'block'; } else { document.getElementById('blogName').style.display = 'none'; } } &lt;/script&gt; </code></pre> <p>At present the only time this is <strong>working</strong> correctly is when I’m at:</p> <pre><code>http://www.fitzofdesign.com/ </code></pre> <p>because Div 1 appears and the other 3 Divs are hidden.</p> <p>This is <strong>not working</strong> when I’m at: </p> <pre><code>http://www.fitzofdesign.com/?category=Profiles http://www.fitzofdesign.com/?category=Retail http://www.fitzofdesign.com/?category=Blog </code></pre> <p>because Div 2, 3 &amp; 4 are all incorrectly displaying for each URL.</p> <p>I hope this makes sense.</p> <p>Can anyone help please?</p> <p>Thanks Rowan</p>
3
1,520
WordPress custom post type link are changed but returns 404
<p>WordPress custom post type link are changed but returns 404.</p> <p>I have created a custom post type like this,</p> <pre><code>function create_notes_custom() { register_post_type( 'coaches_resources', array( 'labels' =&gt; array( 'name' =&gt; __( 'Coaches Resources' ), 'singular_name' =&gt; __( 'Coaches Resource' ), 'add_new' =&gt; __( 'Add New' ), 'add_new_item' =&gt; __( 'Add New Resource' ), 'edit' =&gt; __( 'Edit' ), 'edit_item' =&gt; __( 'Edit Resource' ), 'new_item' =&gt; __( 'New Resource' ), 'view' =&gt; __( 'View' ), 'view_item' =&gt; __( 'View Resource' ), 'search_items' =&gt; __( 'Search Resources' ), 'not_found' =&gt; __( 'No resources found' ), 'not_found_in_trash' =&gt; __( 'No resource found in Trash' ), 'parent' =&gt; __( 'Parent Resource' ) ), 'public' =&gt; true, 'menu_position' =&gt; 5, 'supports' =&gt; array( 'title' ), 'taxonomies' =&gt; array( 'resource_chapter' ), 'rewrite' =&gt; array( 'slug' =&gt; 'resource', 'with_front' =&gt; true ), 'has_archive' =&gt; false, 'hierarchical' =&gt; false ) ); } add_action('init', 'create_notes_custom'); </code></pre> <p>URL is changed by,</p> <pre><code>function change_link( $permalink, $post ) { if( $post-&gt;post_type == 'coaches_resources' ) { $resource_terms = get_the_terms( $post, 'resource_chapter' ); $term_slug = ''; if( ! empty( $resource_terms ) ) { foreach ( $resource_terms as $term ) { if (! empty($term-&gt;slug)) { // The featured resource will have another category which is the main one if( $term-&gt;slug == 'featured' ) { continue; } $term_slug = $term-&gt;slug; break; } } } $permalink = get_home_url() .&quot;/notebook/&quot; . $term_slug . '/' . $post-&gt;post_name; } return $permalink; } add_filter('post_type_link', &quot;change_link&quot;, 10, 2); </code></pre> <p>URL is changed from <a href="http://example.com/resource/my-first-note/" rel="nofollow noreferrer">http://example.com/resource/my-first-note/</a> to <a href="http://example.com/notebook/note-category/my-first-note" rel="nofollow noreferrer">http://example.com/notebook/note-category/my-first-note</a></p> <p>But it returns <code>404</code>.</p>
3
1,440
How to add multiple dropdown with checkboxes in HTML?
<p>My HTML code is:</p> <pre><code> &lt;div id=&quot;list1&quot; class=&quot;dropdown-check-list&quot; tabindex=&quot;100&quot;&gt; &lt;span class=&quot;anchor&quot;&gt;Select Months&lt;/span&gt; &lt;ul class=&quot;items&quot;&gt; &lt;li&gt;&lt;input type=&quot;checkbox&quot; /&gt;Apr &lt;/li&gt; &lt;li&gt;&lt;input type=&quot;checkbox&quot; /&gt;May&lt;/li&gt; &lt;li&gt;&lt;input type=&quot;checkbox&quot; /&gt;June &lt;/li&gt; &lt;li&gt;&lt;input type=&quot;checkbox&quot; /&gt;July &lt;/li&gt; &lt;li&gt;&lt;input type=&quot;checkbox&quot; /&gt;Aug &lt;/li&gt; &lt;li&gt;&lt;input type=&quot;checkbox&quot; /&gt;Sep &lt;/li&gt; &lt;li&gt;&lt;input type=&quot;checkbox&quot; /&gt;Oct&lt;/li&gt; &lt;li&gt;&lt;input type=&quot;checkbox&quot; /&gt;Nov&lt;/li&gt; &lt;li&gt;&lt;input type=&quot;checkbox&quot; /&gt;Dec&lt;/li&gt; &lt;li&gt;&lt;input type=&quot;checkbox&quot; /&gt;Jan&lt;/li&gt; &lt;li&gt;&lt;input type=&quot;checkbox&quot; /&gt;Feb&lt;/li&gt; &lt;li&gt;&lt;input type=&quot;checkbox&quot; /&gt;Mar&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div id=&quot;list2&quot; class=&quot;dropdown-check-list&quot; tabindex=&quot;100&quot;&gt; &lt;span class=&quot;anchor&quot;&gt;Select Quarter&lt;/span&gt; &lt;ul class=&quot;items&quot;&gt; &lt;li&gt;&lt;input type=&quot;checkbox&quot; /&gt;Quarter 1&lt;/li&gt; &lt;li&gt;&lt;input type=&quot;checkbox&quot; /&gt;Quarter 2&lt;/li&gt; &lt;li&gt;&lt;input type=&quot;checkbox&quot; /&gt;Quarter 3&lt;/li&gt; &lt;li&gt;&lt;input type=&quot;checkbox&quot; /&gt;Quarter 4 &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div id=&quot;list3&quot; class=&quot;dropdown-check-list&quot; tabindex=&quot;100&quot;&gt; &lt;span class=&quot;anchor&quot;&gt;Select Monthly/Yearly&lt;/span&gt; &lt;ul class=&quot;items&quot;&gt; &lt;li&gt;&lt;input type=&quot;checkbox&quot; /&gt;6 Months &lt;/li&gt; &lt;li&gt;&lt;input type=&quot;checkbox&quot; /&gt;Year&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>My CSS code is:</p> <pre><code>.dropdown-check-list { display: inline-block; } .dropdown-check-list .anchor { position: relative; cursor: pointer; display: inline-block; padding: 5px 50px 5px 10px; border: 1px solid #ccc; } .dropdown-check-list .anchor:after { position: absolute; content: &quot;&quot;; border-left: 2px solid black; border-top: 2px solid black; padding: 5px; right: 10px; top: 20%; -moz-transform: rotate(-135deg); -ms-transform: rotate(-135deg); -o-transform: rotate(-135deg); -webkit-transform: rotate(-135deg); transform: rotate(-135deg); } .dropdown-check-list .anchor:active:after { right: 8px; top: 21%; } .dropdown-check-list ul.items { padding: 2px; display: none; margin: 0; border: 1px solid #ccc; border-top: none; } .dropdown-check-list ul.items li { list-style: none; } .dropdown-check-list.visible .anchor { color: #0094ff; } .dropdown-check-list.visible .items { display: block; } </code></pre> <p>My Javascript code is:</p> <pre><code>var checkList = document.getElementById('list1'); checkList.getElementsByClassName('anchor')[0].onclick = function(evt) { if (checkList.classList.contains('visible')) checkList.classList.remove('visible'); else checkList.classList.add('visible'); } &lt;/script&gt; &lt;script&gt; var checkList = document.getElementById('list2'); checkList.getElementsByClassName('anchor')[0].onclick = function(evt) { if (checkList.classList.contains('visible')) checkList.classList.remove('visible'); else checkList.classList.add('visible'); } &lt;/script&gt; &lt;script&gt; var checkList = document.getElementById('list3'); checkList.getElementsByClassName('anchor')[0].onclick = function(evt) { if (checkList.classList.contains('visible')) checkList.classList.remove('visible'); else checkList.classList.add('visible'); } &lt;/script&gt; </code></pre> <p>I tried running this code, but by clicking the first and second dropdown only the 3rd dropdown works, the first and second dropdown are not working, so which means that by clicking the first dropdown the 3 dropdown expands and same happens with second. If someone could please help me out, Thank you.</p>
3
2,123
Adding 'mousedown' event listener in a grid which will trigger all cells unless 'mouseup' event occurs
<p>I was still working on my Graph Visualizer project and I am unable to figure out how to add <code>mousedown</code> event listener to all the cells. I am trying to draw a wall-like structure. Let me explain when <code>mousedown</code> event occurs that cell will become a wall (I'll add some color) and unless the <code>mouseup</code> event occurs all the cells through where the cursor will pass will also become a wall. I am facing two issues here: I was able to add an event listener to each cell but I am unable to identify which cell was it. Also, I would like to know how to create continuous walls upon <code>mousedown</code>.</p> <p>Any suggestions or advice is highly appreciated.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var gridCols = 60; var gridRows = Math.floor(screen.height / 25) - 2; gridContainer.style.left = (screen.width-25*gridCols)/screen.width * 50+"%"; var matrix = []; var found = false; function sleep(ms) { return new Promise(resolve =&gt; setTimeout(resolve, ms)); } function getCell(row, col) { return document.querySelector(".row:nth-child("+(row+1)+") .gridsquare:nth-child("+(col+1)+")"); } for(var i=0; i&lt;20; i++) { matrix[i] = []; for(var j=0; j&lt;60; j++) matrix[i][j] = false; } function addWall() { console.log('called'); } function genDivs(rows, cols) { var e = document.getElementById("gridContainer"); for(var r = 0; r &lt; rows; r++) { var row = document.createElement("div"); row.className = "row"; for(var c = 0; c &lt; cols; c++) { var cell = document.createElement("div"); if(r == 10 &amp;&amp; c == 20) cell.className = "gridsquare begin"; else if(r == 10 &amp;&amp; c == 40) cell.className = "gridsquare end"; else cell.className = "gridsquare"; row.appendChild(cell); row.addEventListener("mousedown", addWall) } e.appendChild(row); } } async function dfs(i, j) { if(found || i &gt;= 20 || j &gt;= 60 || i &lt; 0 || j &lt; 0 || matrix[i][j]) return; if(i == 10 &amp;&amp; j == 40) { found = true; return; } matrix[i][j] = true; getCell(i, j).style.background = "magenta"; await sleep(5); await dfs(i+1, j); await dfs(i, j+1); await dfs(i-1, j); await dfs(i, j-1); } genDivs(20, gridCols); //dfs(10, 10);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;style&gt; #gridContainer { outline: 1px solid rgb(175, 216, 248); font-size: 0; position: absolute; } .row { } .gridsquare { width: 25px; height: 25px; box-shadow: 0 1px 0 rgb(175, 216, 248) inset, 1px 0px 0px rgb(175, 216, 248) inset; display: inline-block; } .begin { background-color: purple; } .end { background-color: magenta; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="gridContainer"&gt;&lt;/div&gt; &lt;script type="text/javascript" src="HomeScript.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
3
1,289
keep the new background color of current day in fullcalendar when click on next month or previous month
<p>I am working on a react project using npm fullcalendar. there is a requirement that I need to change the color of the current day. I managed to do that using the following : </p> <pre><code>$('.fc-today').attr('style','background-color:#40cc25'); </code></pre> <p>however, the problem is that when I click on next month or previous month it change the color to the original color of the library. how can I keep my new background color? here is my code :</p> <pre><code>var EventCalendar = React.createClass({ mixins: [History], getInitialState: function () { return { isModalOpen: false }; }, _onCalendarSelect: function (start, end, jsEvent, view) { if (!AuthStore.isAdministrator()) return; var event = { start: start, end: end }; this.setState({ event: event, isUpdate: false }); this.props.onNewEvent(event); }, _onEventSelect: function (event) { this.props.onEventSelect(event) }, _loadEvents: function(start, end, timezone, callback) { var events = EventStore.getInRange(start, end, this.props.environmentId); if (!EventStore.isLoaded(start.format("YYYY-MM"))) { EventActions.fetchData(start, end, this.props.environmentId) } else { callback(events); } }, _onEventStoreUpdate: function() { // This is fix for IE11 required by bug RTC #458121 var moment = this.$fullCalendarContainer.fullCalendar('getDate'); this.$fullCalendarContainer.fullCalendar('destroy'); this.$fullCalendarContainer.fullCalendar({ defaultView: 'month', defaultDate : moment, selectable: true, eventLimit: true, eventClick: this._onEventSelect, select: this._onCalendarSelect, events: this._loadEvents, displayEventEnd: false, displayEventTitle: true, nextDayThreshold: false }); $('.fc-today').attr('style','background-color:#40cc25'); // For other browsers we can just use : this.$fullCalendarContainer.fullCalendar('refetchEvents'); }, componentWillMount: function () { EventActions.invalidateData(); }, componentDidMount: function () { this.$fullCalendarContainer = $(this.getDOMNode()); this.$fullCalendarContainer.fullCalendar({ defaultView: 'month', selectable: true, eventLimit: true, eventClick: this._onEventSelect, select: this._onCalendarSelect, events: this._loadEvents, displayEventEnd: false, displayEventTitle: true, nextDayThreshold: false }); EventStore.addChangeListener(this._onEventStoreUpdate); }, componentWillUnmount: function () { this.$fullCalendarContainer.fullCalendar('destroy'); EventStore.removeChangeListener(this._onEventStoreUpdate); EventActions.invalidateData(); }, render: function () { return &lt;div/&gt; } }); module.exports = EventCalendar; </code></pre> <p>and this how I am calling the componenet: </p> <pre><code>&lt;EventCalendar onEventSelect={this._onEventSelect} onNewEvent={this._onNewEvent} environmentId={this.props.params.id}/&gt; </code></pre>
3
1,462
Passing a Java Script Millisecond Timer Value to PHP
<p>I have used a Java Scipt millisecond timer, I want to pass the timer value to php when user submits the window. Can anyone please help on how to send the JS timer value to PHP ?</p> <p>My JS Timer Code is as follows :-</p> <p>I need to pass Seconds.Millisecond value to PHP, when user submits a form.</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /&gt; &lt;title&gt;Untitled Document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(function () { $(document).keydown(function (e) { return (e.which || e.keyCode) != 116; }); }); &lt;/script&gt; &lt;script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(function () { $(document).bind('contextmenu',function(e){ e.preventDefault(); alert('Right Click is not allowed'); }); }); &lt;/script&gt; &lt;script&gt; var millisec = 0; var seconds = 0; var timer; function display(){ if (millisec&gt;=99){ millisec=0 seconds+=1 } else millisec+=1 document.d.d2.value = seconds + "." + millisec; timer = setTimeout("display()",8); } function startstoptimer() { if (timer &gt; 0) { clearTimeout(timer); timer = 0; } else { display(); } } &lt;/script&gt; &lt;b&gt;Time Elapsed&lt;/b&gt; &lt;form name="d"&gt; &lt;input type="text" id="time" size="8" name="d2"&gt; &lt;/form&gt; &lt;script&gt; function logout() { alert('Times Up, Thank you for taking part in this Quiz!'); document.forms['QuizQuestions'].submit(); } function StartTimer() { t = setTimeout(logout, 80000)//logs out in 15 mins } function submitThis() { document.forms['QuizQuestions'].submit(); } &lt;/script&gt; &lt;/script&gt; &lt;body bgcolor="#cceeff" onLoad="startstoptimer();"&gt; Hello &lt;?php session_start(); echo $_SESSION['signum']; $my_t=getdate(date("U")); $datestamp = "$my_t[weekday], $my_t[month] $my_t[mday], $my_t[year], $my_t[hours]:$my_t[minutes]:$my_t[seconds]"; $_SESSION['StartTime'] = $datestamp; $_SESSION['timervals']="&lt;script&gt; document.write(c)&lt;/script&gt;"; ?&gt;, All the best ! &lt;form name='QuizQuestions' method="post" action="ScoreQuiz.php"&gt; &lt;pre&gt; &lt;font face='sans-serif' size=2&gt; &lt;input type="hidden" name="time1" id="time"&gt; Question 1 In the following PHP Script, what is the correct output: $x=array("aaa","ttt","www","ttt","yyy","tttt"); $y=array_count_values($x); echo $y[ttt]; &lt;input type="hidden" name="qq1" value="null"&gt; &lt;input type="radio" name="qq1" value="1"&gt; 2 &lt;input type="radio" name="qq1" value="2"&gt; 3 &lt;input type="radio" name="qq1" value="3"&gt; 1 &lt;input type="radio" name="qq1" value="4"&gt; 4 &lt;hr&gt;Question 2 In PHP Which method is used to getting browser properties? &lt;input type="hidden" name="qq2" value="null"&gt; &lt;input type="radio" name="qq2" value="1"&gt; $_SERVER['HTTP_USER_AGENT'] &lt;input type="radio" name="qq2" value="2"&gt; $_SERVER['PHP_SELF'] &lt;input type="radio" name="qq2" value="3"&gt; $_SERVER['SERVER_NAME'] &lt;input type="radio" name="qq2" value="4"&gt; $_SERVER['HTTP_VARIENT'] &lt;hr&gt;Question 3 In the following PHP Script, what is the correct output: $x=dir("."); while($y=$x-&gt;read()) { echo $y." " } $y-&gt;close(); &lt;input type="hidden" name="qq3" value="null"&gt; &lt;input type="radio" name="qq3" value="1"&gt; display all folder names &lt;input type="radio" name="qq3" value="2"&gt; display a folder content &lt;input type="radio" name="qq3" value="3"&gt; display content of the all drives &lt;input type="radio" name="qq3" value="4"&gt; Parse error &lt;hr&gt;Question 4 In PHP, which of the following function is used to insert content of one php file into another php file before server executes it: &lt;input type="hidden" name="qq4" value="null"&gt; &lt;input type="radio" name="qq4" value="1"&gt; include[] &lt;input type="radio" name="qq4" value="2"&gt; #include() &lt;input type="radio" name="qq4" value="3"&gt; include() &lt;input type="radio" name="qq4" value="4"&gt; #include{} &lt;hr&gt;Question 5 In PHP the error control operator is _______ &lt;input type="hidden" name="qq5" value="null"&gt; &lt;input type="radio" name="qq5" value="1"&gt; . &lt;input type="radio" name="qq5" value="2"&gt; * &lt;input type="radio" name="qq5" value="3"&gt; @ &lt;input type="radio" name="qq5" value="4"&gt; &amp; &lt;hr&gt;&lt;/font&gt; &lt;/pre&gt; &lt;input type="submit" value="Submit"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
3
2,321
Missing definitions MVC Views Visual Studio Intellisense
<p>I have a Github project which is an ASP.NET MVC website. There's no trouble in pulling and running the project now. However when coding I get all sorts of errors with e.g:</p> <pre><code>@ViewBag @Html.LabelFor @Scripts </code></pre> <p>Errors:</p> <blockquote> <p>The name 'Scrips/ViewBag' does not exist in the current context</p> <p>'System.Web.WebPages.Html.HtmlHelper' does not contain a definition for 'LabelFor' and no extension method 'Label'For' accepting a first argument of type 'System.Web.WebPages.Html.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)</p> </blockquote> <p>I've tried updating Owin in the Nuget console using:</p> <pre><code>Update-Package owin -reinstall </code></pre> <p>which made it able to run the project</p> <p><code>web.config</code>:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;configuration&gt; &lt;configSections&gt; &lt;sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"&gt; &lt;section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /&gt; &lt;section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /&gt; &lt;/sectionGroup&gt; &lt;/configSections&gt; &lt;system.web.webPages.razor&gt; &lt;host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /&gt; &lt;pages pageBaseType="System.Web.Mvc.WebViewPage"&gt; &lt;namespaces&gt; &lt;add namespace="System.Web.Mvc" /&gt; &lt;add namespace="System.Web.Mvc.Ajax" /&gt; &lt;add namespace="System.Web.Mvc.Html" /&gt; &lt;add namespace="System.Web.Optimization"/&gt; &lt;add namespace="System.Web.Routing" /&gt; &lt;add namespace="HackMySite" /&gt; &lt;/namespaces&gt; &lt;/pages&gt; &lt;/system.web.webPages.razor&gt; &lt;appSettings&gt; &lt;add key="webpages:Enabled" value="false" /&gt; &lt;/appSettings&gt; &lt;system.webServer&gt; &lt;handlers&gt; &lt;remove name="BlockViewHandler"/&gt; &lt;add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" /&gt; &lt;/handlers&gt; &lt;/system.webServer&gt; &lt;/configuration&gt; </code></pre> <p>My partners who also work on this project are also working in Visual Studio and they seem to have no trouble with this.</p> <p>Which is exactly the same with another project I would make myself.</p>
3
1,150
Regular Expression Javascript with XCode
<p>i am trying to sieve out the username and text fields of a HTML Form loading in a web view. Previously i tried this method to narrow down the corresponding text fields that i need but it was tedious and there is no end to the computation of variables. even though i thought i listed out a lot of variables, it was still a hit and miss solution, not all website works.</p> <pre><code>var inputFields = document.querySelectorAll("input[type='text']"); for (var i = inputFields.length &gt;&gt;&gt; 0; i--;) { if ( (inputFields[i].getAttribute('name') == 'email') || (inputFields[i].getAttribute('name') == 'Email') || (inputFields[i].getAttribute('name') == 'e-mail') || (inputFields[i].getAttribute('name') == 'E-mail') || (inputFields[i].getAttribute('name') == 'emailerr') || (inputFields[i].getAttribute('name') == 'UID') || (inputFields[i].getAttribute('name') == 'uid') || (inputFields[i].getAttribute('name') == 'username') || (inputFields[i].getAttribute('name') == 'Username') || (inputFields[i].getAttribute('name') == 'userName') || (inputFields[i].getAttribute('name') == 'user_name') || (inputFields[i].getAttribute('name') == 'User_Name') || (inputFields[i].getAttribute('name') == 'User_name') || (inputFields[i].getAttribute('name') == 'userid') || (inputFields[i].getAttribute('name') == 'userID') || (inputFields[i].getAttribute('name') == 'UserID') || (inputFields[i].getAttribute('name') == 'Userid') || (inputFields[i].getAttribute('name') == 'ID') || (inputFields[i].getAttribute('name') == 'id') || (inputFields[i].getAttribute('name') == 'j_username') || (inputFields[i].getAttribute('name') == 'session_key') || (inputFields[i].getAttribute('name') == 'login_password')) { inputFields[i].value = '%@';}} </code></pre> <p>Then i was told about RegularExpression but i wasn't very familiar with it and i read some tutorials about it but not specific to my project to try and get what it means and i piece out this code which is also a hit and miss solution. I am not even sure if i am doing it right but the code is definitely short this time for sure. </p> <pre><code>var inputFields = document.querySelectorAll("input[type='text']"); for (var i = inputFields.length &gt;&gt;&gt; 0; i--;) { regStr = /(mail|user|iden|name|id|key|login|username|email)/i; searchName = inputFields[i].getAttribute('name').search(regStr); searchId = inputFields[i].getAttribute('id').search(regStr); if (!(searchName == -1) || !(searchId == -1)){ inputFields[i].value = '%@';}} </code></pre> <p>Can someone tell me if i have done this RegularExpression correctly? i really have no idea. Some sites it works, some it doesn't. I understand that what i am searching for is configurable by developers and i won't have a 100% hit on all site, but what puzzle me is that sometime even though the term matches exactly one of my search variable it didn't work.</p>
3
1,165
JHipster Liquibase MigrationFailedException
<p>I have a simple test application in jhipster. Liquibase does not generate fake data correctly and does not generate foreign keys into the database of entity B. Is it a known bug or what am I doing wrong? I would like to continue using Liquibase, but it seems to be very error-prone.</p> <pre><code>liquibase.exception.LiquibaseException: liquibase.exception.MigrationFailedException: Migration failed for change set config/liquibase/changelog/20211124143930_added_entity_constraints_B.xml::20211124143930-2::jhipster: Reason: liquibase.exception.DatabaseException: Feld &quot;A_ID&quot; nicht gefunden Column &quot;A_ID&quot; not found; SQL statement: ALTER TABLE PUBLIC.b ADD CONSTRAINT fk_bb__aa_id FOREIGN KEY (a_id) REFERENCES PUBLIC.a (id) [42122-200] [Failed SQL: (42122) ALTER TABLE PUBLIC.b ADD CONSTRAINT fk_bb__aa_id FOREIGN KEY (a_id) REFERENCES PUBLIC.a (id)] </code></pre> <p>JDL:</p> <pre><code>application { config { baseName myApp, applicationType monolith, packageName com.myapp, authenticationType jwt, prodDatabaseType mysql, clientFramework angular } entities * } entity A { number Long } entity B { testNumber Long } relationship OneToMany { A{b(testNumber)} to B{a(number)} } </code></pre> <p>JHipster info:</p> <pre><code>INFO! Using JHipster version installed locally in current project's node_modules Welcome to the JHipster Information Sub-Generator ##### **JHipster Version(s)** ``` my-app@0.0.1-SNAPSHOT C:\Users\kleinoth\IdeaProjects\JHipster\zprojekt `-- generator-jhipster@7.3.0 ``` ##### **JHipster configuration, a `.yo-rc.json` file generated in the root folder** &lt;details&gt; &lt;summary&gt;.yo-rc.json file&lt;/summary&gt; &lt;pre&gt; { &quot;generator-jhipster&quot;: { &quot;authenticationType&quot;: &quot;jwt&quot;, &quot;cacheProvider&quot;: &quot;ehcache&quot;, &quot;clientFramework&quot;: &quot;angularX&quot;, &quot;serverPort&quot;: &quot;8080&quot;, &quot;serviceDiscoveryType&quot;: false, &quot;skipUserManagement&quot;: false, &quot;withAdminUi&quot;: true, &quot;baseName&quot;: &quot;myApp&quot;, &quot;buildTool&quot;: &quot;maven&quot;, &quot;databaseType&quot;: &quot;sql&quot;, &quot;devDatabaseType&quot;: &quot;h2Disk&quot;, &quot;enableHibernateCache&quot;: true, &quot;enableSwaggerCodegen&quot;: false, &quot;enableTranslation&quot;: true, &quot;jhiPrefix&quot;: &quot;jhi&quot;, &quot;languages&quot;: [&quot;en&quot;], &quot;messageBroker&quot;: false, &quot;prodDatabaseType&quot;: &quot;mysql&quot;, &quot;searchEngine&quot;: false, &quot;skipClient&quot;: false, &quot;testFrameworks&quot;: [], &quot;websocket&quot;: false, &quot;enableGradleEnterprise&quot;: false, &quot;gradleEnterpriseHost&quot;: &quot;&quot;, &quot;applicationType&quot;: &quot;monolith&quot;, &quot;packageName&quot;: &quot;com.myapp&quot;, &quot;packageFolder&quot;: &quot;com/myapp&quot;, &quot;jhipsterVersion&quot;: &quot;7.3.0&quot;, &quot;skipServer&quot;: false, &quot;clientPackageManager&quot;: &quot;npm&quot;, &quot;dtoSuffix&quot;: &quot;DTO&quot;, &quot;entitySuffix&quot;: &quot;&quot;, &quot;reactive&quot;: false, &quot;clientTheme&quot;: &quot;none&quot;, &quot;clientThemeVariant&quot;: &quot;&quot;, &quot;applicationIndex&quot;: 0, &quot;entities&quot;: [&quot;A&quot;, &quot;B&quot;], &quot;skipCheckLengthOfIdentifier&quot;: false, &quot;skipFakeData&quot;: false, &quot;blueprints&quot;: [], &quot;otherModules&quot;: [], &quot;pages&quot;: [], &quot;nativeLanguage&quot;: &quot;en&quot;, &quot;creationTimestamp&quot;: 1637764650493, &quot;jwtSecretKey&quot;: &quot;YourJWTSecretKeyWasReplacedByThisMeaninglessTextByTheJHipsterInfoCommandForObviousSecurityReasons&quot;, &quot;devServerPort&quot;: 4200, &quot;lastLiquibaseTimestamp&quot;: 1637764770000 } } &lt;/pre&gt; &lt;/details&gt; ##### **JDL for the Entity configuration(s) `entityName.json` files generated in the `.jhipster` directory** &lt;details&gt; &lt;summary&gt;JDL entity definitions&lt;/summary&gt; &lt;pre&gt; entity A { number Long } entity B { testNumber Long } relationship OneToMany { A{b(testNumber)} to B{a(number)} } &lt;/pre&gt; &lt;/details&gt; ##### **Environment and Tools** openjdk version &quot;11.0.9.1&quot; 2020-11-04 OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.9.1+1) OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.9.1+1, mixed mode) git version 2.33.1.windows.1 node: v14.17.1 npm: 8.0.0 Docker version 20.10.8, build 3967b7d docker-compose version 1.29.2, build 5becea4c No change to package.json was detected. No package manager install will be executed. Congratulations, JHipster execution is complete! Sponsored with ❤️ by @oktadev. </code></pre>
3
2,145
How to make the height of a TextField and a search button equal in Flutter?
<p>I'm creating a Flutter app. The app has a <code>TextField</code> and an <code>IconButton</code>, I want to make their height equal. Here is the current code:</p> <pre class="lang-dart prettyprint-override"><code>import 'package:flutter/material.dart'; class MyHomePage extends StatefulWidget { const MyHomePage({Key? key}) : super(key: key); @override State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState(); } class _MyHomePageState extends State&lt;MyHomePage&gt; { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 20), child: SafeArea( child: Row( children: [ const Expanded( child: TextField( decoration: InputDecoration( fillColor: Colors.yellow, filled: true, hintText: &quot;Input here...&quot;, isCollapsed: true, border: OutlineInputBorder( borderSide: BorderSide( width: 0, style: BorderStyle.none, ), ), ), ), ), const SizedBox(width: 10), Ink( decoration: const BoxDecoration( color: Colors.yellow, ), child: IconButton( onPressed: () =&gt; {}, icon: const Icon(Icons.search) ), ) ], )), ), ), ); } } </code></pre> <p>This is the result:</p> <p><a href="https://i.stack.imgur.com/93beM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/93beM.png" alt="enter image description here" /></a></p> <p>You can see that their height is not the same. There are some suggestions on the Internet to make their height equal, but none of them worked for me. Most suggest using a <code>contentPadding</code> inside <code>TextField</code>, like this:</p> <pre class="lang-dart prettyprint-override"><code>TextField( decoration: InputDecoration( fillColor: Colors.yellow, filled: true, hintText: &quot;Input here...&quot;, isCollapsed: true, // Add this contentPadding: EdgeInsets.all(12), border: OutlineInputBorder( borderSide: BorderSide( width: 0, style: BorderStyle.none, ), ), ), ), </code></pre> <p>This seems to work. My complaint with this method is that I need to manually try the correct padding, which is <code>12</code> in the above code. Does the number always work on all devices? I'm not sure.</p> <p>Some suggest using a <code>SizedBox</code>, I've tried it, it doesn't work for me either. Here is my code:</p> <pre class="lang-dart prettyprint-override"><code>import 'package:flutter/material.dart'; class MyHomePage extends StatefulWidget { const MyHomePage({Key? key}) : super(key: key); @override State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState(); } class _MyHomePageState extends State&lt;MyHomePage&gt; { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 20), child: SafeArea( child: Row( children: [ const Expanded( child: SizedBox( height: 80, child: TextField( decoration: InputDecoration( fillColor: Colors.yellow, filled: true, hintText: &quot;Input here...&quot;, border: OutlineInputBorder( borderSide: BorderSide( width: 0, style: BorderStyle.none, ), ), ), ), ), ), const SizedBox(width: 10), SizedBox( height: 80, child: Ink( decoration: const BoxDecoration( color: Colors.yellow, ), child: IconButton( onPressed: () =&gt; {}, icon: const Icon(Icons.search)), )) ], )), ), ), ); } } </code></pre> <p>Here is the screenshot:</p> <p><a href="https://i.stack.imgur.com/T8wWy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T8wWy.png" alt="enter image description here" /></a></p> <p>My question is, what's the correct way to make it work?</p>
3
2,714
Microk8s ImagePullBackOff cannot be fixed by modifying the config
<p>I have installed a microk8s to ubuntu (arm64 bit version), I would like to access my local image registry provided by the <code>microk8s enable registry</code>. But I get a ImagePullBackOff error, I have tried to modify <code>/var/snap/microk8s/current/args/containerd.toml</code> config, but it not works:</p> <pre><code>[plugins.cri.registry] [plugins.cri.registry.mirrors] [plugins.cri.registry.mirrors.&quot;docker.io&quot;] endpoint = [&quot;https://registry-1.docker.io&quot;] [plugins.cri.registry.mirrors.&quot;localhost:32000&quot;] endpoint = [&quot;http://localhost:32000&quot;] [plugins.cri.registry.mirrors.&quot;192.168.0.45:32000&quot;] endpoint = [&quot;http://192.168.0.45:32000&quot;] [plugins.cri.registry.configs.&quot;192.168.0.45:32000&quot;.tls] insecure_skip_verify = true </code></pre> <p>My pod status:</p> <pre><code>microk8s.kubectl describe pod myapp-7d655f6ccd-gpgkx Name: myapp-7d655f6ccd-gpgkx Namespace: default Priority: 0 Node: 192.168.0.66/192.168.0.66 Start Time: Mon, 15 Mar 2021 16:53:30 +0000 Labels: app=myapp pod-template-hash=7d655f6ccd Annotations: &lt;none&gt; Status: Pending IP: 10.1.54.7 IPs: IP: 10.1.54.7 Controlled By: ReplicaSet/myapp-7d655f6ccd Containers: myapp: Container ID: Image: 192.168.0.45:32000/myapp:latest Image ID: Port: 9000/TCP Host Port: 0/TCP State: Waiting Reason: ImagePullBackOff Ready: False Restart Count: 0 Limits: memory: 384Mi Requests: memory: 128Mi Environment: REDIS: redis MYSQL: mysql Mounts: /var/run/secrets/kubernetes.io/serviceaccount from default-token-dn4bk (ro) Conditions: Type Status Initialized True Ready False ContainersReady False PodScheduled True Volumes: default-token-dn4bk: Type: Secret (a volume populated by a Secret) SecretName: default-token-dn4bk Optional: false QoS Class: Burstable Node-Selectors: &lt;none&gt; Tolerations: node.kubernetes.io/not-ready:NoExecute for 300s node.kubernetes.io/unreachable:NoExecute for 300s Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Scheduled 15m default-scheduler Successfully assigned default/myapp-7d655f6ccd-gpgkx to 192.168.0.66 Normal Pulling 14m (x4 over 15m) kubelet Pulling image &quot;192.168.0.45:32000/myapp:latest&quot; Warning Failed 14m (x4 over 15m) kubelet Failed to pull image &quot;192.168.0.45:32000/myapp:latest&quot;: rpc error: code = Unknown desc = failed to resolve image &quot;192.168.0.45:32000/myapp:latest&quot;: no available registry endpoint: failed to do request: Head &quot;https://192.168.0.45:32000/v2/myapp/manifests/latest&quot;: http: server gave HTTP response to HTTPS client Warning Failed 14m (x4 over 15m) kubelet Error: ErrImagePull Warning Failed 13m (x6 over 15m) kubelet Error: ImagePullBackOff Normal BackOff 20s (x63 over 15m) kubelet Back-off pulling image &quot;192.168.0.45:32000/myapp:latest&quot; </code></pre> <p>version info:</p> <pre><code>microk8s.kubectl version Client Version: version.Info{Major:&quot;1&quot;, Minor:&quot;18&quot;, GitVersion:&quot;v1.18.15&quot;, GitCommit:&quot;73dd5c840662bb066a146d0871216333181f4b64&quot;, GitTreeState:&quot;clean&quot;, BuildDate:&quot;2021-01-13T13:22:41Z&quot;, GoVersion:&quot;go1.13.15&quot;, Compiler:&quot;gc&quot;, Platform:&quot;linux/arm64&quot;} Server Version: version.Info{Major:&quot;1&quot;, Minor:&quot;18&quot;, GitVersion:&quot;v1.18.15&quot;, GitCommit:&quot;73dd5c840662bb066a146d0871216333181f4b64&quot;, GitTreeState:&quot;clean&quot;, BuildDate:&quot;2021-01-13T13:14:05Z&quot;, GoVersion:&quot;go1.13.15&quot;, Compiler:&quot;gc&quot;, Platform:&quot;linux/arm64&quot;} </code></pre> <p>It seems that it want to use https instead of http.</p> <p>How can I use insecure option in microk8s with containerd?</p>
3
2,079
Convert string to dict in python, but string dict has no quotes and = instead of :
<p>I have dictionaries as strings. In the string the keys and values have no quotes, and instead of having key-value pairs in the usual format (key:value), I have them like this key=value. An example of such string is here below</p> <p><code>{created={type=FREEMIUM, title={value=Drool is love, drool is live..., _iscolumngrouppresent=true}, content={value=null, _iscolumngrouppresent=false}, status=PROCESSING, tags=[], attachments=[{payload_0={video_id=null, image_id=2efbff31-a0a6-4f4c-a163-667c4aabd111}}], visible_at={value=null, _iscolumngrouppresent=false}, author_user_id=8cfdf75d-5816-42f8-906f-8b203bb2c99f, _iscolumngrouppresent=true}, _iscolumngrouppresent=true}</code></p> <p>Which I would like to convert to</p> <pre><code> &quot;created&quot;: { &quot;type&quot;: &quot;FREEMIUM&quot;, &quot;title&quot;: { &quot;value&quot;: &quot;Drool is love, drool is live...&quot;, &quot;_iscolumngrouppresent&quot;: True }, &quot;content&quot;: { &quot;value&quot;: None, &quot;_iscolumngrouppresent&quot;: False }, &quot;status&quot;: &quot;PROCESSING&quot;, &quot;tags&quot;: [], &quot;attachments&quot;: [ { &quot;payload_0&quot;: { &quot;video_id&quot;: None, &quot;image_id&quot;: &quot;2efbff31-a0a6-4f4c-a163-667c4aabd111&quot; } } ], &quot;visible_at&quot;: { &quot;value&quot;: None, &quot;_iscolumngrouppresent&quot;: False }, &quot;author_user_id&quot;: &quot;8cfdf75d-5816-42f8-906f-8b203bb2c99f&quot;, &quot;_iscolumngrouppresent&quot;: True }, &quot;_iscolumngrouppresent&quot;: True } </code></pre> <p>I tried to parse the string by myself, but there are cases where it fails. Mainly when a value of a key:value pair is a string with commas in it (&quot;,&quot;).</p> <p>Is there a tooling already out there that I can use. Any ideas are more than welcome.</p> <p>Thanks in advance</p>
3
1,071
Discord.js awaitmessage error, how to fix?
<p>I was making this new bot and used awaitmessage function.When a user use the cmd '!gangsug', the bot is supposed to ask a question like - &quot;Please choose a option - RP or Fight&quot; and when the user uses an option it is supposed to give a reply. (Which is a embed one). I have given two different replies for the 2 answers given by the user.(One for the answer &quot;RP&quot; and the other for the answer &quot;Fight&quot;). In this case, by bot is giving same answer for both answer. If the user types &quot;RP&quot; or &quot;Fight&quot; same reply is being given by the bot. I hope you understood the problem.The code will be given below (ofc only the part where the problem comes)</p> <pre><code>if (message.content === `${prefix}gangsug`) { message.reply('Hey there! Please choose a option.\n' + 'Confirm with `RP` or with `Fight`.'); // First argument is a filter function - which is made of conditions // m is a 'Message' object message.channel.awaitMessages(m =&gt; m.author.id == message.author.id, {max: 1, time: 30000}).then(collected =&gt; { // only accept messages by the user who sent the command // accept only 1 message, and return the promise after 30000ms = 30s // first (and, in this case, only) message of the collection if (collected.first().content.toLowerCase() == 'RP') { message.reply(suggestgang1); } else message.reply(suggestgang2); message.reply(suggestgang3); }).catch(() =&gt; { message.reply('No answer after 30 seconds, req canceled.'); }); } } ); </code></pre> <p>**Yea, this is the code..It would be great of you give an answer by stating the problem and a fixed code to replace this one. Thank you :) **</p>
3
1,138
how to display id of input field with respective those value
<p>I have multiple forms like shown below:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function chartsubmitbtn() { var x = $('#x_axis_t1').val(); alert(x); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;div id="trace-div1"&gt; &lt;h4&gt;&lt;b&gt;Trace 1 &lt;/b&gt;&lt;/h4&gt; &lt;form&gt; &lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;X Axis: &lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="t1_x_axis" id="x_axis_t1" size="50"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;Y Axis: &lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="t1_y_axis" id="y_axis_t1" size="50"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/form&gt; &lt;/div&gt; &lt;div id="trace-div2"&gt; &lt;h4&gt;&lt;b&gt;Trace 2 &lt;/b&gt;&lt;/h4&gt; &lt;form&gt; &lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;X Axis: &lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="t1_x_axis" id="x_axis_t2" size="50"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;Y Axis: &lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="t1_y_axis" id="y_axis_t2" size="50"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/form&gt; &lt;/div&gt; &lt;button type="button" id="chart-report-submit" onclick="chartsubmitbtn();"&gt;Submit&lt;/button&gt;</code></pre> </div> </div> </p> <p>in above code if i click the submit button it will display values with respect there id .</p> <p>my expected out put is </p> <pre><code>x_axis_t1 = "x axis t1"; y_axis_t1 = "y axis t1"; x_axis_t2 = "x axis t2"; y_axis_t2 = "y axis t2"; </code></pre> <p>in above <code>x_axis_t1,x_axis_t1,x_axis_t1</code> and <code>x_axis_t1</code> are IDs with respect there input text values.</p>
3
1,175
System.IO.FileNotFoundExecption, GUID are different for filename stored in database and file stored on server
<p>I am trying to use GUID to allow users to upload files with same names, but the GUIDs attach to filenames &amp; filepaths stored in database are different from the GUIDs attached to the files stored on server. It means it is giving two different GUIDs to the same file. So when I am trying to download the file from server its giving me an FileNotFound exception as the command arguement takes the filename from database and therefore when it goes to server its not able to find the file as the GUID of the same file stored on the server is different. Please if anybody can give me some advise that would be appreciable.</p> <p>My Database schema:</p> <pre><code>Table: Sales Columns: ReceiptFileName(Stores Name without GUID) Coulmn:ReceiptFilePath(Stores file path with GUID) Column: filename(Stores filename with GUID) </code></pre> <p>Aspx code:</p> <pre><code>&lt;ItemTemplate&gt; &lt;asp:LinkButton ID="LinkButton1" runat="server" CommandName="Download" CommandArgument='&lt;%# Bind("filename") %&gt;' Text='&lt;%# Bind("ReceiptFileName") %&gt;' &gt;&lt;/asp:LinkButton&gt; &lt;/ItemTemplate&gt; </code></pre> <p>Code for upload:</p> <pre><code>if (FileUpload1.HasFile) { //check file Extension &amp; Size string filename = FileUpload1.PostedFile.FileName; { filename = filename + Guid.NewGuid(); } int filesize = FileUpload1.PostedFile.ContentLength; if (filesize &gt; (20 * 1024)) { Label1.Text = "Please upload a zip or a pdf file"; } string fileextention = System.IO.Path.GetExtension(FileUpload1.FileName); if (fileextention.ToLower() != ".zip" &amp;&amp; fileextention.ToLower() != ".pdf") { Label1.ForeColor = System.Drawing.Color.Green; Label1.Text = "Please upload a zip or a pdf file"; } else { //string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName); string ReceiptFileName = Path.GetFileName(filename); //save file to disk FileUpload1.SaveAs(Server.MapPath("~/Reimbursement/Reciepts/" + ReceiptFileName)); } } </code></pre> <p>Method for adding filename and receiptname</p> <pre><code>public static int AddSale(SaleID, string ReceiptFileName,string ReceiptFilePath, string filename) { int sale; SqlCommand addSales = new SqlCommand("addSale", con); addSale.CommandType = CommandType.StoredProcedure; addSale.Parameters.AddWithValue("@ReceiptFileName", ReceiptFileName); addSale.Parameters.AddWithValue("@filename", filename); addSale.Parameters.AddWithValue("@ReceiptFilePath", ReceiptFilePath); try { con.Open(); added = addSale.ExecuteNonQuery(); } finally { con.Close(); } </code></pre> <p>Code for download:</p> <pre><code>protected void gridExpenditures_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Download") { Response.Clear(); Response.ContentType = "application/octet-stream"; Response.AppendHeader("content-disposition", "FileName=" + e.CommandArgument); Response.TransmitFile(Server.MapPath("~/Reimbursement/Reciepts/") + e.CommandArgument); Response.End(); } } </code></pre>
3
1,197
Android : IndexOutOfBoundsException: Invalid index 8, size is 0
<p>I have an error ,and i'm seeking it since yesterday .It seems to be a broblem of size in an array. This is the function when the exception seems to happen :</p> <pre><code> private XYMultipleSeriesDataset getTruitonBarDataset() { XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset(); int [] classObject =new int[] {-70,-56,-45,-80,-47,-55,-80,-50,-75,-85,-35,-45};//Signal strength receiver from each access point for (int j=0;j&lt;classObject.length;j++){ values.add(new int[] { classObject[j]}); //every serie will concern an access point and contain one RSSI } final int nr = classObject.length; ArrayList&lt;String&gt; legendTitles = new ArrayList&lt;String&gt;(); for (int k = 0; k &lt; classObject.length; k++) { legendTitles.add("Sales"+k);//every serie will have a legend } SERIES_NR = classObject.length ;//number of access point for (int i = 0; i &lt; SERIES_NR; i++) {//Loop for every series CategorySeries series = new CategorySeries(legendTitles.get(i)); int[] v = values.get(i); int seriesLength = v.length; dataset.addSeries(series.toXYSeries()); for (int k = 0; k &lt; seriesLength; k++) { Log.i("STOOP SERIES_NR",SERIES_NR+""); Log.i("STOOP ii",i+""); Log.i("STOOP",k+""); Log.i("STOOP",v[k]+""); Log.i("STOOP",v[k] / 10+""); /* XYSeries tempSerie = dataset.getSeriesAt(i); tempSerie.add(i, 40 - v[k] %10);*/ switch (v[k] / 10){ case -8 : //series.add(classObject[k]); if (v[k] %10 == 0) //series.add(40); {XYSeries tempSerie = dataset.getSeriesAt(i); tempSerie.add(i, 40); } else //series.add(40 - v[k] %10); {XYSeries tempSerie = dataset.getSeriesAt(i); tempSerie.add(i, 40 - v[k] %10); } break; case -7 : //series.add(classObject[k]); if (v[k] %10 == 0) { XYSeries tempSerie = dataset.getSeriesAt(i); tempSerie.add(i, 50); tempSerie.addAnnotation("text *** "+i, 0, 50); } else // EDITED //series.add(50 - v[k] %10); {XYSeries tempSerie = dataset.getSeriesAt(i); // ERROR LINE 100 tempSerie.add(i, 7.5,50 - v[k] %10); tempSerie.add(i,50 - v[k] %10);//right line // series.toXYSeries().add(7.5,50 - v[k] %10); } break; case -6 : //series.add(classObject[k]); if (v[k] %10 == 0) //series.add(60); {XYSeries tempSerie = dataset.getSeriesAt(i); tempSerie.add(i, 60); } else //series.add(60 - v[k] %10); {XYSeries tempSerie = dataset.getSeriesAt(i); tempSerie.add(i, 60 - v[k] %10); } break; case -5 : //series.add(classObject[k]); if (v[k] %10 == 0) //series.add(70); {XYSeries tempSerie = dataset.getSeriesAt(i); tempSerie.add(i, 70); } else //series.add(70 - v[k] %10); {XYSeries tempSerie = dataset.getSeriesAt(i); tempSerie.add(i, 70 - v[k] %10); } break; case -4 : //series.add(classObject[k]); if (v[k] %10 == 0) //series.add(80); {XYSeries tempSerie = dataset.getSeriesAt(i); tempSerie.add(i, 80); } else {XYSeries tempSerie = dataset.getSeriesAt(i); tempSerie.add(i, 80 - v[k] %10); tempSerie.addAnnotation("text"+i, i, 80 - v[k] %10); } break; case -3 : //series.add(classObject[k]); if (v[k] %10 == 0) {XYSeries tempSerie = dataset.getSeriesAt(i); tempSerie.add(i, 90); } else //series.add(90 - v[k] %10); {XYSeries tempSerie = dataset.getSeriesAt(i); tempSerie.add(i, 90 - v[k] %10); } break; } } } return dataset; } </code></pre> <p>When i delete the switch condition part, and put this code, i don't get any exception :</p> <pre><code>XYSeries tempSerie = dataset.getSeriesAt(i); tempSerie.add(i, 40 - v[k] %10); </code></pre> <p>.I tryed to run the code mannualy ,and i did not found an error (maybe i don't see it ). Here the running stops (Log.i )</p> <pre><code>04-11 08:58:24.415: I/STOOP(17738): -47 04-11 08:58:24.415: I/STOOP(17738): -4 04-11 08:58:24.415: I/STOOP SERIES_NR(17738): 12 04-11 08:58:24.415: I/STOOP ii(17738): 5 04-11 08:58:24.415: I/STOOP(17738): 0 04-11 08:58:24.415: I/STOOP(17738): -55 04-11 08:58:24.415: I/STOOP(17738): -5 04-11 08:58:24.416: I/STOOP SERIES_NR(17738): 12 04-11 08:58:24.416: I/STOOP ii(17738): 6 04-11 08:58:24.416: I/STOOP(17738): 0 04-11 08:58:24.416: I/STOOP(17738): -80 04-11 08:58:24.416: I/STOOP(17738): -8 04-11 08:58:24.416: I/STOOP SERIES_NR(17738): 12 04-11 08:58:24.416: I/STOOP ii(17738): 7 04-11 08:58:24.416: I/STOOP(17738): 0 04-11 08:58:24.416: I/STOOP(17738): -50 04-11 08:58:24.416: I/STOOP(17738): -5 04-11 08:58:24.416: I/STOOP SERIES_NR(17738): 12 04-11 08:58:24.416: I/STOOP ii(17738): 8 04-11 08:58:24.416: I/STOOP(17738): 0 04-11 08:58:24.416: I/STOOP(17738): -75 04-11 08:58:24.417: I/STOOP(17738): -7 </code></pre> <p><strong>And this is the exception that i'm having :</strong></p> <pre><code> 04-11 08:58:24.431: W/dalvikvm(17738): threadid=1: thread exiting with uncaught exception (group=0x419559a8) 04-11 08:58:24.439: E/AndroidRuntime(17738): FATAL EXCEPTION: main 04-11 08:58:24.439: E/AndroidRuntime(17738): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.truitonachartengine/com.example.truitonachartengine.TruitonAChartEngineActivity}: java.lang.IndexOutOfBoundsException: Invalid index 8, size is 0 04-11 08:58:24.439: E/AndroidRuntime(17738): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343) 04-11 08:58:24.439: E/AndroidRuntime(17738): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395) 04-11 08:58:24.439: E/AndroidRuntime(17738): at android.app.ActivityThread.access$600(ActivityThread.java:162) 04-11 08:58:24.439: E/AndroidRuntime(17738): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364) 04-11 08:58:24.439: E/AndroidRuntime(17738): at android.os.Handler.dispatchMessage(Handler.java:107) 04-11 08:58:24.439: E/AndroidRuntime(17738): at android.os.Looper.loop(Looper.java:194) 04-11 08:58:24.439: E/AndroidRuntime(17738): at android.app.ActivityThread.main(ActivityThread.java:5371) 04-11 08:58:24.439: E/AndroidRuntime(17738): at java.lang.reflect.Method.invokeNative(Native Method) 04-11 08:58:24.439: E/AndroidRuntime(17738): at java.lang.reflect.Method.invoke(Method.java:525) 04-11 08:58:24.439: E/AndroidRuntime(17738): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833) 04-11 08:58:24.439: E/AndroidRuntime(17738): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) 04-11 08:58:24.439: E/AndroidRuntime(17738): at dalvik.system.NativeStart.main(Native Method) 04-11 08:58:24.439: E/AndroidRuntime(17738): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 8, size is 0 04-11 08:58:24.439: E/AndroidRuntime(17738): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251) 04-11 08:58:24.439: E/AndroidRuntime(17738): at java.util.ArrayList.add(ArrayList.java:143) 04-11 08:58:24.439: E/AndroidRuntime(17738): at org.achartengine.util.IndexXYMap.put(IndexXYMap.java:42) 04-11 08:58:24.439: E/AndroidRuntime(17738): at org.achartengine.model.XYSeries.add(XYSeries.java:155) 04-11 08:58:24.439: E/AndroidRuntime(17738): at com.example.truitonachartengine.TruitonAChartEngineActivity.getTruitonBarDataset(TruitonAChartEngineActivity.java:100) 04-11 08:58:24.439: E/AndroidRuntime(17738): at com.example.truitonachartengine.TruitonAChartEngineActivity.onCreate(TruitonAChartEngineActivity.java:37) 04-11 08:58:24.439: E/AndroidRuntime(17738): at android.app.Activity.performCreate(Activity.java:5122) 04-11 08:58:24.439: E/AndroidRuntime(17738): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081) 04-11 08:58:24.439: E/AndroidRuntime(17738): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307) 04-11 08:58:24.439: E/AndroidRuntime(17738): ... 11 more </code></pre> <p>I'll appreciate any help .Thank you.</p>
3
5,056