text
stringlengths
64
81.1k
meta
dict
Q: Can someone explain string formating in java for the below code Can someone explain string formatting in java and also explanation for below code on how it will work System.out.printf( "%-15s%03d %n", s1, x); A: If you run it with some given values you will get something like: for: System.out.printf( "%-15s%03d %n", "string1", 123); you get: 'string1 123 ' (without the '' of course and followed by an empty line) As you can see, the first format will complete until 15 chars if the string is less then 15, for the second parameter, if it is less then 3 digits, it will add 0's in front of the number to match the 3 digits. After a space, you will get a new line too.
{ "pile_set_name": "StackExchange" }
Q: Restrict iOS app to wifi only? I am looking for a way to restrict my iOS app (or even a portion of it ) to wifi only. I've looked through the reachability example and haven't really come up with a solution. I can get it to display a message when the user is connected to 3g, but I don't know how to get it to stop loading the view. I have a view that loads another view when a button is pressed. I want that second view to close if the device is connected to 3g. How can I go about doing this? A: I've never done what you're trying to do before, but I imagine it's just a matter of figuring out the Reachability API. I'd start out with some code in your AppDelegate class: // ivars Reachability *wifiReach; Reachability *hostReach; - (void) reachabilityChanged: (NSNotification *)note { Reachability *curReach = (Reachability *)[note object]; if ([curReach currentReachabilityStatus] == NotReachable) { // do something } } - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil]; hostReach = [[Reachability reachabilityWithHostName: @"www.apple.com"] retain]; [hostReach startNotifier]; wifiReach = [[Reachability reachabilityForLocalWiFi] retain]; [wifiReach startNotifier]; // controller setup viewController = [[CFSplashViewController alloc] init]; [window addSubview:viewController.view]; [window makeKeyAndVisible]; return YES; } It's a really simple piece of code. What you could do here is listen for changes in reachability status and then set up your app to react appropriately. You don't necessarily have to do this in your AppDelegate class. It all depends on what you want to accomplish.
{ "pile_set_name": "StackExchange" }
Q: Deleting all records in indexedDB object store for a specific index value For an object store with an array key of [a,b] where a is also an index, is there a more efficient way to delete all records for a specific value of a than opening a cursor on the index a and deleting each record as step through the cursor? Is there a way to define a key range for an index only, or just on a and leave b open to any value, such that can delete all records for that key range? In this particular case, a is a positive integer excluding zero and b is a positive integer including zero. Would a key range from [n,0] to [n+1,0] be guaranteed to return all keys for equivalent to index a=n regardless of the value of b? For example, IDBKeyRange.bound( [2,0], [3,0], false, true) would return all keys for index a=2? The above key range works for my test cases, but I'd like to know how to handle the situation if b wasn't an integer, making it sort of a special case. It appears that the following would not work because it would delete only a record with a key of 2. Is there a method like this for a general case? i = transaction.objectStore( name ).index( 'a' ); i.delete( 2 ); Thank you. As I learned more and looked over code below that is generating the desired result, I'm not sure anymore why it is working. The key is compound [ topic, note ] and k is set to only the topic value. So, no key in n should match k, should it? I don't understand why n.openCursor( k ) returned any records to work on, since none have a simple key. Is k being treated as the key of the records or the index value? T = DB_open.base.transaction( ['notes'], 'readwrite' ), o = T.objectStore( 'notes' ), k = IDBKeyRange.only( topic_value ); n = T.objectStore( 'notes' ).index( 'topic' ); n.openCursor( k ).onsuccess = ( e ) => { /* stepped through cursor */ }; It appears that what I wasn't understanding is that the key parameter for an index is not the key of the actual record but the key of the index, here the topic value. For read operations and cursors, that works fine; but there is not a delete method on an index, such as a deleteAll equivalent to getAll. I think I must have understood this several months ago when I wrote the cursor code but now got myself confused in trying to delete a set of records for a specific index value without opening a cursor. A: It appears that what I wasn't understanding is that the key parameter for an index is not the key of the actual record but the key of the index, here the topic value. For read operations and cursors, that works fine; but there is not a delete method on an index, such as a deleteAll equivalent to getAll. You are correct, key is the index key. And there is no single command to say "delete every record matching a certain key or key range in an index". Here is some discussion about this - my interpretation is that there isn't a great argument against that functionality existing, but it's a rare enough use case that it's just sat there as an unimplemented feature request. However if the primary key is an compound key and the first entry in the compound key is the field you want to filter on, you can use a KeyRange and pass it to IDBObjectStore.delete like you suggested: In this particular case, a is a positive integer excluding zero and b is a positive integer including zero. Would a key range from [n,0] to [n+1,0] be guaranteed to return all keys for equivalent to index a=n regardless of the value of b? For example, IDBKeyRange.bound( [2,0], [3,0], false, true) would return all keys for index a=2? Yes, that would work. You can play around with it an see for yourself too: var range = IDBKeyRange.bound( [2,0], [3,0], false, true); console.log(range.includes([2, -1])); // false console.log(range.includes([2, 0])); // true console.log(range.includes([2, 100])); // true console.log(range.includes([2, Infinity])); // true console.log(range.includes([3, 0])); // false Just for fun... you could also define your key range like this: var range = IDBKeyRange.bound( [2,0], [2,""], false, true); since numbers sort before strings. There's a bunch of other ways you could write the same thing. It all comes down to how cross-type comparisons are done in the IndexedDB spec. As soon as you have arrays or multiple types, things get interesting.
{ "pile_set_name": "StackExchange" }
Q: Library for WYSIWYG Editor I created a simple CMS. And now, when users add their own articles, I want them to add as html without writing any html. Just like stackoverflow does. I use PHP and MySQL. For example, user creates an article (user does not have html skills), now JS builds markup and this will be added into MySQL via PHP as html. A: StackOverflow uses a Markdown system for inputting text. Specifically, PageDown, which runs in the client. It's fairly simple to use and set up, and if you want to store as HTML, you can just convert the article to HTML sometime before storing it into your MySQL database. Finding a MarkDown implementation that can be used from PHP (with sanitizer support) would probably be better than trusting the HTML generated by the article when they submit. At the very least, you should check the article to make sure it's both valid HTML and only using white-listed tags!
{ "pile_set_name": "StackExchange" }
Q: Using .net3.5 assemblies and mixed-mode dlls on .net4 Its in context of a C++ application that uses .net3.5 assemblies through mixed-mode (again targeted .net3.5) assemblies. The native app explicitly loads the .net assemblies. I mainly want to know the repercussions of using .net3.5 assemblies on .net4. I found a few links that suggest using the useLegacyV2RuntimeActivationPolicy. There is another similar question answer to which suggests its fine, but following links make me think its better to recompile targeting .net4: "...Apps that were built for versions 2.0, 3.0, and 3.5 can all run on version 3.5, but they will not work on version 4 or later." - On MSDN "Some framework types have moved across assemblies between versions..." - In an SO answer "No idea. It depends on the application and which APIs it uses. There were breaking changes in .NET 4 and this application is likely hitting one..." - In an MSDN forum answer A: I mainly want to know the repercussions of using .net3.5 assemblies on .net4. In general, you need to set the runtime activation policy to force .NET 4. This means that your 3.5 assembly will be executed using the CLR 4 runtime, not the CLR 2 runtime. For most scenarios, things "just work". However, there are definitely edge cases where there could be problems, as there were some subtle changes (as you've linked) in the 4.0 runtime. In my experience, these issues are very rare, and things typically work flawlessly. I would recommend thorough testing of the 3.5 functionality if you're going to use it in a 4.0 application, however, just to verify that you're not hitting an edge case that is problematic.
{ "pile_set_name": "StackExchange" }
Q: Changing a chart's properties breaks after changing its location In the following code, it's possible to change a chart title or its location by themselves, but changing its title after changing its location doesn't work, as indicated by the standard error logging. According to What is error code 0x800A01A8 coming out of Excel ActiveX call?, 0x800a01a8 means "Object Required.", but I assume #{chart.ole_obj_help.name} indicates that an object exists. What's going wrong? Code is followed by logging. require "win32ole" class ExcelOutputter def initialize(workbook_filename) @workbook_filename = workbook_filename # Create an instance of the Excel application object @excel = WIN32OLE.new('Excel.Application') # Make Excel visible @excel.Visible = 1 # Add a new Workbook object @workbook = @excel.Workbooks.Add end def create_chart(title) # http://rubyonwindows.blogspot.com/2008/06/automating-excel-creating-charts.html chart = @workbook.Charts.Add # Select a worksheet for source data worksheet = @workbook.Worksheets("Sheet1") # Excel insists on having source data, even if it's empty. Picky, isn't it? chart.SetSourceData('Source' => worksheet.Range("$A$1:$B$6")) chart.HasTitle = true STDERR.puts "#{__method__}: Before renaming the freshly created #{chart.ole_obj_help.name}, the title is #{chart.ChartTitle.Characters.Text.inspect}" chart.ChartTitle.Characters.Text = title STDERR.puts "#{__method__}: The chart has been created, and is still a #{chart.ole_obj_help.name} and now has a title of #{chart.ChartTitle.Characters.Text.inspect}" chart end def change_chart_title(chart, new_title) STDERR.puts "#{__method__}: Apparently the chart object is still a #{chart.ole_obj_help.name}" old_title = chart.ChartTitle.Characters.Text chart.ChartTitle.Characters.Text = new_title STDERR.puts "#{__method__}: The chart object is still a #{chart.ole_obj_help.name} and has been renamed from #{old_title.inspect} to #{chart.ChartTitle.Characters.Text.inspect}" end def move_chart(chart, target_worksheet_name) xlLocationAsObject = 2 chart.Location("Where" => xlLocationAsObject, "Name" => target_worksheet_name) STDERR.puts "#{__method__}: The chart object is still a #{chart.ole_obj_help.name} and has been moved to #{target_worksheet_name.inspect}" end def write_to_file # Save the workbook @workbook.SaveAs(@workbook_filename) # Close the workbook @workbook.Close # Quit Excel @excel.Quit end def self.show_everything_works_if_you_do_not_change_a_moved_chart STDERR.puts "#{__method__}: Starting" excel_outputter = ExcelOutputter.new("chart_location_confusion.xlsx") chart = excel_outputter.create_chart("If you saw this it would mean change_chart_title never worked") excel_outputter.change_chart_title(chart, "Show that change_chart_title works") excel_outputter.move_chart(chart, "Sheet2") # Don't change the chart title after changing its location # excel_outputter.change_chart_title(chart, "If you saw this it would mean change_chart_title works after you called move_chart") another_chart = excel_outputter.create_chart("If you saw this it would mean change_chart_title never worked") excel_outputter.change_chart_title(another_chart, "Check that change_chart_title or move_chart isn't broken permanently") excel_outputter.move_chart(another_chart, "Sheet3") excel_outputter.write_to_file STDERR.puts "#{__method__}: Finishing" STDERR.puts("\n\n") end def self.try_renaming_after_moving_the_same_chart STDERR.puts "#{__method__}: Starting" excel_outputter = ExcelOutputter.new("chart_location_confusion.xlsx") chart = excel_outputter.create_chart("If you saw this it would mean change_chart_title never worked") excel_outputter.change_chart_title(chart, "change_chart_title works before you call move_chart") excel_outputter.move_chart(chart, "Sheet2") begin # This will raise an exception excel_outputter.change_chart_title(chart, "Will not get here") rescue STDERR.puts "#{__method__}: It didn't work" raise else STDERR.puts "#{__method__}: It worked after all!" end end end if __FILE__ == $0 ExcelOutputter.show_everything_works_if_you_do_not_change_a_moved_chart ExcelOutputter.try_renaming_after_moving_the_same_chart end produces show_everything_works_if_you_do_not_change_a_moved_chart: Starting create_chart: Before renaming the freshly created _Chart, the title is "" create_chart: The chart has been created, and is still a _Chart and now has a title of "If you saw this it would mean change_chart_title never worked" change_chart_title: Apparently the chart object is still a _Chart change_chart_title: The chart object is still a _Chart and has been renamed from "If you saw this it would mean change_chart_title never worked" to "Show that change_chart_title works" move_chart: The chart object is still a _Chart and has been moved to "Sheet2" create_chart: Before renaming the freshly created _Chart, the title is "" create_chart: The chart has been created, and is still a _Chart and now has a title of "If you saw this it would mean change_chart_title never worked" change_chart_title: Apparently the chart object is still a _Chart change_chart_title: The chart object is still a _Chart and has been renamed from "If you saw this it would mean change_chart_title never worked" to "Check that change_chart_title or move_chart isn't broken permanently" move_chart: The chart object is still a _Chart and has been moved to "Sheet3" show_everything_works_if_you_do_not_change_a_moved_chart: Finishing try_renaming_after_moving_the_same_chart: Starting create_chart: Before renaming the freshly created _Chart, the title is "" create_chart: The chart has been created, and is still a _Chart and now has a title of "If you saw this it would mean change_chart_title never worked" change_chart_title: Apparently the chart object is still a _Chart change_chart_title: The chart object is still a _Chart and has been renamed from "If you saw this it would mean change_chart_title never worked" to "change_chart_title works before you call move_chart" move_chart: The chart object is still a _Chart and has been moved to "Sheet2" change_chart_title: Apparently the chart object is still a _Chart try_renaming_after_moving_the_same_chart: It didn't work chart_location_confusion_replication.rb:30:in `method_missing': ChartTitle (WIN32OLERuntimeError) OLE error code:0 in <Unknown> <No Description> HRESULT error code:0x800a01a8 from chart_location_confusion_replication.rb:30:in `change_chart_title' from chart_location_confusion_replication.rb:75:in `try_renaming_after_moving_the_same_chart' from chart_location_confusion_replication.rb:87 Edit: If I change the chart creation to the following: def create_chart(title) # Select a worksheet for source data worksheet = @workbook.Worksheets("Sheet1") # http://rubyonwindows.blogspot.com/2008/06/automating-excel-creating-charts.html chart = worksheet.Shapes.AddChart.Chart # Excel insists on having source data, even if it's empty. Picky, isn't it? chart.SetSourceData('Source' => worksheet.Range("$A$1:$B$6")) chart.HasTitle = true STDERR.puts "#{__method__}: Before renaming the freshly created #{chart.ole_obj_help.name}, the title is #{chart.ChartTitle.Characters.Text.inspect}" chart.ChartTitle.Characters.Text = title STDERR.puts "#{__method__}: The chart has been created, and is still a #{chart.ole_obj_help.name} and now has a title of #{chart.ChartTitle.Characters.Text.inspect}" chart end and add excel_outputter.write_to_file to the end of try_renaming_after_moving_the_same_chart and turn off show_everything_works_if_you_do_not_change_a_moved_chart, then I get try_renaming_after_moving_the_same_chart: Starting create_chart: Before renaming the freshly created _Chart, the title is "" create_chart: The chart has been created, and is still a _Chart and now has a title of "If you saw this it would mean change_chart_title never worked" change_chart_title: Apparently the chart object is still a _Chart change_chart_title: The chart object is still a _Chart and has been renamed from "If you saw this it would mean change_chart_title never worked" to "change_chart_title works before you call move_chart" move_chart: The chart object is still a _Chart and has been moved to "Sheet2" change_chart_title: Apparently the chart object is still a _Chart change_chart_title: The chart object is still a _Chart and has been renamed from "change_chart_title works before you call move_chart" to "Will not get here" try_renaming_after_moving_the_same_chart: It worked after all! but when I view it in Excel, the chart has the title change_chart_title works before you call move_chart, rather than Will not get here. However, the following VBA works: Sub Tester3() Dim cht As Object Debug.Print "Start" Set cht = Sheet2.Shapes.AddChart.Chart Debug.Print TypeName(cht) 'Chart cht.SetSourceData Sheet1.Range("B4:C15") Debug.Print TypeName(cht) 'Chart cht.ChartTitle.Characters.Text = "Second title" cht.Location Where:=xlLocationAsObject, Name:="Sheet2" cht.ChartTitle.Characters.Text = "Third title" Debug.Print TypeName(cht) 'Chart Debug.Print cht.Name 'Sheet2 Chart 7 End Sub A: If I recall correctly there are some differences between chart sheets and charts embedded on worksheets. It may be that those differences are breaking your "chart" reference such that it no longer points to the "same" object after the move. A bit of VBA to show the same thing: Sub Tester() Dim cht As Object Set cht = ThisWorkbook.Charts.Add() cht.SetSourceData Sheet1.Range("B4:C15") Debug.Print TypeName(cht) 'Chart cht.Location Where:=xlLocationAsObject, Name:="Sheet1" Debug.Print TypeName(cht) 'Object Debug.Print cht.Name 'Error: object required End Sub Edit: moving an embedded chart to another sheet also doesn't work: Sub Tester2() Dim cht As Object Set cht = Sheet1.Shapes.AddChart.Chart cht.SetSourceData Sheet1.Range("B4:C15") Debug.Print TypeName(cht) 'Chart cht.Location Where:=xlLocationAsObject, Name:="Sheet2" Debug.Print TypeName(cht) 'Chart Debug.Print cht.Name 'Error: Method 'Name' of object _chart failed End Sub Is there some reason why you need to create the chart as a chart sheet and don't create it directly on the worksheet?
{ "pile_set_name": "StackExchange" }
Q: ExtJS 4.1: unload event I am working with ext js 4.1. I am developing an application that have to support IE9, the latest Firefox, the latest Chrome and Safari. I need to show an alert message when the user wants to leave the if there are some data that is pending to submit. I did the following using raw Javascript: window.onbeforeunload=function(){ if (Ext.getStore('LocalChangesStore')){ if (Ext.getStore('LocalChangesStore').getCount() > 0) { return 'Your changes are be lost.'; } } }; I am wondering if that would be possible with ext js. I saw the following function: app.js: EventManager.onWindowUnload( function(){ if (Ext.getStore('LocalChangesStore')){ if (Ext.getStore('LocalChangesStore').getCount() > 0) { return 'Your changes are be lost.'; } } }, this ); but it did not work. Can somebody let me know which would be the best approach to solve this issue? A: The onWindowUnload method attachs a function to the unload event but what you need is attach a function to the beforeunload event. Try this please Ext.EventManager.on(window, 'beforeunload', function() { return 'Your changes are be lost.'; }); Good luck.
{ "pile_set_name": "StackExchange" }
Q: Controlling X-Axis Marks on Date Data Charts c# I have records in the database and a chart where I can preview them. The graph is data x Voltage in volts. When I have few records in the table the graph shows exactly the date recorded in the bank on the X axis, but over the time I add more records, the graph grows and stops marking all the date records where there was a change in the voltage. I am putting a picture of how the chart is: This chart is taking 50 entries from my bank with different times and voltage values. I would like a way to improve and be able to better control the X-axis points, perhaps making them appear every 10 minutes for example. Below is the code that generates the graphics: SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringSQL"].ConnectionString); con.Open(); SqlCommand cmd = new SqlCommand("SELECT Log.ValorEntrada, Log.DataHoraEvento, Log.NumeroEntrada FROM Log INNER JOIN Equipamento ON Log.IDEquipamento = Equipamento.IDEquipamento INNER JOIN EntradaEstado ON Equipamento.IDEquipamento = EntradaEstado.IDEquipamento INNER JOIN Entrada ON EntradaEstado.IDEntrada = Entrada.IDEntrada WHERE Log.NumeroEntrada = N'" + descricao.SelectedItem.Value + "' AND Log.ValorEntrada IS NOT NULL AND DATEDIFF(day, Log.DataHoraEvento, GETDATE()) = 1 AND EntradaEstado.IDEquipamento = N'" + equip.Text + "' AND Entrada.Descricao = N'" + descricao.SelectedItem.Text + "' ORDER BY DataHoraEvento ASC"); cmd.Connection = con; SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); if (dt.Rows.Count > 0) { Chart2.DataSource = dt; if (descricao.SelectedItem.Text == "Corrente da bomba de graxa") { Chart2.ChartAreas["ChartArea1"].AxisY.Title = "Corrente (A)"; } else { Chart2.ChartAreas["ChartArea1"].AxisY.Title = "Tensão (V)"; } Title title = Chart2.Titles.Add("Gráfico do dia: " + DateTime.Now.AddDays(-1).ToString("dd/MM/yyyy")); title.ForeColor = System.Drawing.Color.DarkBlue; title.Font = new System.Drawing.Font("Arial", 12, System.Drawing.FontStyle.Bold); Chart2.ChartAreas["ChartArea1"].AxisX.Title = "Hora"; Chart2.ChartAreas["ChartArea1"].AxisX.LabelStyle.Format = "HH:mm:ss"; Chart2.ChartAreas["ChartArea1"].AxisX.MajorGrid.LineColor = System.Drawing.Color.DarkGray; Chart2.ChartAreas["ChartArea1"].AxisX.MajorGrid.LineDashStyle = ChartDashStyle.Dot; Chart2.ChartAreas["ChartArea1"].AxisY.MajorGrid.LineColor = System.Drawing.Color.DarkGray; Chart2.ChartAreas["ChartArea1"].AxisY.MajorGrid.LineDashStyle = ChartDashStyle.Dot; Chart2.Series["Series1"].XValueType = ChartValueType.DateTime; Chart2.Series["Series1"].BorderWidth = 2; Chart2.Series["Series1"].XValueMember = "DataHoraEvento"; Chart2.Series["Series1"].YValueMembers = "ValorEntrada"; Chart2.Series["Series1"].IsXValueIndexed = true; Chart2.Width = 1200; Chart2.Height = 400; Chart2.DataBind(); con.Close(); A: Have you tried to alter the label style on the X-axis? There are quite a few options, perhaps something like Chart2.ChartAreas["ChartArea1"].AxisX.IsLabelAutoFit = false; Chart2.ChartAreas["ChartArea1"].AxisX.LabelStyle = new LabelStyle() { IntervalType = DateTimeIntervalType.Minutes, Interval = 10, Format = "HH:mm:ss"}; can point you in the right direction.
{ "pile_set_name": "StackExchange" }
Q: Line-integration along a parametrized curve Exercise: $\int_{\alpha}{( x^2 + y^2 )}d\alpha$ where $\alpha$ is the curve parameterized by $x=a(\cos(t)+ t\sin(t))$, $y=a(\sin(t)-t\cos(t))$ (correction by DonAntonio's) with $t \in [0,2\pi]$ where $a>0$ Proof $M=\int_{\alpha}{( x^2 + y^2 )}d\alpha$ $M=\int_{0}^{2\pi}{a^2 \cos(t)^2 + a^2 t^2\sin(t)^2 + a^2 \sin(t)^2 + a^2 t^2\cos(t)^2}$ $dt$ ??? (it's that I have) Solution $M=16\pi^2(1+2\pi^2)$ Have some idea how to solve this integral of line, some hint to find the solution??? Example If the circumference is $x^2+y^2=ax$ in the form $(x-a/2)^2 + y^2 = a^2/4$ where $C$ is parameterized by $x=(a/2)+(a/2)\cos(t)$ and $y=(a/2)\sin(t)$ with $(0\leq t\leq 2\pi)$ That mode $\sigma'(t)=(-a\sin(t/2),a\cos(t/2))$ then $|\sigma'(t)|=a/2$ Then $M=\int_{C}\sqrt{x^2+y^2}ds=\int_{0}^{2\pi}\sqrt{a^2/2 (1+\cos(t)a/2)}dt$ $...$ $M=\frac{a^2}{2}\cdot 2(1-\cos(t))^{1/2}|_{0}^{2\pi}=0$ A: I guess that there is a typo (see also DonAntonio's comment) and the parametrized curve $\alpha$ should be $$x:=a(\cos(t)+t\sin(t)),\quad y=a(\sin(t)-t\cos(t))$$ for $t\in [0,2\pi]$. Then $$x^2+y^2=a^2(1+t^2)\quad\mbox{and}\quad ds=\sqrt{(x'(t))^2+(y'(t))^2}=at.$$ Therefore $$\int_{\alpha}{( x^2 + y^2 )}ds=a^3\int_{0}^{2\pi}(1+t^2)t dt=2a^3\pi^2(1+2\pi^2).$$
{ "pile_set_name": "StackExchange" }
Q: Java application that reads in a csv file and compares data in each row I am fairly new to programming and have just been set the task of creating an application that will read in a .csv file name from a user input before then running a series of tests. Ultimately the program needs to compare each row (each row in the csv file represents one router) and return which routers need a patch based on set criteria. The format of the CSV file will look like this with the headings 'Hostname', 'IP Address', 'Patched?', Os Version, and Notes which do not necessarily need to be included - A.example.COM, 1.1.1.1, NO, 11, Faulty fans b.example.com, 1.1.1.2, no, 13, Behind other routers C.EXAMPLE.COM, 1.1.1.3, no, 12.1 d.example.com, 1.1.1.4, yes, 14 c.example.com, 1.1.1.5, no, 12, Case a bit loose e.example.com, 1.1.1.6, no, 12.3 f.example.com, 1.1.1.7, No, 12.2 g.example.com, 1.1.1.6, no, 15 So the program needs to return the name of any routers that do not share the same Hostname and IP Address as any other router, has a current OS version of 12 or higher, or has not already been patched. So far I have tried to read in each individual line as a Java object and compare from there however I have had no success. Any suggestions on a good way to go about making this program work would be greatly appreciated, thanks. A: Here are my suggestions: Create a class (let's call it "Router") that contains "hostName" - String, "ipAddresss" - String, "patched" - Boolean, "osVersion" - Double and "notes" - String. Add related setters and getters. Create a list "routers" that contains a list of "Router" classes and initialize it to empty. Create a method that takes a Router object as the parameter. First compare the "osVersion". Then iterates through the "routers" list. During the iteration compare the given Router object against each Router object you encounter. If there are duplicates don't do anything, otherwise add this object to the list after the iteration. Iterate through each line of the CSV file and parse each row into "Router" object and invoke the method you created from #3. The "routers" should contain the final result after the program finishes.
{ "pile_set_name": "StackExchange" }
Q: site navigation in ASP .NET I am creating simple website in ASP .NET c# for social network, and my question is if I am having a page for groups and for every time user clicks on a group called x for example it should be redirected to the page of group x, how I can do this? (sorry if I can't explain but am still newbie with ASP .NET) A: I believe you are referring to a hyper link <a href="group?id=123">My Group</a> you will most likely need to change the url and stuff, but basically it's just a link.
{ "pile_set_name": "StackExchange" }
Q: Detect â in a string I'm trying to detect the character â in a string in Objective C and can't seem to get it to work. It's displaying a bullet point when it's finally displayed on screen, so maybe that's why I can't detect it? In iOS 10 these bullet points display larger than they should, so I need to find the range of each of these characters and make them a few sizes smaller. I've tried the following: [inputString contains:@"â"] [inputString contains:@"•"] [inputString contains:@"\u00b7"] [inputString contains:@"\u2022"] The one that interests me the most is when I copy and paste exactly from the API response: [inputString contains:@"â "]. There's actually 4 or 5 spaces in that string, but they get truncated when pasting from the JSON I get back -- I'm not sure why but I feel like that has to do with why I can't recognize the string contains that character. Any ideas on how to correctly deal with this character? Edit: Few more details, here's the string that gets sent back from API: â All of your exclusive deals in one place\nâ More deals matched specifically to you\nâ Get alerts to know when new deals are available or your saved deals are expiring" I noticed something weird as well, when I edit the response and add in more of those a's with a hat, they get moved into bullet points, however when I add them into the string in code, they are displayed as simply bullet points. Maybe they're being encoded somehow? Although I don't see anywhere in our code where that could be happening, so I'm a little confused as to what's going on here. Edit 2: Here's a hexdump of the line, this is probably more useful to some of you than it is to me: 000026c0 6e 74 65 6e 74 22 3a 20 22 e2 97 8f 20 41 6c 6c |ntent": "... All| 000026d0 20 6f 66 20 79 6f 75 72 20 65 78 63 6c 75 73 69 | of your exclusi| 000026e0 76 65 20 64 65 61 6c 73 20 69 6e 20 6f 6e 65 20 |ve deals in one | 000026f0 70 6c 61 63 65 5c 6e e2 97 8f 20 4d 6f 72 65 20 |place\n... More | 00002700 64 65 61 6c 73 20 6d 61 74 63 68 65 64 20 73 70 |deals matched sp| 00002710 65 63 69 66 69 63 61 6c 6c 79 20 74 6f 20 79 6f |ecifically to yo| 00002720 75 5c 6e e2 97 8f 20 47 65 74 20 61 6c 65 72 74 |u\n... Get alert| 00002730 73 20 74 6f 20 6b 6e 6f 77 20 77 68 65 6e 20 6e |s to know when n| 00002740 65 77 20 64 65 61 6c 73 20 61 72 65 20 61 76 61 |ew deals are ava| 00002750 69 6c 61 62 6c 65 20 6f 72 20 79 6f 75 72 20 73 |ilable or your s| 00002760 61 76 65 64 20 64 65 61 6c 73 20 61 72 65 20 65 |aved deals are e| 00002770 78 70 69 72 69 6e 67 22 2c 0d 0a 20 20 20 20 22 |xpiring",.. "| A: The bytes e2 97 8f in your dump is the UTF8 encoding of U+25CF, BLACK CIRCLE. When interpreted as ISO-8859 or Windows-1252 e2 is â (a circumflex), 97 is an em dash, and 8f is unused. This indicates the JSON itself is UTF8 and somewhere is being interpreted differently, probably as one of the above encodings. You need to check both in your code and in the full server response (for an example of the latter causing an issue see the question JSON character encoding).
{ "pile_set_name": "StackExchange" }
Q: Sum of child levels total in a Hierarchy I need to have each level be the sum of all children (in the hierarchy) in addition to any values set against that value itself for the Budget and Revised Budget columns. I've included a simplified version of my table structure and some sample data to illustrate what is currently being produced and what I'd like to produce. Sample table: CREATE TABLE Item (ID INT, ParentItemID INT NULL, ItemNo nvarchar(10), ItemName nvarchar(max), Budget decimal(18, 4), RevisedBudget decimal(18, 4)); Sample data: INSERT INTO Item (ID, ParentItemID, ItemNo, ItemName, Budget, RevisedBudget) VALUES (1, NULL, N'10.01', N'Master Bob', 0.00, 17.00); INSERT INTO Item (ID, ParentItemID, ItemNo, ItemName, Budget, RevisedBudget) VALUES (2, 1, N'10.01.01', N'Bob 1', 0.00, 0.00); INSERT INTO Item (ID, ParentItemID, ItemNo, ItemName, Budget, RevisedBudget) VALUES (3, 2, N'10.01.02', N'Bob 2', 2.00, 2.00); INSERT INTO Item (ID, ParentItemID, ItemNo, ItemName, Budget, RevisedBudget) VALUES (4, 2, N'10.02.01', N'Bob 1.1', 1.00, 1.00); CTE SQL to generate Hierarchy: WITH HierarchicalCTE AS ( SELECT ID, ParentItemID, ItemNo, ItemName, Budget, RevisedBudget, 0 AS LEVEL FROM Item WHERE Item.ParentItemID IS NULL UNION ALL SELECT i.ID, i.ParentItemID, i.ItemNo, i.ItemName, i.Budget, i.RevisedBudget, cte.LEVEL + 1 FROM HierarchicalCTE cte INNER JOIN Item i ON i.ParentItemID = cte.ID ) So, currently my CTE produces (simplified): ID: 1, Level: 0, Budget: 0, RevisedBudget: 17 ID: 2, Level: 1, Budget: 0, RevisedBudget: 0 ID: 3, Level: 2, Budget: 2, RevisedBudget: 2 ID: 4, Level: 2, Budget: 1, RevisedBudget: 1 And I want the results to produce: ID: 1, Level: 0, Budget: 3, RevisedBudget: 20 ID: 2, Level: 1, Budget: 3, RevisedBudget: 3 ID: 3, Level: 2, Budget: 2, RevisedBudget: 2 ID: 4, Level: 2, Budget: 1, RevisedBudget: 1 Hopefully that is easy enough to understand. Link to SQLFiddle with table and initial CTE: http://sqlfiddle.com/#!3/66f8b/4/0 Please note, any proposed solution will need to work in SQL Server 2008R2. A: Your ItemNo appears to have the item hierarchy embedded in it. However, the first value should be '10' rather than '10.01'. If this were fixed, the following query would work: select i.ID, i.ParentItemID, i.ItemNo, i.ItemName, sum(isum.Budget) as Budget, sum(isum.RevisedBudget) as RevisedBudget from item i left outer join item isum on isum.ItemNo like i.ItemNo+'%' group by i.ID, i.ParentItemID, i.ItemNo, i.ItemName; EDIT: To do this as a recursive CTE requires a somewhat different approach. The idea of the recursion is to generate a separate row for each possible value for an item (that is, everything below it), and then to aggregate the values together. The following does what you need, except it puts the levels in the reverse order (I don't know if that is a real problem): WITH HierarchicalCTE AS ( SELECT ID, ParentItemID, ItemNo, ItemName, Budget, RevisedBudget, 0 AS LEVEL FROM Item i UNION ALL SELECT i.ID, i.ParentItemID, i.ItemNo, i.ItemName, cte.Budget, cte.RevisedBudget, cte.LEVEL + 1 FROM HierarchicalCTE cte join Item i ON i.ID = cte.ParentItemID ) select ID, ParentItemID, ItemNo, ItemName, sum(Budget) as Budget, sum(RevisedBudget) as RevisedBudget, max(level) from HierarchicalCTE group by ID, ParentItemID, ItemNo, ItemName;
{ "pile_set_name": "StackExchange" }
Q: Prove or disprove the converse of a proposition of test of convergence of series We can see the fact that: If a series $\sum_{n=1}^{\infty} a_{n}$ converges then: $\displaystyle \lim_{n \rightarrow \infty} (a_n + a_{n+1} +···+ a_{n+r} )=0 $ This is my proof: $\displaystyle \lim_{n \rightarrow \infty} (a_n + a_{n+1} +···+ a_{n+r} )$ $=\displaystyle \lim_{n \rightarrow \infty} a_n + \displaystyle \lim_{n \rightarrow \infty}a_{n+1} +···+\displaystyle \lim_{n \rightarrow \infty} a_{n+r} $ $=0+0+...+0=0$ Is it correct? Also I want to ask:Does the converse of the implication holds: That it: Does $\displaystyle \lim_{n \rightarrow \infty} (a_n + a_{n+1} +···+ a_{n+r} )=0 $ imply the series $\sum_{n=1}^{\infty} a_{n}$ convergent? Whether it is true or not. I am searching for a proof and a justification. Could someone help to prove or disprove the statement? Thanks so much ! A: As long as $r$ is finite, I believe your answer is correct. The converse is not true. Let's, for example, let $a_n = 1/n.$
{ "pile_set_name": "StackExchange" }
Q: Why householders are advised not to worship fierce forms of Kali? Why are householders advised not to venerate fierce forms of Kali? I was told by those who follow the shakti tradition that householders should not honor the angry forms of Kali. Why is this? A: That is not true. There are no such fierce forms of Goddess KAli. She is fierce apparently but at the same time endowed with motherly affection. So, she can perfectly worshiped by everyone irrespective of whether one is a householder or a sannyAsi. She is a perfect deity for the householders in fact. I have done a preliminary study of the Dasha MahAvidyAs and still doing so. She is the first MahAvidya in the group. And, she does not have Murtibhedas (that is different forms of the one principle Deity). So, there are no such classifications such as- pleasant forms KAli, fierce forms of KAli etc. The second MahAvidyA, Goddess TArA, however has Murtibhedas. But all her forms are Bhoga-Moksha pradA and can be worshiped by all. TArA chogrA mahogrAcha vajrA nilA sarswati | KAmeswari bhadrakAli ityashtau tArini smritAh || ..... TArA, Ugra, MahAugra, Vajra, NilA, Saraswati, KAmeswari, BhadrakAli; These are the eight Murtibhedas of Goddess TArA. Nila Tantram. Now, apparently Goddess KAli will seem as terrifying but that will be only for persons who are at their lowest level of spiritual evolution. The scriptures say that she is known as MahAkAlki since she devours even MahAkAla, who himself devours everything at the time of dissolution. Tava rupam mahAkalo jagat sanhAra kArakaha | KalanAt sarva bhutAnAm mahAkAlah prakirtitAh || MahAkAlasya kalanAt tvamAdyA kAlikA parA ||.. ........ [Lord Sadashiva says to Sri AdyA] Your form, MahAkAla, devours everything at the time of dissolution of the universe (samhAra). Since he devours (kalan) everything and every being during samhAra he is known as MahAkAla. And, since you devour even MahAkala, you are known as the primordial (AdyA) and supreme KAlikA. MahAnirvAna Tantram 4-30,31. So, because of this terrible samhAra murti, she is bound to terrify the weak minded. But for the higher level sadhAkas, she is appears as the affectionate Mother. Her Dhyana Sloka that's why mentions her both as terrible (viz-KAli karAla VadanA) and at the same time as the affectionate Mother ( viz-Hasnmukhim, SmerAnana saroruhAm; having a smiling, affectionate and pleasant face). Now, coming to the overwhelming importance of KAli worship in Kali Yuga. ShadAmneshu deveshi bhuyashyah sashti devatAh | TAsu kAshchit kritayuge tretAyAm kAshchidiritAh || DwApare phaladAh kAshchit kalau kAshchit phalapradAh | Chaturyugeshu phaladA dasha vidyA mayeritAh || TAsu tisro vishishyante kAli tArA cha sundari | Tisrishvapi shive tAsu kalau kAli vishishyate || ............. In the six amnAyas (Simply put, AmnAya is the original source of all Tantras spoken by Lord Shiva, from his six faces came six AmnAyas which is the source of all Tantras and Agamas) there are numerous deities Among them some gives fruits in Satya Yuga while some others give fruits in Kali Yuga. The Deities who give fruits in all the four Yugas are the Dasha MahAvidyAs. Among the MahAvidyA deities, KAli, TArA and Tripura Sundari are specially significant. And among these three, KAli is particularly effective in Kali Yuga. MahAkAla Samhita's Anusmriti prakalpa. So, needless to say, such an important deity can not have such restrictions over its worship. In my opinion, your friends must have talked about another MahAvidya, the 6th one, Goddess ChinnamastA or Prachanda ChandikA. The scriptures do say that there is no difference between KAli and ChinnamastA, so your ShAkta friends must have meant ChinnamastA as the "fierce form of KAli". YathA chinnA tathA kAli tathaiva sundariparA | Tathaiva tArA samdishta chaturanAm nahi bhinnatA || ......... Who is Chinnamsta, is KAli, she is [Tripura] Sundari and she is TArA as well. There is no difference between the four Deities Shakti Samgama Tantra 4-51. Now, as far as Goddess ChinnamastA is concerned, there are certainly some serious apprehensions. The scriptures clearly say that she is an extremely fierce deity and that there is no deity who is more fierce than her. NAtah paratarA kAchidugrA devi bhavisyati | TasmAd sattairmurjaina grAhyeyam kathanchana || Siddhirva mrityurapi vA dwayorekataram bhavet || ... There is no deity which is more fierce than ChinnamastA. That's why faint hearted and weak person should not receive her mantra. In her sAdhana either Siddhi is achieved or Mrityu (death). ViswasAra Tantram verse quoted in PurashcharjAnava's Taranga 9. Yet another verse depicting the terrible nature of Goddess is the following one: PrachandachandikAmevadhyAtvA yastu na pujayet | Sadyastasya ShirashchitvA devi pivati shonitam || ..... One who worships Chinnamasta or PrachandachndikA without her meditative verse, Devi cuts his head off. The significance of this verse is that, while other deities can still be worshiped without employing their DhyAna Slokas, ChinnamastA simply can not be. Such is her fierce nature. So, a ritualistic worship of Goddess ChinnamstA is not safe to practise in homes on ones own without the guidance of an able Guru. And, as far as Devi's DhyAna Slokas are concerned, there are indeed many of them. And more importantly, there are separate DhyAnas for Yatis (sannyAsi) and for Grihastas (householders). The DhyAna for sannyAsis starts like this: SvanAbhounirajam dhyAyet bhanu mandala sannibham | Yonichakra samAyuktam gunatritraya samgitam || Tatra madhye mahAdevim chinnamastAm smared yatihi || And, the DhyAna for the householders starts like this: PratyAlirapadAm sadiava dadhatim chinnam sirah katrikAm.... And, as far as goddess MahAkAli is concerned, there are no such restrictions. In Bengal, plenty of homes even have MahAkAli Temples within the premises of their homes.
{ "pile_set_name": "StackExchange" }
Q: Do I lose the anonymity of a VPN if they open a port for me? I currently use a VPN supplier that does not allow for opening ports. They argue that I lose the whole point of a VPN and the anonymity by doing this. I can't see how and they don't seem to be able to explain how this would work for me. Shouldn't I still be protected behind the NAT of the VPN? A: Opening a unique port just for you? Yes, you lose anonymity, even with NAT, because now that traffic on that unique port unique identifies your traffic. One of the benefits of a VPN is that your traffic gets co-mingled with so much other traffic that it is difficult to uniquely identify users. Your proposal eliminates this benefit.
{ "pile_set_name": "StackExchange" }
Q: Testing Private Methods Not Working Here is my Test Class; <?php namespace stats\Test; use stats\Baseball; class BaseballTest extends \PHPUnit_Framework_TestCase { public function setUp() { $this->instance = new Baseball(); } public function tearDown() { unset($this->instance); } public function testOps() { $obp = .363; $slg = .469; $ops = $this->instance->calc_ops($obp, $slg); //line 23 $expectedops = $obp + $slg; $this->assertEquals($expectedops, $ops); } } And this is my Baseball Class; <?php namespace stats; class Baseball { private function calc_ops($slg,$obp) { return $slg + $obp; } } And I keep getting this error when I run my tests; Fatal error: Call to private method stats\Baseball::calc_ops() from context 'stats\Test\BaseballTest' in /media/sf_sandbox/phpunit/stats/Test/BaseballTest.php on line 23 This is only a tutorial I am following.. But it's not working so it's frustrating because I am following it exactly. A: You can't test private method, you can use a workaround and invoke it via reflection as described in this article. This is a working example based on the article: class BaseballTest extends \PHPUnit_Framework_TestCase { public function setUp() { $this->instance = new Baseball(); } public function tearDown() { unset($this->instance); } public function testOps() { $obp = .363; $slg = .469; // $ops = $this->instance->calc_ops($obp, $slg); //line 23 $ops = $this->invokeMethod($this->instance, 'calc_ops', array($obp, $slg)); $expectedops = $obp + $slg; $this->assertEquals($expectedops, $ops); } /** * Call protected/private method of a class. * * @param object &$object Instantiated object that we will run method on. * @param string $methodName Method name to call * @param array $parameters Array of parameters to pass into method. * * @return mixed Method return. */ public function invokeMethod(&$object, $methodName, array $parameters = array()) { $reflection = new \ReflectionClass(get_class($object)); $method = $reflection->getMethod($methodName); $method->setAccessible(true); return $method->invokeArgs($object, $parameters); }
{ "pile_set_name": "StackExchange" }
Q: how to globally set timeout in nhibernate I periodically receive the following exception. System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. I've added the following to my criteria to increase the timeout time. .SetTimeout(180) 1) Is there a way to add this to my nhibernate configuration so that 180 is the default time? 2) what are the consequences to increase the timeout? Will this increase or decrease the likely hood of deadlocks? A: command_timeout - Specify the default timeout of IDbCommands generated by NHibernate Taken from Table 3.1. NHibernate ADO.NET Properties in http://www.nhforge.org/doc/nh/en/index.html#configuration-hibernatejdbc
{ "pile_set_name": "StackExchange" }
Q: Delete clicked item in jQuery and PHP? I just have a quick question how do I delete the item I just clicked? I don't have a great way of tracking it and I'm at my last resort way right now (which is what I'm posting) which deletes everything in the list. PHP/HTML/jQuery: <div class="image-list"> <?php $count = 1; if ($hotelId) { foreach(glob($hotelDir) as $filename=>$hotelvalue){ echo '<li id="del'.$count.'" class="image-list"><a class="enlargeUser" href="'.$hotelvalue.'"><img class="imageListMain" src="'.$hotelvalue.'" width="50px" height="50px"/><p class="filename">' . basename($hotelvalue) . '</p></a> <a class="btn btn-mini btn-primary image-list" style="width: 18px;margin-top: -35px;position: relative\9;top: -25px\9;border-radius: 100%;-moz-border-radius: 100%;-o-border-radius: 100%;-webkit-border-radius: 100%;margin-left:330px;" id="del'.$count.'" value="Delete"><i class="icon-remove-circle icon-2" style="margin-left:-3px;"></i></a></li>' . "\n" . "<br>"; $count++; } }else{} ?> </div> </div> <script> $('div.image-list li a.image-list').live('click', function() { bootbox.confirm("Are you sure you want to delete this image?", "Cancel", "Confirm", function(result) { if (result) { $('ul.image-list li a.image-list').closest('li').fadeOut(); $.post('assets/php/deletefile.php'); } }); }); </script> Here is the delete information (right now it is static PHP that only deletes the first file I don't have another way of doing this yet): <?php session_start(); $files = glob("upload/" . $_SESSION['curHotelId'] . "/" . '*.*'); if(is_file($files[0])) @unlink($files[0]); ?> UPDATE: Thanks to Karl's answer I got a better idea of what I'm doing, but I still cannot get these to remove. I don't know why. They stay blank and act as if they don't even exist or the button does not work. Here is my updated PHP/HTML/jQuery: <div class="image-list"> <?php $count = 1; if ($hotelId) { foreach(glob($hotelDir) as $filename=>$hotelvalue){ echo '<li data-filename="' . basename($hotelvalue) . '" id="del'.$count.'" class="image-list"><a class="enlargeUser" href="'.$hotelvalue.'"><img class="imageListMain" data-filename="' . basename($hotelvalue) . '" src="'.$hotelvalue.'" width="50px" height="50px"/><p class="filename">' . basename($hotelvalue) . '</p></a> <a data-filename="' . basename($hotelvalue) . '" class="btn btn-mini btn-primary image-list" style="width: 18px;margin-top: -35px;position: relative\9;top: -25px\9;border-radius: 100%;-moz-border-radius: 100%;-o-border-radius: 100%;-webkit-border-radius: 100%;margin-left:330px;" id="del'.$count.'" value="Delete"><i class="icon-remove-circle icon-2" style="margin-left:-3px;"></i></a></li>' . "\n" . "<br>"; $count++; } }else{} ?> </div> </div> <script> $('li.image-list a.image-list').click( function () { var filename = $(this).attr('data-filename'); $(this).remove(); $.get('assets/php/deletefile.php?filename=' + filename).done( function() { // it succeeded }).fail( function (){ // it failed }); }); }); </script> And the PHP was updated too: <?php session_start(); $filename = $_get['filename']; $files = glob("upload/" . $_SESSION['curHotelId'] . "/" . $filename); if(is_file($files)) @unlink($files); ?> HOPEFULLY FINAL UPDATE: I'm so close, I just wanna throw everything I love out a window. So here is where I'm having an issue. It isn't deleting the images when the code executes so here is PHP: ALL OF THIS CODE WORKS. C: Thank you everyone that helped! <?php session_start(); $file = $_POST['filename']; $selHotelId = $_SESSION['curHotelId']; $files = "upload/" . $selHotelId . "/" . $file; unlink($files); ?> jQuery: $(document).ready(function(){ $("#imageClick").live("click", "li.image-list a.image-list", function () { var _clicked = $(this); var _filename = _clicked.attr('data-filename'); _clicked.parents("li.image-list").fadeOut(function(){ $(this).empty().remove(); }); $.post('assets/php/deletefile.php', {filename: _filename}).done( function(data) { bootbox.alert('File has been deleted!'); }).fail( function (error){ bootbox.alert('There has been an error. Contact admin.'); }); }); }); A: There were still a few issues in your updated code. I've made some changes, and pasted in the code below. I've changed the method to $.post(), so your PHP file will need to access the parameter as $_POST['filename']. A couple issues I noticed, you had more than one element with the same id attribute. I removed the redundant data-filename attributes from elements that didn't need them. I placed your jQuery inside a $(document).ready() in order to make sure that nothing was called until all DOM elements had been loaded. I also used the .on method for binding the event...just in case you ever dynamically add more li elements with the a.image-list element. This way you are binding the event to an element that will always be there, and catching it on the a.image-list. (I might be explaining that incorrectly...it's late). Hope this helps. <ul class="image-list"> <?php $count = 1; if ($hotelId) { foreach(glob($hotelDir) as $filename=>$hotelvalue){ echo '<li id="del'.$count.'" class="image-list"><a class="enlargeUser" href="'.$hotelvalue.'"><img class="imageListMain" src="'.$hotelvalue.'" width="50px" height="50px"/><p class="filename">' . basename($hotelvalue) . '</p></a> <a class="btn btn-mini btn-primary image-list" style="width: 18px;margin-top: -35px;position: relative\9;top: -25px\9;border-radius: 100%;-moz-border-radius: 100%;-o-border-radius: 100%;-webkit-border-radius: 100%;margin-left:330px;" title="Delete" data-filename="' . basename($hotelvalue) . '" ><i class="icon-remove-circle icon-2" style="margin-left:-3px;"></i></a></li>' . "\n" . "<br>"; $count++; } } ?> </ul> <script> $(document).ready(function(){ $("ul.image-list").on("click", "li.image-list a.image-list", function () { var _clicked = $(this); var _filename = _clicked.attr('data-filename'); _clicked.parents("li.image-list").fadeOut(function(){ $(this).empty().remove(); }); $.post('assets/php/deletefile.php', {filename: _filename}).done( function(data) { // it succeeded }).fail( function (error){ // it failed }); }); }) </script> UPDATE: I had a typo in my code...not sure you caught it. var _filename = clicked.attr('data-filename'); SHOULD BE... var _filename = _clicked.attr('data-filename'); My apologies. To see if you are hitting your PHP file, you can do something simple like this... <?php $data["response"] = $_POST['filename']; echo json_encode($data); ?> And then modify your .done method to look like this... $.post('assets/php/deletefile.php', {filename: _filename}).done( function(data) { // it succeeded console.log(data); }).fail( function (error){ // it failed });
{ "pile_set_name": "StackExchange" }
Q: Haven't got revised employment yet I have already got employment contract via email. But it is just draft only. So, I discussed with my employer everything I wanna know about my salary and benefits etc via email only. My employer said he will send revised contract soon. It's almost one week ago and I haven't received any revised contract yet. Is it safe to have all these discussion via email only, even if they haven't provided the revised contract yet? Shall I proceed to resign without receiving revised contract? I am just worried that after I resign from current job, they may not revise accordingly what we discussed. A: Don't resign before you have a written contract, ink on paper. Email discussions are just that, discussions. In your position, you want to (friendly) remind the hiring person to finalize the contract. Call them, ask them about where the hangup is and if they need to clarify more things with you. Remind them that you won't resign your current position without a valid, binding contract. Even if you hear something along the line "You're fine, just quit your job, we'll hash it out don't wait for the contract" remain firm. The hiring person knows it's the professional thing to do, even if they pretend otherwise. There are possible reasons that you don't have your contract yet: They are interviewing someone else and have not totally committed to you, but won't tell you The funds or the project your new position hinges on is stalled, they are waiting for this to clear before committing By far, FAR the most likely reason: They simply haven't gotten around to finalizing the contract But the first two options should be reason enough for you to wait for the proper contract.
{ "pile_set_name": "StackExchange" }
Q: Params url do not execute get method form server I have very strange problem. I have component ProductListItemsComponent, In ngOnInit I execute the method getCategoryFromServer and getProductList(). This is look like: ngOnInit() { this.productsService.getCategoryFromServer(); this.getProductList(); } Method getCategoryFromServer is in my service ProductsService : getCategoryFromServer() { this.dataStorageServiceServiceta.getCategory().subscribe((category: CategoryModel[]) => { this.categoryModule = category; this.cateogoryChange.next(this.categoryModule.slice()) }) } Method getProductList() in my component and look like this: getProductList() { this.subscription = this.route.params .subscribe((params: Params) => { this.categoryName = params['category']; this.singleProducts = this.productsService.getListOfProduct(this.categoryName); }) } Problem is because start executing getCategoryFromServer and skip execution, and executed getProductList and after that execute getCategoryFromServer. But I need to first execute getCategoryFromServer and after that getCategoryFromServer. A: It seems you're talking about the async of observables here. An easy solution for this behavior would be to wrap your ProductsService call getCategoryFromServer() in a Promise. getCategoryFromServer(): Promise<CategoryModel[]> { return new Promise((resolve, reject) => { this.dataStorageServiceServiceta.getCategory().subscribe( (category: CategoryModel[]) => { this.categoryModule = category; this.cateogoryChange.next(this.categoryModule.slice()); resolve(this.categoryModule.slice()); }, (error) => reject(error) ); }); } Here you see I've wrapped our original call in a promise, now you can also see if the subscribe was successful we call the resolver and pass back the data (you don't have to do this, you can pass nothing back and things will work the same) As well I've added error handling in your subscribe to reject the promise if something happens in your subscribe. To use this in your ngInit it would look something like this now. ngOnInit() { this.getCategoryFromServer().then((cat: CategoryModel[]) => { this.getProductList(); }).catch( (reason: any) => { // error handling here }); } Now you've successfully made a way to know that your async calls have finished and to run your getProductList() method.
{ "pile_set_name": "StackExchange" }
Q: Postfix/Dovecot Issues receiving Mail I am having an issue with PostFix and Dovecot. I followed this guide: https://github.com/opensolutions/ViMbAdmin/wiki/Mail-System-Install-on-Ubuntu and when mail is sent into the server, this is in the mail.log Oct 26 12:40:11 vps31465 postfix/smtpd[13551]: connect from nm3-vm2.bt.bullet.mail.ir2.yahoo.com[212.82.99.122] Oct 26 12:40:11 vps31465 postfix/smtpd[13551]: warning: SASL: Connect to private/dovecot-auth failed: No such file or directory Oct 26 12:40:11 vps31465 postfix/smtpd[13551]: fatal: no SASL authentication mechanisms Oct 26 12:40:12 vps31465 postfix/master[13383]: warning: process /usr/lib/postfix/smtpd pid 13551 exit status 1 Oct 26 12:40:12 vps31465 postfix/master[13383]: warning: /usr/lib/postfix/smtpd: bad command startup -- throttling This is my output from postfix -n: alias_database = hash:/etc/aliases alias_maps = hash:/etc/aliases append_dot_mydomain = no biff = no broken_sasl_auth_clients = yes config_directory = /etc/postfix home_mailbox = Maildir/ inet_interfaces = all mailbox_command = /usr/lib/dovecot/deliver -c /etc/dovecot/dovecot.conf -m "${EXTENSION}" mailbox_size_limit = 0 mydestination = polynet.me, vps31465.vps.ovh.ca, localhost.vps.ovh.ca, localhost myhostname = vps31465.vps.ovh.ca mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 myorigin = /etc/mailname readme_directory = no recipient_delimiter = + relayhost = smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache smtp_use_tls = yes smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu) smtpd_recipient_restrictions = reject_unknown_sender_domain, reject_unknown_recipient_domain, reject_unauth_pipelining, permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination smtpd_sasl_auth_enable = yes smtpd_sasl_authenticated_header = yes smtpd_sasl_local_domain = $myhostname smtpd_sasl_path = private/dovecot-auth smtpd_sasl_security_options = noanonymous smtpd_sasl_type = dovecot smtpd_sender_restrictions = reject_unknown_sender_domain smtpd_tls_auth_only = yes smtpd_tls_cert_file = /etc/dovecot/dovecot.pem smtpd_tls_key_file = /etc/dovecot/private/dovecot.pem smtpd_tls_mandatory_ciphers = medium smtpd_tls_mandatory_protocols = SSLv3, TLSv1 smtpd_tls_received_header = yes smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache smtpd_use_tls = yes tls_random_source = dev:/dev/urandom And my Output from doveconf -n root@vps31465:~# doveconf -n # 2.2.9: /etc/dovecot/dovecot.conf # OS: Linux 2.6.32-042stab093.5 x86_64 Ubuntu 14.04.1 LTS mail_location = mbox:~/mail:INBOX=/var/mail/%u managesieve_notify_capability = mailto managesieve_sieve_capability = fileinto reject envelope encoded-character vacation subaddress comparator-i;ascii-numeric relational regex imap4flags copy include variables body enotify environment mailbox date ihave namespace inbox { inbox = yes location = mailbox Drafts { special_use = \Drafts } mailbox Junk { special_use = \Junk } mailbox Sent { special_use = \Sent } mailbox "Sent Messages" { special_use = \Sent } mailbox Trash { special_use = \Trash } prefix = } passdb { driver = pam } plugin { sieve = ~/.dovecot.sieve sieve_dir = ~/sieve } protocols = " imap lmtp sieve pop3" ssl_cert = </etc/dovecot/dovecot.pem ssl_key = </etc/dovecot/private/dovecot.pem userdb { driver = passwd } The domain is mail.polynet.me. I don't know where I have gone wrong. Help is greatly appreciated :) A: OK, so firstly it looks like your incoming mail transaction is running into problems with SASL authentication. Oct 26 12:40:11 vps31465 postfix/smtpd[13551]: warning: SASL: Connect to private/dovecot-auth failed: No such file or directory That path looks to have come from here, in what I assume is postconf output (contrary to how you describe how you got it): smtpd_sasl_path = private/dovecot-auth That's a path to a socket, which is relative to $queue_directory. I'm not sure why that's not in your (assumed) postconf output. On my system it's /var/spool/postfix. So check that that path exists (presumably it doesn't) Your doveconf -n output actually looks like a repeat of your postconf output, so I can only do so much. On my system I have a stanza like so: service auth { unix_listener /var/spool/postfix/private/auth { group = postfix mode = 0660 user = postfix } } Which creates the socket which postfix talks to to deliver email. You've named your socket file dovecot-auth instead of auth, which seems sensible enough. I'm guessing though that you have something wrong in configuring that socket for postfix to talk to. Please fix the configuration listings in your question, or I might have to down-vote it. EDIT: I took a look at the link you've been using. It refers to a gist with instructions for dovecot setup, which I think you've missed entirely.
{ "pile_set_name": "StackExchange" }
Q: Coordinates of click I'm trying to use HERE js sdk. I'm add a tap-event listener to map. How to get the actual coord of a tap. I finished with code bellow: let tapHandler = (evt) => { console.log(evt.currentTarget.getCenter()) } but it actually returns an initial center of the Map A: You can get coordinates from the map with: clickCoords = map.screenToGeo(e.viewportX, e.viewportY);
{ "pile_set_name": "StackExchange" }
Q: @Font-face not working on IOS So I am working on a WordPress website and on each page I have an H1 tag for the title of that page. I am using a special font using @font-face and it works great on windows in every browser, but when I switch over to a mac it won't display the h1 tag its just white space. I have tested this in safari and chrome on multiple mac's and its not working on any of them. If I change the font to let say Arial it works great, if I setup to have a fall back font it does not work. If I change the h1,h2,h3 tags to use NorthBergen-Light it works great, its just the NorthBergen that doesn't work and the code for both of them is the exact same. In my research I have found that some people say they have had success when they remove all of the quotes but when I do that it just breaks everything. I can't figure out why NorthBergen-Light works great but NorthBergen does not. @font-face { font-family: 'NorthBergen'; font-style: normal; src: url('//www.mywebsite.com/op/wp-content/uploads/useanyfont/141009064915ufonts.com_northbergen-regular.eot'); src: local('NorthBergen'), url('//www.mywebsite.com/op/wp-content/uploads/useanyfont/141009064915ufonts.com_northbergen-regular.eot') format('embedded-opentype'), url('//www.mywebsite.com/op/wp-content/uploads/useanyfont/141009064915ufonts.com_northbergen-regular.woff') format('woff'); } @font-face { font-family: 'NorthBergen-Light'; font-style: normal; src: url('//www.mywebsite.com/op/wp-content/uploads/useanyfont/141009083525ufonts.com_northbergen-light-opentype.eot'); src: local('NorthBergen-Light'), url('//www.mywebsite.com/op/wp-content/uploads/useanyfont/141009083525ufonts.com_northbergen-light-opentype.eot') format('embedded-opentype'), url('//www.mywebsite.com/op/wp-content/uploads/useanyfont/141009083525ufonts.com_northbergen-light-opentype.woff') format('woff'); } .services .services-inside .services-title{ font-family: 'NorthBergen' !important; } h1, h2, h3{ font-family: 'NorthBergen', 'Times New Roman', 'Times', 'serif' !important; } footer.main-footer .widget .widget-title{ font-family: 'NorthBergen-Light' !important; } h5, h6, p, blockquote, li, a, .main-container, h4.widget-title, .widget-title{ font-family: 'NorthBergen-Light' !important; } So I got it to work by using fontsquirrel and taking all the files and putting them in my FTP and changing the css file to look like. @font-face { font-family: 'NorthBergen'; font-style: normal; src: url('ufonts.com_northbergen-regular-opentype-webfont.eot'); src: url('ufonts.com_northbergen-regular-opentype-webfont.eot?#iefix') format('embedded-opentype'), url('ufonts.com_northbergen-regular-opentype-webfont.woff2') format('woff2'), url('ufonts.com_northbergen-regular-opentype-webfont.woff') format('woff'), url('ufonts.com_northbergen-regular-opentype-webfont.ttf') format('truetype'), url('ufonts.com_northbergen-regular-opentype-webfont.svg#northbergenregular') format('svg'); } A: Dont know anything about Wordpress, but you might need some conversion of font for all browsers: @font-face { font-family: 'Min_font'; src: url('../fonts/Min_font/Min_font.eot') format('embedded-opentype'); /* IE9 + later */ src: url('../fonts/Min_font/Min_font.eot?#iefix') format('embedded-opentype'), /* IE6 to IE8 */ url('../fonts/Min_font/Min_font.woff') format('woff'), /* Newer browsers */ url('../fonts/Min_font/Min_font.ttf') format('truetype'), /* Safari og iOS, Chrome, Android, Firefox and Opera except Opera Mini */ url('../fonts/Min_font/Min_font.svg#Min_font + regular, italic, bold) format('svg'); /*IE og iOS earlier than version 5*/ } Try fontsquirrel: http://www.fontsquirrel.com/tools/webfont-generator
{ "pile_set_name": "StackExchange" }
Q: What does it mean to say the first Goodwillie derivative of $TC$ is $THH$? A paradox: Goodwillie calculus considers only finitary functors. $TC$ isn't finitary. Yet in some sense $\partial(TC) = \partial(K) = THH$ is the crux of the Dundas-Goodwillie-McCarthy theorem. (Here, a finitary functor is one preserving filtered colimits[1]. $\partial$ denotes the first Goodwillie derivative. $TC,K,THH$ are respectively topological cyclic homology, algebraic $K$-theory, and topological Hochschild homology, regarded as functors from $E_1$-ring spectra to spectra.) Obviously I don't fully understand that last point, which is just a rough idea I think I've read somewhere, and that's what I want to ask about. Questions: What does it mean to say that the first Goodwillie derivative of $TC$ is $THH$? Is there a general formalism for Goodwillie calculus of non-finitary (but, say, accessible) functors? If so, how much of the usual theory goes through? If the answer to (2) is "yes", does it specialize in the case of $TC$ to recover the answer to (1)? [1] At any rate, in Goodwillie calculus one always requires one's functor to commute with sequential colimits. Any functor that commutes with sequential colimits and $\aleph_1$-filtered colimits commutes with all filtered colimits. $TC$ is defined from $THH$ (which commutes with filtered colimits) via a countable limit and therefore $TC$ commutes with $\aleph_1$-filtered colimits. I conclude that if $TC$ doesn't commute with filtered colimits, then it already doesn't commute with sequential colimits, and so standard Goodwillie calculus doesn't apply to it. A: This answer addresses Question 1. Let "ring" mean associative unital ring spectrum, say in the $A^\infty$ sense. For a functor $F$ from rings to spectra (such as $TC$), differentiating $F$ at the ring $R$ means finding the best excisive approximation to the functor from rings-having-$R$-as-a-retract to spectra, $$ (R\to S\to R)\mapsto fiber (F(S)\to F(R)). $$ The universal excisive functor takes values in $R$-bimodules. (That is, a spectrum object for the category of rings over $R$ can be encoded in an $R$-bimodule.) Call it $\Omega_R$. If $S$ is $n$-connected relative to $R$ then $\Omega_R(S)$ is related to $fiber(S\to R)$ by a roughly $2n$-connected map of bimodules. The derivative of $F$ at $R$ must be $L\circ \Omega$ for some linear functor $L$ from $R$-bimodules to spectra. Thus to name the derivative of $F$ at $R$ you have to name a certain such linear functor. If $F$ is what I call analytic (or even if it is what I call stably excisive) then this means that $fiber (F(S)\to F(R))$ is related by a roughly $2n$-connected map to $L(S\to R)$. If $F$ is finitary then its derivative at $R$ is a finitary linear functor, and therefore the corresponding map $L$ is given by tensoring over $R\wedge R^{op}$ with a fixed bimodule. It happens that the derivative of $TC$ is finitary (even though $TC$ is not) and the fixed bimodule in question is $R$ itself. Tensoring an $R$-bimodule $M$ with $R$ gives $THH(R;M)$, so this means that in a stable range $fiber(TC(S)\to TC(R)$ looks like $THH(R;fiber (S\to R))$. There is an unfortunate clash of terminology. When differentiating a functor of spaces at $X$ you get an excisive functor from spaces-containing-$X$-as-a-retract to spectra. In Calculus 3 I called this the "differential" of $F$ at $X$, denoting it by $D_XF$. If $F$ is finitary then $D_XF$ is as well, and then it must be given by fiberwise smash product with a fixed parametrized spectrum over $X$. I denoted the fiber of that parametrized spectrum at $x\in X$ by $\partial_xF(X)$ and called it the (partial) derivative. So the differential is given by smashing with the derivative. In the setting of functors of rings, the "spectra" made out of objects over $R$ correspond to $R$-bimodules, whereas in the setting of functors of spaces the "spectra" made out of objects over $X$ correspond to parametrized spectra over $X$. In the latter setting "derivative" means the parametrized spectrum that you smash with to give the differential. By analogy in the former setting it ought to mean the bimodule you tensor with to give the differential. In those terms the derivative of $TC$ at $R$ is the bimodule $R$. A: Your first premise - that Goodwillie calculus considers only finitary functors - is wrong. Goodwillie doesn't insist on this. The only point at which finitary enters the story is when one wishes to identify homogeneous functor of degree $n$ with spectra with (naive) actions of the $n$-th symmetric group. And even without the finitary condition, Goodwillie shows that degree $n$ homogeneous functors correspond to symmetric $n$--linear functors. In my own work, I have made much use of Goodwillie calculus applied to non--finitary functors of the form $LF$, where $L$ is a non-smashing Bousfield localization (e.g. localization with respect to a Morava $K$--theory). Composites like this are also a source of instructive examples, e.g., the composition of homogeneous functors need not be again homogeneous. See my survey paper [Goodwillie towers and chromatic homotopy: an overview. Proceedings of the Nishida Fest (Kinosaki 2003), 245–279, Geom. Topol. Monogr., 10] for more about all of this, and more references.
{ "pile_set_name": "StackExchange" }
Q: How to fix memmory allocation problem in the function below? (malloc) I need to read a .txt file and to allocate each word from the file in a struct which is pointed from a vector of structs. I'll explain better below. I appreciate your help. My program is allocating only the first word of the file... I know that the problem is in the function insere_termo() cause I've tested the fscanf whitout calling the function and it's doing ok. STRUCTS typedef struct _item { int conta; //contador char *termo; //palavra } Item; typedef struct _mapa { int total; // número de itens no mapa int blocos; // número de blocos de itens alocados Item **lista; // vetor de ponteiros para itens } Mapa; MAIN int main() { Mapa mp; FILE *arq; int i, result, numPalavras; float x; int valor, max, min, mincar; char caminho[20]; char termo[40]; int tam; inicia_mapa(&mp); valor = menu(); HERE'S THE IMPORTANT PART OF MY CODE. WHERE I READ A FILE IN THE PATH GIVEN BY THE USER AND CALL THE FUNCTION insere_termo(); WHICH IS RESPONSIBLE FOR ALLOCATING EACH WORD IN THE struct. switch (valor) { case 1: printf ("*Ler Arquivo* \n"); printf("Digite caminho: "); scanf("%s", caminho); arq = fopen(caminho,"r"); // abrir arquivo no caminho especificado if (arq == NULL) { printf("Erro, nao foi possivel abrir o arquivo\n"); } while(fscanf(arq, "%s", termo) != EOF) { //Adiciona cada palavra no vetor insere_termo(&mp, termo); } break; FUNCTIONS INICIA_MAPA() IS THE FUNCTION WHICH IS RESPONSIBLE FOR INITIATING THE MAP, ALLOCATING A BLOCK OF 10 POINTERS TO THE STRUCT "ITEM". INSERE_TERMO() IS THE FUNCTION WHICH IS RESPONSIBLE FOR ALLOCATING THE WORDS GIVEN BY THE TEXT FILE. THERE'S SOME PROBLEM WITH THE MEMORY ALLOCATION BUT I COULDN'T FIGURE IT OUT. ANY HELP IS WELCOME. void inicia_mapa (Mapa *mp) //inicia um mapa vazio { mp->lista = (Item**)malloc(BLOCK*sizeof(Item*)); mp->total = 0; mp->blocos = 1; } void insere_termo (Mapa *mp, char *s) // insere um item com termo s e conta = 1 { if ((mp->total != 0)&&((mp->total%BLOCK) == 0)) { mp->lista = (Item**)realloc(mp->lista,(mp->blocos+1)*BLOCK*(sizeof(Item*))); mp->blocos++; } mp->lista[mp->total] = (Item*) malloc(sizeof(Item)); // alocação dinâmica de item no mapa if (mp->lista[mp->total] == NULL) { printf("Erro na alocacao de memoria\n"); exit(0); } strcpy(mp->lista[mp->total]->termo, s); // Insere termo s printf("%s\n", mp->lista[mp->total]->termo); mp->lista[mp->total]->conta++; mp->total++; // contagem do total } A: strcpy(mp->lista[mp->total]->termo, s); fails as mp->lista[mp->total]->termo is not yet assigned a value. Passing an uninitialized pointer pp to strcpy(p, ...) is undeifned behavior (UB). Instead allocate memory, then copy with strcpy() // strcpy(mp->lista[mp->total]->termo, s); p->lista[mp->total]->termo = malloc(strlen(s) + 1); strcpy(p->lista[mp->total]->termo, s); // or p->lista[mp->total]->termo = strdup(s); Be sure to free memory when done. Other problems may exist.
{ "pile_set_name": "StackExchange" }
Q: Smith normal form of a matrix A, prove first diagonal entry of the SNF is the hcf of the entries of A So, as per the title, assuming that we know an $n \times n$ matrix $A$ with integer entries is equivalent (can be obtained via row/column operations on $A$) to a matrix with diagonal entries $d_1, d_2, ... , d_n$ where $0< d_i | d_{i+1}$ for each $1 \leq i \leq m-1$ (Smith Normal Form), show that $d_1$ is the highest common factor of the entries of the matrix $A$. Firstly, it's obvious $d_1$ is the highest common factor of the entries in the diagonal matrix, for if there's some other common factor $d$ then $d | d_1$ by definition, but I've been unsuccessful in showing this is also true for the entries in the matrix $A$ Any help appreciated! A: If $d$ is the hcf, you can use it to clear out all entries in its row and column, and can then move $d$ to the upper left by swaps. What remains is a smaller matrix, so by induction, its SNF has ITS hcf in the upper left corner, and this HCF must be no less than $d$. So all that remains is to show that the upper left entry can't be LESS than the HCF. Well...all the row operations you perform don't change the hcf (recall that the row/col ops are only exchanges and "add k times row i to row j" for integers k (and similarly for cols). So since $d$ divides all the diagonal entries of the SNF, it also divides all the original entries. And I believe that's the whole story.
{ "pile_set_name": "StackExchange" }
Q: \pic without named coordinates Is it possible to use the \pic command provided by the angles library in tikz, without using coordinates? If I use something like this, it works correctly. \begin{tikzpicture} \coordinate (A) at (0,0); \coordinate (B) at (0,5); \coordinate (C) at (5,0); \node [left] at (A) {$A$}; \node [left] at (B) {$B$}; \node [right] at (C) {$C$}; \draw (A) -- (B) -- (C); \pic [draw] {angle = A--B--C}; \end{tikzpicture} However, if I use this, \begin{tikzpicture} \coordinate (A) at (0,0); \coordinate (B) at (0,5); \coordinate (C) at (5,0); \node [left] at (A) {$A$}; \node [left] at (B) {$B$}; \node [right] at (C) {$C$}; \draw (A) -- (B) -- (C); \pic [draw] {angle = (0,0)--(0,5)--(5,0)}; \end{tikzpicture} it does not work. It would be great if I could use this so that I can use points without naming them. A: angle expects names, not coordinates. The name argument is directly parsed to \pgfpointanchor, from tikzlibraryangles.code.tex: \def\tikz@lib@angle@parse#1--#2--#3\pgf@stop{% % ... \pgf@process{\pgfpointanchor{#2}{center}}% \pgf@xa=\pgf@x% \pgf@ya=\pgf@y% \pgf@process{\pgfpointanchor{#1}{center}}% \pgf@xb=\pgf@x% \pgf@yb=\pgf@y% \pgf@process{\pgfpointanchor{#3}{center}}% % ... } \pgfpointanchor expects a node name as first argument. Therefore the library needs heavy patching to support coordinate specifications, too. The following example patches libary angles. The argument of angle needs to be sourrounded by curly braces to hide the comma from the pgfkeys parser: \documentclass{article} \usepackage{tikz} \usetikzlibrary{angles} \usepackage{etoolbox} \makeatletter % Helper macros \def\tikz@lib@angle@def@coord#1{% \ifx(#1\relax \coordinate(tikz@lib@angle@tmp)at#1;% \else \coordinate(tikz@lib@angle@tmp)at(#1);% \fi } \def\tikz@lib@angle@coord#1{% \pgf@process{% \ifx(#1\relax \tikz@scan@one@point\@firstofone#1\relax \else \pgfpointanchor{#1}{center}% \fi }% } % Patching \patchcmd\tikz@lib@angle@background{#2}{tikz@lib@angle@tmp}{}{% \errmessage{Cannot patch \string\tikz@lib@angle@background}% } \patchcmd\tikz@lib@angle@foreground{#2}{tikz@lib@angle@tmp}{}{% \errmessage{Cannot patch \string\tikz@lib@angle@foreground}% } \pretocmd\tikz@lib@angle@background{\tikz@lib@angle@def@coord{#2}}{}{% \errmessage{Cannot prepend \string\tikz@lib@angle@background}% } \pretocmd\tikz@lib@angle@foreground{\tikz@lib@angle@def@coord{#2}}{}{% \errmessage{Cannot prepend \string\tikz@lib@angle@foreground}% } \patchcmd\tikz@lib@angle@parse{% \pgf@process{\pgfpointanchor{#2}{center}}% }{% \tikz@lib@angle@coord{#2}% }{}{% \errmessage{Cannot patch \string\tikz@lib@angle@parse}% } \patchcmd\tikz@lib@angle@parse{% \pgf@process{\pgfpointanchor{#1}{center}}% }{% \tikz@lib@angle@coord{#1}% }{}{% \errmessage{Cannot patch \string\tikz@lib@angle@parse}% } \patchcmd\tikz@lib@angle@parse{% \pgf@process{\pgfpointanchor{#3}{center}}% }{% \tikz@lib@angle@coord{#3}% }{}{% \errmessage{Cannot patch \string\tikz@lib@angle@parse}% } % Better support for the comma in the value for angle: \tikzset{ pics/angle/.style = { setup code = {\tikz@lib@angle@parse#1\pgf@stop}, background code = {\tikz@lib@angle@background#1\pgf@stop}, foreground code = {\tikz@lib@angle@foreground#1\pgf@stop}, }, } \makeatother \begin{document} \begin{tikzpicture} \coordinate (A) at (0,0); \coordinate (B) at (0,5); \coordinate (C) at (5,0); \node [left] at (A) {$A$}; \node [left] at (B) {$B$}; \node [right] at (C) {$C$}; \draw (A) -- (B) -- (C); % \pic [draw] {angle=A--B--C}; \pic [draw] {angle={(0,0)--(0,5)--(5,0)}}; \end{tikzpicture} \end{document}
{ "pile_set_name": "StackExchange" }
Q: Trouble with Flask's request.is_secure using gunicorn and heroku with Flask I've seen this problem discussed on the web, but the explanations for fixing it aren't exactly clear, especially if you're not super familiar with Flask. It's the issue where request.is_secure always returns False when flask is running on gunicorn on Heroku, even if the request is done with HTTPS. I'm using Flask 0.8 and gunicorn 19.0.0. I found this link, makes it look like you create a file called gunicorn.py with those contents, but that just created an import error on the Heroku server. Then I tried taking those settings and applying them directly to my app Flask object by doing: app.secure_proxy_ssl_header = ('HTTP_X_FORWARDED_PROTO', 'https') app.forwarded_allow_ips = '*' app.x_forwarded_for_header = 'X-FORWARDED-FOR' app.secure_scheme_headers = { 'X-FORWARDED-PROTO': 'https', } but still no dice. Can somebody please give a clear explanation of what I have to do, and where to put the configuration? A: Turned out the solution was much simpler than I thought. All I had to do was: from werkzeug.contrib.fixers import ProxyFix and then app.wsgi_app = ProxyFix(application.wsgi_app)
{ "pile_set_name": "StackExchange" }
Q: Wrap a div element for a body's innerHTML I need to wrap up the body content inside a div dynamically. I tried the below code and i am getting, 'newDiv.append function is undefined'. I tried with setTimeout as well and checked after the jquery file loads made for loop to get loaded. Still getting the same error. function initiate() { var jq_script = document.createElement('script'); jq_script.setAttribute('src', '//code.jquery.com/jquery-1.11.2.min.js'); document.head.appendChild(jq_script); var newDiv = document.createElement('div') newDiv.setAttribute('id', 'wrapper'); var bodyChildren = document.body.childNodes; for (var i = 0; i < bodyChildren.length; i++) { newDiv.append(bodyChildren[i]); } document.body.appendChild(newDiv); } initiate(); And i tried this as well to wrap up the body's innerHTML with a div element. function initiate() { var jq_script = document.createElement('script'); jq_script.setAttribute('src', '//code.jquery.com/jquery-1.11.2.min.js'); document.head.appendChild(jq_script); var div = document.createElement("div"); div.id = "wrapper"; while (document.body.firstChild) { div.appendChild(document.body.firstChild); } document.body.appendChild(div); } initiate(); This keeps on adding the wrapper element inside body. And the above script is inside iframe. Any solution on this? A: Two problems: It's appendChild, not append. Once that's out of the way, though, the other problem is in your loop: childNodes is a dynamic list, and so when you move a child out of body into newDiv, the list changes, making your indexes invalid. You can fix that by just looping, moving first child into your div, until the body runs out of children, then append the div: var newDiv = document.createElement('div') newDiv.id = "wrapper"; // You don't need or want setAttribute here var bodyChildren = document.body.childNodes; while (bodyChildren.length) { newDiv.appendChild(bodyChildren[0]); } document.body.appendChild(newDiv); Or actually, you don't even need the list, you can use firstChild: var newDiv = document.createElement('div') newDiv.id = "wrapper"; // You don't need or want setAttribute here while (document.body.firstChild) { newDiv.appendChild(document.body.firstChild); } document.body.appendChild(newDiv);
{ "pile_set_name": "StackExchange" }
Q: What to do after change HTTP to HTTPS? I've a website working good from a couple of years. Now I'd like to implement ssl protection, for Facebook app and payment stuff. My question is if I've to change inside the code all the http url to https url. Or, with your experience, what I've to modify in my code? (htaccess? link? ecc) Thanks in advance. Alex A: Good article on SSL might give you a better understanding of how it works. http://info.ssl.com/article.aspx?id=10694
{ "pile_set_name": "StackExchange" }
Q: check if any is 0 How to check with php/sql if any of fields in database that are selected in while loop is 0? $res = mysql_query('SELECT id, name FROM table'); \\check here? while($row = mysql_fetch_array) { \\or check here? } Thanks in advance! EDIT: I need to select all fields and then check if any one of them is 0. A: $foundZero = false; $res = mysql_query('SELECT id, name FROM table'); while ($row = mysql_fetch_array($res)) { if (in_array(0, $row)) { // This row has a zero $foundZero = true; } } if ($foundZero) { // at least one zero in one row has been found } else { // No zeros have been found } If $foundZero is true, then at least one field in one row is equal to 0. Otherwise, all fields are non-zero.
{ "pile_set_name": "StackExchange" }
Q: How to use QoreProgramLocation class to identify particular location in Qore source code I need get statement(s) (i.e.instance of AbstractStatement class) related to particular location in file (e.g. foo.q:150) so I process somehow parent class (struct) QoreProgramLocation which defines two members file and source (when the latter is often null). It is not clear what is difference. I suspect it might be used when files are included to point both original file and real location in include. There is also offset member. Is it intended for sections used when Qore is embedded in another program (e.g.Qorus) ? struct QoreProgramLocation : public QoreProgramLineLocation { public: const char* file; const char* source; int offset; ... } A: This is a great question. In QoreProgramLocation, members are as follows: file: refers to the label given when parsing the code source: refers to the actual file name or path of the source code (if the label does not provide this info) offset: the offset of the code in source So source and offset are only given if there are multiple code objects defined in the same file. In case of one code object in one file, then file is the set, source is nullptr, offset is 0, and the line number is taken directly from start_line and end_line. In case of multiple code objects in one file, then all members are assigned values, in such cases start_line and end_line refer to the line number within the code object, and the line number in the file is calculated by adding with offset, giving the line number offset within source. For example, in the documentation of the following Qore method: QoreProgram::parse() describes this case; note that label will be set as file in QoreProgramLocation. Because offset is always 0 when there is no source, you can always derive the actual line numbers by using: start_line + offset and end_line + offset. I hope this is clear!
{ "pile_set_name": "StackExchange" }
Q: What is the standard reference point for measuring speed? Speed, as we know, doesn't exist without first having a reference point. We then say that the reference point isn't moving at all, and speed is then measured in relation to the reference point. What is the standard reference point when determining the speed of objects in astronomy? Earth? A: As Einstein realized and like you correctly state, you indeed can't measure the speed of an object by itself since it has to be measured relative to something else. As a logic result, if you ask the question "How fast is X moving?", you will have to specify that you want the speed with respect to another object because motion cannot be measured without a reference point. Some examples: If you ask how fast Earth is moving with respect to its own axis, the center of the Earth will be your reference point. If you want to know how fast the Earth orbits the Sun, the Sun will be your reference point. If you want to know how fast the Moon's distance from Earth increases, Earth will be your reference point. If you want to know the speed of our solar system in the milky way galaxy, the center of the Milky Way will be your reference point. "standard" reference point If no reference point is given, it could be assumed that the "standard reference point" is the location of the observer. In the realms of astronomy, that would be the location of the astronomer. It should be noted that the astronomer could well be on an space mission outside Earth's atmosphere, or he/she could be using a telescope in Earth's orbit. Therefore, "Earth" can not generally be assumed to be a standard reference point for astronomy because, depending on the precision of the measurements and the location of (for example) the telescope, assuming "Earth" may result in inexact measurements. EDIT As @TidalWave correctly commented, there's also the International Celestial Reference Frame (ICRS) which can help you find reference points, calculate distances, etc. according to a celestial reference system, which has been adopted by the International Astronomical Union (IAU) for high-precision positional astronomy. The origin of ICRS resides at the barycenter of the solar system. Wrapping it up: If no reference point is defined and if we can assume that the astronomer works according to the rules and definitions of the International Astronomical Union (which would be the regular, if not ideal case), the International Celestial Reference Frame provides you with a "standard reference point" at it's center (which is the barycenter of the solar system). In rare cases where IAU compliance can not be assumed (something that "might" happen in amateur realms), it has to be assumed that the reference point is the point of observation. A: The rest frame for measuring (astronomical) speeds and velocities depends on the context and purpose. A geocentric frame, based on the Earth's centre of mass might be appropriate for objects in orbit around the Earth. A heliocentric reference frame, centred on the Sun, is often used when describing the line of sight velocities of astronomical objects, but more usually, a barycentric frame at the solar system centre of mass is used. For example, this is how the radial velocities measurements of exoplanet host stars or components of eclipsing binaries would be quoted. It would also be appropriate for the motion of objects in the solar system. Motions in the Galaxy are commonly defined in two ways. One is the Local Standard of Rest (LSR), which measures velocities with respect to the average motion of stars near the Sun. The second attempts to measure velocities with respect to the Galactic plane and radially and tangentially in the plane with respect to the Galactic centre. These are the so-called $U,V,W$ velocities. The position and motion of the LSR with respect to the Galactic centre are uncertain at the level of a few km/s, whereas the solar motion with respect to the LSR is more precisely known. The Galactic centre can also be used as a reference frame for the motion of galaxies in our local group. e.g. when talking about the motion of the Andromeda Galaxy. Finally, we can determine a cosmic standard of rest - the co-moving stationary frame of the Hubble flow - using precise measurements of the cosmic microwave background (CMB). In other words, we can determine our peculiar motion with respect to the Hubble flow by observing the dipole doppler signature in the CMB.
{ "pile_set_name": "StackExchange" }
Q: Postgres: fulltext filter on result row I am using jTable to present a table of say, customers. This table supports filtering on various criteria, sorting the results, and paging. All of this is reflected in the Postgres query to fetch the data: SELECT ...some columns... FROM ...some table... WHERE ...filter conditions... ORDER BY ...sort order... OFFSET offset LIMIT limit; Now the table should be able to do a "fulltext" search, meaning: if the search term is not found as a substring in any of the columns of the result row, this row is not admitted. My first approach was to render each row into JSON (as jTable requires it) and then do a String.contains(), but this does not work well with the rest of the filtering/sorting/pagination. What I want is a way to check if the term is contained in the query result row, and I want this to be part of the query. I do not want to explicitly check each of the columns: ... AND (col1 LIKE '%term%' OR col2 LIKE '%term%' OR .... Is there a way to do this in Postgres? A: You could concatenate all the columns together into a single string and then do the search: SELECT ...some columns... FROM (SELECT ...some columns..., concat_ws(, '|', ...some columns...) as tosearch FROM ...some table... WHERE ...filter conditions... ORDER BY...sort order... OFFSET offset LIMIT limit ) t WHERE tosearch like '%searchterm%'; As a note: concat_ws() ignores NULLs, so you don't have to worry about a NULL search string.
{ "pile_set_name": "StackExchange" }
Q: How to detect incoming call on N900 and display info window based on caller? Does the N900 allow me to display additional information in parallel to the native application or does the latter always have priority over my process? I'm interested in displaying additional information based on caller id. If it's possible, can you name any pitfalls or give small python code examples / or tipps to get started? A: detecting incoming call might be the smallest problem you will see in this journey - you can start with this thread now consider few other factors before you decided whether you want to continue or not: calls come not only as phone call but also as SIP call, Skype call, GTalk call, etc call signaling is relatively resource-heavy due to time constraints vs blocked by I/O, etc call dialog should work ok in portrait and landscape, so you might need to go down extending call architecture not writing my own little thing in 1-2 weekends internal eMMC storage is not quick and gets slow on 2+ threads trying to write if you are Ok with risk to spent time and bump into limitations of Maemo5 platform put on end-of-lifecycle hook -- consider learning down googleing keywords maemo5 telepathy mission-control . this is starting point not definitive guide -- you have to learn quit many different things before you start to approach plugging call progress dialogs.
{ "pile_set_name": "StackExchange" }
Q: What are Facelets and how is it related to JSF? Am farely new to JSF and I get easily confused between JSF and Facelets when I read tutorials... What are Facelets ?..Is JSF & Facelets the same ?... How is Facelets different from JSTL ? A: Facelets is a powerful but lightweight page declaration language that is used to build JavaServer Faces views using HTML style templates and to build component trees. Facelets features include the following: ·Use of XHTML for creating web pages ·Support for Facelets tag libraries in addition to JavaServer Faces and JSTL tag libraries ·Support for the Expression Language (EL) ·Templating for components and pages Basically, Facelets allows you to add template tag libraries (XML documents) that are useful for adding UI controls in html pages, if you work with JSF. this declaration is an example of Facelets: <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"> <!-- look at the xml library 'import' --> <body> <h:form> <h:outputText value="Welcome, #{loggedInUser.name}" disabled="#{empty loggedInUser}" /> <h:inputText value="#{bean.property}" /> <!-- look at this tags, the special mark 'h:outputText'... --> <h:commandButton value="OK" action="#{bean.doSomething}" /> </h:form> </body> </html> In conclusion, Facelets provides the tools (template tag libraries) for UI controls and JSF allows the communication of this controls with back-beans. http://en.wikipedia.org/wiki/Facelets http://docs.oracle.com/javaee/6/tutorial/doc/gijtu.html
{ "pile_set_name": "StackExchange" }
Q: ArrayList and IEnumerable query Why does the following DisplayContents not work(wont compile) for an ArrayList as it inherits form IEnumerable) public class Program { static void Main(string[] args) { List<int> l = new List<int>(){1,2,3}; DisplayContents(l); string[] l2 = new string[] {"ss", "ee"}; DisplayContents(l2); ArrayList l3 = new ArrayList() { "ss", "ee" }; DisplayContents < ArrayList>(l3); Console.ReadLine(); } public static void DisplayContents<T>(IEnumerable<T> collection) { foreach (var _item in collection) { Console.WriteLine(_item); } } } A: ArrayList implements IEnumerable, but not the generic IEnumerable<T>. This is to be expected, since ArrayList is neither generic nor bound to any specific type. You need to change the parameter type of your DisplayContents method from IEnumerable<T> to IEnumerable and remove its type parameter. The items of your collection are passed to Console.WriteLine, which can accept any object. public static void DisplayContents(IEnumerable collection) { foreach (var _item in collection) { Console.WriteLine(_item); } } A: Well, a quick check of the docs tells me that ArrayList does not implement IEnumerable<T>, but instead implements IEnumerable, which makes sense as ArrayList is a vestigial artifact from the days before generics and has few real uses today. There's really no reason to use ArrayList at all. You can at least use a List<object>, but what problem does that solve? Unless you absolutely need to have a collection of random types that do not / cannot implement a common interface and cannot be grouped into a new type then use a more specific generic parameter.
{ "pile_set_name": "StackExchange" }
Q: Node.js - Try Catch Error Not Being Returned i have written a node.js api using the express framework. I am using await and async. I catch the asynchronous function in a try catch block. However in the catch(err) method the err is not being returned. try { const job = await this.jobRepository.functionDoesNotExist(); if (job.success === false) { return res.status(404).json({ success: false, status: 404, data: job, message: "Failed to retrieve job" }); } return res.status(200).json({ success: true, status: 200, data: job.data, message: "Successfully retrieved job" }); } catch (err) { return res.status(500).json({ success: false, status: 500, data: err, message: "The server threw an unxpected errror" }); } In the above example i am deliberately calling a function that does not exist so that it throws an error. The response i get is below. It is hitting the catch block, but the error is not being added to the data object. { "success": false, "status": 500, "data": {}, "message": "The server threw an unxpected errror" } However, if i move the below line out of the try catch block. The console will throw the following error. const job = await this.jobRepository.functionDoesNotExist(); "error":{},"level":"error","message":"uncaughtException: this.jobRepository.functionDoesNotExist is not a function\nTypeError: this.jobRepository.functionDoesNotExist is not a function\n at JobController.<anonymous> So my question is, why is this error not being displayed in the response when the call is made within the try catch block. A: By default, The error object is not JSON.stringify()-able. Read Here To get the stack trace however, you can use err.stack like so: return res.status(500).json({ success: false, status: 500, data: err.stack, message: "The server threw an unxpected errror" });
{ "pile_set_name": "StackExchange" }
Q: Save image from bar code scanner iOS 7 I have a barcode scanner I wrote using the some of the new AVCapture APIs in IOS7. Everything works great, but would love to grab the image after I get the met data from the capture output. The method below is the delegate where I do my lookup on SKU, etc and would like to grab the image as well. Is it possible to so this from this method? - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection { ... } A: To specifically answer your question, no, there isn't a way to save an image from a AVCaptureMetadataOutput instance. However, as codingVoldemort's excellent example shows, you can create an AVCaptureStillImageOutput instance and add it to your AVCaptureSession outputs. Once your app has detected some metadata, you can immediately trigger a capture on that CaptureStillImageOutput instance. Here's a little more explicit solution using codingVoldemort's initial code as a base: First, wherever you establish your AVCaptureSession, add an AVCaptureStillImageOutput to it: _session = [[AVCaptureSession alloc] init]; _output = [[AVCaptureMetadataOutput alloc] init]; [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()]; [_session addOutput:_output]; _stillImageOutput = [[AVCaptureStillImageOutput alloc] init]; [_session addOutput:_stillImageOutput]; Now, in - captureOutput: didOutputMetadataObjects, you can capture a still image when the method is triggered: AVCaptureConnection *stillImageConnection = [_stillImageOutput connectionWithMediaType:AVMediaTypeVideo]; [stillImageConnection setVideoOrientation:AVCaptureVideoOrientationPortrait]; [stillImageConnection setVideoScaleAndCropFactor:1.0f]; [_stillImageOutput setOutputSettings:[NSDictionary dictionaryWithObject:AVVideoCodecJPEG forKey:AVVideoCodecKey]]; _stillImageOutput.outputSettings = @{AVVideoCodecKey: AVVideoCodecJPEG, AVVideoQualityKey:@1}; [stillImageOutput captureStillImageAsynchronouslyFromConnection:stillImageConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) { if (error) { NSLog(@"error: %@", error); } else { NSData *jpegData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer]; UIImage *image =[UIImage imageWithData:jpegData]; //Grabbing the image here dispatch_async(dispatch_get_main_queue(), ^(void) { //Update UI if necessary. }); } } ];
{ "pile_set_name": "StackExchange" }
Q: g++ no matching function call error I've got a compiler error but I can't figure out why. the .hpp: #ifndef _CGERADE_HPP #define _CGERADE_HPP #include "CVektor.hpp" #include <string> class CGerade { protected: CVektor o, rv; public: CGerade(CVektor n_o, CVektor n_rv); CVektor getPoint(float t); string toString(); }; the .cpp: #include "CGerade.hpp" CGerade::CGerade(CVektor n_o, CVektor n_rv) { o = n_o; rv = n_rv.getUnitVector(); } the error message: CGerade.cpp:10: error: no matching function for call to ‘CVektor::CVektor()’ CVektor.hpp:28: note: candidates are: CVektor::CVektor(float, float, float) CVektor.hpp:26: note: CVektor::CVektor(bool, float, float, float) CVektor.hpp:16: note: CVektor::CVektor(const CVektor&) CGerade.cpp:10: error: no matching function for call to ‘CVektor::CVektor()’ CVektor.hpp:28: note: candidates are: CVektor::CVektor(float, float, float) CVektor.hpp:26: note: CVektor::CVektor(bool, float, float, float) CVektor.hpp:16: note: CVektor::CVektor(const CVektor&) A: From the looks of it, your CVektor class has no default constructor, which CGerade uses in your constructor: CGerade::CGerade(CVektor n_o, CVektor n_rv) { // <-- by here, all members are constructed o = n_o; rv = n_rv.getUnitVector(); } You could (and probably should) add one, but better is to use the initialization list to initialize members: CGerade::CGerade(CVektor n_o, CVektor n_rv) : o(n_o), rv(n_rv.getUnitVector()) {} Which specifies how the members are initialized. (And above, it was defaulting to the non-existent default-constructor.)
{ "pile_set_name": "StackExchange" }
Q: error setting up nginx provisioning on vagrant with virtualbox on Ubuntu I have installed Vagrant and Virtualbox on Ubuntu 16.04 LTS, with apt-get repositories fully updated. I have port forwarding set up for 'guest:80 host:8080', and a bootstrap.sh file requiring Vagrant to install nginx, start the service and create a symlink to /var/www. Despite having verified that nginx can be installed through the apt-get command, and the all the files exist, I continue to receive, 404 errors relating to the files to be downloaded, file not found errors, and an error claiming that the service nginx does not exist. I have included all relevant outputs and code below. The output from vagrant for the command, vagrant up --provision is as follows: Bringing machine 'default' up with 'virtualbox' provider... ==> default: Checking if box 'hashicorp/precise64' is up to date... ==> default: Clearing any previously set forwarded ports... ==> default: Clearing any previously set network interfaces... ==> default: Preparing network interfaces based on configuration... default: Adapter 1: nat default: Adapter 2: hostonly ==> default: Forwarding ports... default: 80 (guest) => 8080 (host) (adapter 1) default: 22 (guest) => 2222 (host) (adapter 1) ==> default: Booting VM... ==> default: Waiting for machine to boot. This may take a few minutes... default: SSH address: 127.0.0.1:2222 default: SSH username: vagrant default: SSH auth method: private key ==> default: Machine booted and ready! ==> default: Checking for guest additions in VM... default: The guest additions on this VM do not match the installed version of default: VirtualBox! In most cases this is fine, but in rare cases it can default: prevent things such as shared folders from working properly. If you see default: shared folder errors, please make sure the guest additions within the default: virtual machine match the version of VirtualBox you have installed on default: your host and reload your VM. default: default: Guest Additions Version: 4.2.0 default: VirtualBox Version: 5.1 ==> default: Configuring and enabling network interfaces... ==> default: Mounting shared folders... default: /vagrant => /home/thucydides/website-files ==> default: Running provisioner: shell... default: Running: /tmp/vagrant-shell20161213-8723-c2l7wt.sh ==> default: stdin: is not a tty ==> default: Reading package lists... ==> default: Building dependency tree... ==> default: Reading state information... ==> default: The following extra packages will be installed: ==> default: libgd2-noxpm libjpeg-turbo8 libjpeg8 libxslt1.1 nginx-common nginx-full ==> default: Suggested packages: ==> default: libgd-tools ==> default: The following NEW packages will be installed: ==> default: libgd2-noxpm libjpeg-turbo8 libjpeg8 libxslt1.1 nginx nginx-common ==> default: nginx-full ==> default: 0 upgraded, 7 newly installed, 0 to remove and 66 not upgraded. ==> default: Need to get 276 kB/882 kB of archives. ==> default: After this operation, 2,686 kB of additional disk space will be used. ==> default: Err http://us.archive.ubuntu.com/ubuntu/ precise-updates/main libjpeg-turbo8 amd64 1.1.90+svn733-0ubuntu4.1 ==> default: 404 Not Found [IP: 91.189.91.23 80] ==> default: Err http://us.archive.ubuntu.com/ubuntu/ precise-updates/main libxslt1.1 amd64 1.1.26-8ubuntu1.1 ==> default: 404 Not Found [IP: 91.189.91.23 80] ==> default: Failed to fetch http://us.archive.ubuntu.com/ubuntu/pool/main/libj/libjpeg-turbo/libjpeg-turbo8_1.1.90+svn733-0ubuntu4.1_amd64.deb 404 Not Found [IP: 91.189.91.23 80] ==> default: Failed to fetch http://us.archive.ubuntu.com/ubuntu/pool/main/libx/libxslt/libxslt1.1_1.1.26-8ubuntu1.1_amd64.deb 404 Not Found [IP: 91.189.91.23 80] ==> default: E ==> default: : ==> default: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing? ==> default: nginx: unrecognized service ==> default: cp: ==> default: cannot create regular file `/etc/nginx/sites-available/default' ==> default: : No such file or directory ==> default: chmod: ==> default: cannot access `/etc/nginx/sites-available/default' ==> default: : No such file or directory ==> default: ln: ==> default: failed to create symbolic link `/etc/nginx/sites-enabled/default' ==> default: : No such file or directory ==> default: nginx: unrecognized service the code for bootstrap.sh: #!/usr/bin/env bash #nginx sudo apt-get -y install nginx sudo service nginx start #set up nginx server sudo cp /vagrant/.provision/nginx/nginx.conf /etc/nginx/sites-available/default sudo chmod 644 /etc/nginx/sites-available/default sudo ln -s /etc/nginx/sites-available/default /etc/nginx/sites-enabled/default sudo service nginx restart #clean /var/www sudo rm -Rf /var/www #symlink /var/www => /vagrant ln -s /vagrant /var/www Any assistance you could provide here would be greatly appreciated. Thank you. A: you should update the repo before running the install with apt-get update #!/usr/bin/env bash #nginx sudo apt-get update sudo apt-get -y install nginx sudo service nginx start #set up nginx server sudo cp /vagrant/.provision/nginx/nginx.conf /etc/nginx/sites-available/default sudo chmod 644 /etc/nginx/sites-available/default sudo ln -s /etc/nginx/sites-available/default /etc/nginx/sites-enabled/default sudo service nginx restart #clean /var/www sudo rm -Rf /var/www #symlink /var/www => /vagrant ln -s /vagrant /var/www note you did not specify how you're running the provisioning from Vagrantfile but if you have something as config.vm.provision "shell", path: "bootstrap.sh" then the script runs as root and you dont need the sudo part in your script
{ "pile_set_name": "StackExchange" }
Q: Encoding: TypeError: write() argument must be str, not bytes I have a rudimentary grasp of python but am not clear on dealing with binary encoding issues. I am trying to run sample code from a firefox-webextensions example in which a python script sends text that is read by a javascript program. I keep encountering encoding errors. The python code is: #! /Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 import sys, json, struct text = "pong" encodedContent = json.dumps(text) encodedLength = struct.pack('@I', len(encodedContent)) encodedMessage = {'length': encodedLength, 'content': encodedContent} sys.stdout.write(encodedMessage['length']) sys.stdout.write(encodedMessage['content']) The error trace (displayed in firefox console) is: stderr output from native app chatX: Traceback (most recent call last): stderr output from native app chatX: File "/Users/inchem/Documents/firefox addons/py/chatX.py", line 10, in <module> stderr output from native app chatX: sys.stdout.write(encodedMessage['length']) stderr output from native app chatX: TypeError: write() argument must be str, not bytes Running python 3.5.1 on OS X El Capitan 10.11.6, x86 64bit cpu; firefox developer ed 52.0 The python script I am using, as shown above, is minimized from the original at https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Native_messaging I also tried: sys.stdout.buffer.write(encodedMessage['length']) sys.stdout.buffer.write(encodedMessage['content']) which generated: stderr output from native app chatX: sys.stdout.buffer.write(encodedMessage['content']) stderr output from native app chatX: TypeError: a bytes-like object is required, not 'str' A: The example was probably Python 2-compliant, but things have changed in Python 3. You are generating a binary representation of the length as bytes with this: encodedLength = struct.pack('@I', len(encodedContent)) It is not printable. You can write it through a socket stream which is a binary stream but not through stdout which is a text stream. The trick of using buffer (as explained in How to write binary data in stdout in python 3?) is good but only for the binary part (note that you get the error message for the text part now): sys.stdout.buffer.write(encodedMessage['length']) For the text part, just write to stdout: sys.stdout.write(encodedMessage['content']) or use sys.stdout.buffer with string to bytes conversion: sys.stdout.buffer.write(bytes(encodedMessage['content'],"utf-8"))
{ "pile_set_name": "StackExchange" }
Q: Dynamically size uitableViewCell according to UILabel (With paragraph spacing) I have a UITableView which is populated by text and images from a JSON file. The TableView Cell is currently sizing correctly for "posts" that do not contain many line breaks in the text however I cannot get it to calculate the correct height for "posts" with 4 or 5 line breaks. Code for getting height: -(float)height :(NSMutableAttributedString*)string { NSString *stringToSize = [NSString stringWithFormat:@"%@", string]; CGSize constraint = CGSizeMake(LABEL_WIDTH - (LABEL_MARGIN *2), 2000.f); CGSize size = [stringToSize sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:contraint lineBreakMode:NSLineBreakByWordWrapping]; return size.height; } How do I calculate the correct size while allowing for line breaks and white space? EDIT The Rest of the method, Inside of TableView CellForRow: -(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *row = [NSString stringWithFormat:@"%i", indexPath.row]; float postTextHeight = [self height:postText]; NSString *height = [NSString stringWithFormat:@"%f", heightOfPostText + 70]; [_cellSizes setObject:height forKey:row]; } And the height of Table Cell: -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *imageHeightString = [NSString stringWithFormat:@"%@", [_cellSizes objectForKey:indexPath.row]]; float heightOfCell = [imageHeightString floatValue]; if (heightOfCell == 0) { return 217; }; return heightOfCell + 5; } A: better u need to calculate the height first, don't include the height calculation part in method: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath Better to calculate it in method: - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath since u are getting the data from json it is easy for u to calculate in the "heightForRowAtIndexPath" method. follwing code will give the example to calculate height of text change it ur requirement. hopee this helps u :) // i am using an array - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. UIFont *labelFont = [UIFont fontWithName:@"Noteworthy-Bold" size:20]; NSDictionary *arialdict = [NSDictionary dictionaryWithObject:labelFont forKey:NSFontAttributeName]; NSMutableAttributedString *message = [[NSMutableAttributedString alloc] initWithString:@"this is just the sample example of how to calculate the dynamic height for tableview cell which is of around 7 to 8 lines. you will need to set the height of this string first, not seems to be calculated in cellForRowAtIndexPath method." attributes:arialdict]; array = [NSMutableArray arrayWithObjects:message, nil]; NSMutableAttributedString *message_1 = [[NSMutableAttributedString alloc] initWithString:@"you will need to set the height of this string first, not seems to be calculated in cellForRowAtIndexPath method." attributes:arialdict]; [array addObject:message_1]; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 2; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 2; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *Cell = [self.aTableView dequeueReusableCellWithIdentifier:@"cell"]; if(Cell == nil) { Cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]; } //dont include the height calculation part hear, becz heights are already set for all the cell [Cell.textLabel sizeToFit]; Cell.textLabel.attributedText = [array objectAtIndex:indexPath.row]; // dont calculate height hear it will be called after "heightForRowAtIndexPath" method Cell.textLabel.numberOfLines = 8; return Cell; } // put ur height calculation method i took some hardcoded values change it :) -(float)height :(NSMutableAttributedString*)string { /* NSString *stringToSize = [NSString stringWithFormat:@"%@", string]; // CGSize constraint = CGSizeMake(LABEL_WIDTH - (LABEL_MARGIN *2), 2000.f); CGSize maxSize = CGSizeMake(280, MAXFLOAT);//set max height //set the constant width, hear MAXFLOAT gives the maximum height CGSize size = [stringToSize sizeWithFont:[UIFont systemFontOfSize:20.0f] constrainedToSize:maxSize lineBreakMode:NSLineBreakByWordWrapping]; return size.height; //finally u get the correct height */ //commenting the above code because "sizeWithFont: constrainedToSize:maxSize: lineBreakMode: " has been deprecated to avoid above code use below NSAttributedString *attributedText = string; CGRect rect = [attributedText boundingRectWithSize:(CGSize){225, MAXFLOAT} options:NSStringDrawingUsesLineFragmentOrigin context:nil];//you need to specify the some width, height will be calculated CGSize requiredSize = rect.size; return requiredSize.height; //finally u return your height } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { //whatever the height u need to calculate calculate hear only CGFloat heightOfcell = [self height:[array objectAtIndex:indexPath.row]]; NSLog(@"%f",heightOfcell); return heightOfcell; } Hope this helps u :) For SWIFT version class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { var messageArray:[String] = [] //array to holde the response form son for example override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. messageArray = ["One of the most interesting features of Newsstand is that once an asset downloading has started it will continue even if the application is suspended (that is: not running but still in memory) or it is terminated. Of course during while your app is suspended it will not receive any status update but it will be woken up in the background", "In case that app has been terminated while downloading was in progress, the situation is different. Infact in the event of a finished downloading the app can not be simply woken up and the connection delegate finish download method called, as when an app is terminated its App delegate object doesn’t exist anymore. In such case the system will relaunch the app in the background.", " If defined, this key will contain the array of all asset identifiers that caused the launch. From my tests it doesn’t seem this check is really required if you reconnect the pending downloading as explained in the next paragraph.", ] } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1; } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messageArray.count; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell; if(cell == nil) { cell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier: "CELL") cell?.selectionStyle = UITableViewCellSelectionStyle.None } cell?.textLabel.font = UIFont.systemFontOfSize(15.0) cell?.textLabel.sizeToFit() cell?.textLabel.text = messageArray[indexPath.row] cell?.textLabel.numberOfLines = 0 return cell!; } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var height:CGFloat = self.calculateHeightForString(messageArray[indexPath.row]) return height + 70.0 } func calculateHeightForString(inString:String) -> CGFloat { var messageString = inString var attributes = [UIFont(): UIFont.systemFontOfSize(15.0)] var attrString:NSAttributedString? = NSAttributedString(string: messageString, attributes: attributes) var rect:CGRect = attrString!.boundingRectWithSize(CGSizeMake(300.0,CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, context:nil ) var requredSize:CGRect = rect return requredSize.height //to include button's in your tableview } }
{ "pile_set_name": "StackExchange" }
Q: Android Need to set image from gallery as paint canvas background I want to set an image from gallery as a background to the canvas in fingerpaint (api demo sample). I can retrieve the image from gallery but not able to set that as a background. One guess is I can open the image as a input stream, convert that as a array and pass it for bitmap - but I am not sure whether it will work or not and i don't have any clue for how the code will be. Can somebody help me? A: You can modify the onSizeChanged() function to, protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); BitmapFactory.Options decode_options = new BitmapFactory.Options(); decode_options.inMutable = true; mBitmap = BitmapFactory.decodeFile(<file_path>,decode_options); mCanvas = new Canvas(mBitmap); mBitmapPaint.setXfermode(new PorterDuffXfermode (SRC_IN)); }
{ "pile_set_name": "StackExchange" }
Q: lstinputlistings syntax highlighting I am using package listings to import my Python source code into my LaTeX document. I use the command \lstinputlistings. I have a Python source like class MyClass(Yourclass): def __init__(self, myvar, yours): bla bla bla... What should I write in my \lstset command in order to enlight words MyClass, init etc.? I wouldn't want to write any word I want to be highlighted. I tried using moredelims=[s][\color{teal}]{class}{(} inside lstset but it doesn't work. And why is morekeywords={...} not working with lstinputlistings. It does with lstlistings environment, but doesn't with input from a source file. A: It is always good to post a minimal and compilable example, not just code snippets. This way, the answerers do not have to guess what's happening with your problem. I guess that you are looking for something like this. \documentclass{article} \usepackage{listings} \usepackage{xcolor} \lstset{language=Python, morekeywords={as,__init__,MyClass}, keywordstyle=\color{teal}\bfseries, } \begin{document} \lstinputlisting{guess.py} \end{document} where guess.py is your sample code snippet. I just added as on the last line to show that morekeywords works. class MyClass(Yourclass): def __init__(self, myvar, yours): bla bla bla... as Here is the output. You can also remove __init__ from morekeywords option and use the answers in How to I emphazise all words beginning with ` in an lstlisting and Listings language definition keyword suffixes. So you may put the following code snippet into your preamble. \lstset{language=Python, morekeywords={as,MyClass}, keywordstyle=\color{teal}\bfseries, keywordsprefix=_, } Let me know if this works for you.
{ "pile_set_name": "StackExchange" }
Q: Constructing Icosahedral Fullerene Graphs I am interested in constructing graphs of icosahedral fullerenes, following the construction explained in the first few pages of this article (alternate link). Mathematica has built-in information about the 60-site graph, $C_{60}$, in GraphData["TruncatedIcosahedralGraph"] and ChemicalData["Fullerene60"] and information about the 20-site dodecahedron, but there's a whole zoo of icosahedral fullerenes. First, I construct an underlying hexagonal grid of ions: Li = 10; Lj = 10; offset = {-3 - 1/2, Sqrt[3]/2}; a1 = {3/2, +Sqrt[3]/2}; a2 = {3/2, -Sqrt[3]/2}; ions = Flatten[Outer[offset + #1 a1 + #2 a2 + #3 (a1 + a2)/3 &, Range[-Li, Li], Range[-Lj, Lj], {0, 1} (* A/B shift comes last to ensure even/odd sites alternate *)], 2]; with a face centered on the origin. Then I compute the locations of the pentagonal defects: Gi = 1; Gj = 2; b1 = {3/2, Sqrt[3]/2}; b2 = {0, Sqrt[3]}; upRight = {+1, +1} Gj b2 + {+1, -1}*Gi b1; downRight = {+1, -1} Gi b2 + {+1, +1}*Gj b1 - upRight; horizontal = upRight + downRight; pentagonCenters = Flatten[{# horizontal, # horizontal + upRight, # horizontal + 2 upRight, # horizontal + downRight} & /@ Range[0, 4], 1] ~Join~ {5 horizontal, 5 horizontal + upRight}; So that you can visually see what I've got, Show[ListPlot[{ions, pentagonCenters}, AspectRatio -> 1, PlotRange -> {{0, 20}, {-10, 10}}, PlotMarkers -> ({#, Large} & /@ {\[FilledSmallCircle], ★})], Graphics[Line /@ (pentagonCenters[[#]] & /@ { {1, 3}, {4, 7}, {8, 11}, {12, 15}, {16, 19}, {20, 22}, {1, 4}, {2, 8}, {3, 12}, {7, 16}, {11, 20}, {15, 21}, {19, 22}, {1, 21}, {2, 22}})] ] which, for Gi = 1; Gj = 2 yields the $C_{60}$ graph where the blue circles are locations of the ions and the stars will be the centers of the pentagonal defects. The triangles with stars as their vertices are the faces of the icosahedron. Running again with Gi=1;Gj=3 yields a 170-ion graph My questions are all aimed at constructing the adjacency matrix for these icosahedral fullerenes. How can I easily "cut out" the ions that aren't inside the black triangles. Also: the sites I generate are definitely too many... [EDIT]: This can be accomplished with by construction a region: region = Region[Polygon[pentagonCenters[[ {1, 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 21, 20, 17, 16, 13, 12, 9, 8, 5, 4}]]]]; and then using RegionMember. I still have to pick Li and Lj large enough to cover the area of interest. [Updated question]: how can I just generate the "needed" hexagonal grid to begin with, or just the needed ones plus a little extra, that can then be discarded via RegionMember? How can I "stitch up" the sides of the black triangles? On a hexagonal grid I can detect if two ions are nearest neighbors by seeing if the Norm of the difference of their locations differ by 1. How should I make these identifications in an easy, programmatic way that Mathematica will understand? Bonus: In an ideal world, I'd know the geometrical locations of all of these ions when the graph is thought of as a polyhedron. Is there something relatively automatic I can do to get at this information? [EDIT: once I have a Graph object I can cast to a Graph3D and use AbsoluteOptions[ graph3D, VertexCoordinates] to get the locations.] Note that sometimes ions land exactly on the sides of the black triangles (as in the Gi=1;Gj=2 case). A: Jason B gave a hint to the tool buckygen. This tool is easily downloaded, unpacked and compiled (by running make in the unpacked folder). Assuming that the compiled executable of buckygen is contained in the subfolder buckygen-1.0 of folder Downloads of the current user (and maybe also assuming that you run this on a unixoid OS), you can run buckygen and import the results with the following tiny program. It generates all fullerenes with vertex count between m and n. Also some but not all options of buckygen got translated into Mathematica options. ClearAll[getBucky]; getBucky[m_Integer, n_Integer, OptionsPattern[{ "Dual" -> False, "IPROnly" -> False, "Statistics" -> False, "Verbose" -> True }] ] := Module[{file, runstring, path, data, time}, path = FileNameJoin[{$HomeDirectory, "Downloads", "buckygen-1.0"}]; file = FileNameJoin[{path, "FullerDump.g6"}]; runstring = StringJoin[{"! ", FileNameJoin[{path, "buckygen"}], " -s", If[OptionValue["Dual"], " -d", ""], If[OptionValue["IPROnly"], " -I", ""], If[OptionValue["Statistics"], " -v", ""], If[! OptionValue["Verbose"], " -q", ""], " -S", ToString[m], " ", ToString[n], " ", file, " 2>&1 &"}]; Print[Import[runstring, "Text"]]; Print["Importing ", file, "..."]; time = AbsoluteTiming[data = Import[file, "Sparse6"];][[1]]; Print["Time elapsed for import: ", time, "."]; Flatten[{data}] ] A usage example: data = getBucky[20,20]; GraphicsGrid[Partition[data, 6, 6, {1, 1}, Graphics[]], ImageSize -> Full] The dual graphs can be obtained with data = getBucky[20, 20, "Dual" -> True]; GraphicsGrid[Partition[data, 6, 6, {1, 1}, Graphics[]], ImageSize -> Full] The graphs are imported as a list of Mathematica Graph objects. (I am using version 11.0.1 and do not know what happens for legacy versions of Mathematica.) For example, you can obtain the AdjacencyMatrix of the first fullerene in the list with AdjacencyMatrix[data[[1]]]. Or you can obtain planar embeddings with PlanarGraph: GraphicsGrid[Partition[PlanarGraph /@ data, 6, 6, {1, 1}, Graphics[]], ImageSize -> Full] If the executable is located somewhere else, adjust the variable path in the program to your needs. If you would like to use other options of buckygen, you merely have to adjust the variable runstring to your needs. What's really bugging me is that Import for Sparse6 is very, very slow. Maybe, someone else knows an improvement.
{ "pile_set_name": "StackExchange" }
Q: Parent association for embedded document using MongoMapper If I have: class Post include MongoMapper::Document has_many :comments end If I do: class Comment include MongoMapper::EmbeddedDocument belongs_to :post # relevant part end Does that create an association using _root_document/_parent_document, or do I have to add the (redundant) key :post_id? A: You do not need post_id or belongs_to :post. Instead, you can use embedded_in :post. This will make a read method for _parent_reference named post so you can say comment.post instead of comment._parent_reference. class Comment include MongoMapper::EmbeddedDocument embedded_in :post end
{ "pile_set_name": "StackExchange" }
Q: Kentico sync 404 error on large files I have some large video files that are causing a 404 sync error. I know it's due to the size. I've done some digging and found this great article: http://www.mcbeev.com/Blog/September-2012/Kentico-CMS-Quick-Tip-Content-Staging-and-Large-Files My media library is in /kff/media with the appropriate subfolders for the media libraries. I have added the following to my web.config. Right now, my biggest file is around 90meg, but i'm expecting larger video files. But i'm still getting errors. <!-- Sales Force Resourse Site Start --> <location path="KFF/media"> <system.web> <httpRuntime executionTimeout="2400" maxRequestLength="2097151"/> </system.web> <system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="2147483648"/> </requestFiltering> </security> </system.webServer> </location> <!-- Sales Force Resourse Site End --> A: You need to update your main web.config for this, not a web.config in the media directory. You'd set your maxRequestLength = 100000. I should mention the default value of 2097152 is over 2GB so you should be fine. Or you can use a simple converter to do the work.
{ "pile_set_name": "StackExchange" }
Q: Retrieve create node form. Why cant save send values? I want to add a custom page for creating "blog post". Ive got a node blog. So I write something like this: function module_menu() { $items = array(); $items['user/%/edit/blog/add'] = array( 'title' => 'Add blog post', 'page callback' => 'drupal_get_form', 'page arguments' => array('module_add_blog',1), 'access arguments' => array('createBlog'), 'type' => MENU_CALLBACK, ); return $items; } And then in module_add_blog callback: function module_add_blog(&$form_state, $arg) { $form = array(); $id = intval($arg); if ($id == 0){ drupal_set_message('ID must be an integer.' , '$error'); return; } $user = user_load($id); module_load_include('inc', 'node', 'node.pages'); $node = array('uid' => $user->uid, 'name' => $user->name, 'type' => 'blog'); $form = drupal_retrieve_form('blog_node_form', $form_state, $node); drupal_prepare_form('blog_node_form', $form, $form_state); return $form; } Form is rendered in path user/1/edit/blog/add but when I send data it is NOT SAVED. Any ideas how fix it? Thanks A: I think you're confusing Drupal by having a form within a form so-to-speak. I think it would be a lot easier to define a proxy function for the node form so you don't need to worry about doing so: function module_menu() { $items['user/%/edit/blog/add'] = array( 'title' => 'Add blog post', 'page callback' => 'module_blog_form_proxy', 'page arguments' => array(1), 'access arguments' => array('createBlog'), 'type' => MENU_CALLBACK, ); return $items; } function module_blog_form_proxy($uid) { // Validitiy checks etc... $user = user_load($uid); $node = array('uid' => $user->uid, 'name' => $user->name, 'type' => 'blog'); module_load_include('inc', 'node', 'node.pages'); return drupal_get_form('blog_node_form', $node); }
{ "pile_set_name": "StackExchange" }
Q: Infinite Knight's Tour Does there exists a one-to-one and onto map $f:\mathbb{N}\rightarrow \mathbb{Z}[i]$ such that $|f(n+1)-f(n)|=\sqrt{5}$? That is to get from $f(n)$ to $f(n+1)$ you have to move like a knight in chess: move two vertically and then one horizontally or two horizontally and then one vertically. I know there is a lot written about when a knight tour is possible on a finite board. Check out the wiki and wolfram for some background. I can see how you might be able to do this in a type of infinite outward spiral if you could travel down a corridor of an arbitrary length. It seems that there is already some interest in that. But you would also need to make sure that you "end" your journey on the far side of the corridor in such a way that you could turn to travel down the next corridor. Motivation: The key part of my question is the infinite part. I have recently been thinking about how we can traverse infinite spaces which is particularly relevant to mathematicians (as opposed to say computer scientists). For example when computing something over the entire set of Guassian integers. Let's say that some function $f$ does exist. Then $$\sum_{z\in \mathbb{Z}[i]} \alpha_z =\sum_{n=1}^\infty \alpha_{f(n)}$$ I am not sure that such a thing could practically be done. But my point is that it's valuable to know different ways we can traverse infinite spaces. A: Too long for a comment. Also, sorry for overturning my claims over and over. I was careless when looking at the image and fooled twice. According to this article, it seems that an infinite knight's tour on $\mathbb{Z}^2$ exists: $\hspace{9em}$ The following image shows both the path and the order of visit of each cell. $\hspace{9em}$
{ "pile_set_name": "StackExchange" }
Q: Inline div's rows messed up I'm having an issue that I don't know why is this, but I created 3 ids on CSS named first, second, and third and aligned them to left to be all inline with a 320px width. Now I'm trying to put the same divs on a second row inline as well but they are messing up. The second row starts in the middle of the page, and only the third one displays the right way. The first one starts on the left, the next one starts in the middle of the page, and the next one starts on the left as well and so on... Here's the JSFiddle file: Example You have to expand the Result box to the left to the max width so you can see what I'm talking about. html: <a href="#"> <div id="first" align="left"><img src="http://www.main-hosting.com/hostinger/welcome/index/folder.png"><strong> Empty-Field/</strong></div> <div id="second">-</div> <div id="third" align="right">Last Update - January 0, 2014 00:00:00</div> </a> <a href="#"> <div id="first" align="left"><img src="http://www.main-hosting.com/hostinger/welcome/index/folder.png"><strong> Empty-Field/</strong></div> <div id="second">-</div> <div id="third" align="right">Last Update - January 0, 2014 00:00:00</div> </a> CSS: #first { width:320px; float:left; } #second { width:320px; float:left; } #third { width:320px; float:left; } A: demo: http://jsfiddle.net/vyxN4/6/ <a class="fll" href="#"> <div id="first" align="left"><img src="http://www.main-hosting.com/hostinger/welcome/index/folder.png"><strong> Empty-Field/</strong></div> <div id="second">-</div> <div id="third" align="right">Last Update - January 0, 2014 00:00:00</div> </a><div class="clear"></div> <a class="fll" href="#"> <div id="first" align="left"><img src="http://www.main-hosting.com/hostinger/welcome/index/folder.png"><strong> Empty-Field/</strong></div> <div id="second">-</div> <div id="third" align="right">Last Update - January 0, 2014 00:00:00</div> </a><div class="clear"></div> <a class="fll" href="#"> <div id="first" align="left"><img src="http://www.main-hosting.com/hostinger/welcome/index/folder.png"><strong> Empty-Field/</strong></div> <div id="second">-</div> <div id="third" align="right">Last Update - January 0, 2014 00:00:00</div> </a><div class="clear"></div> <a class="fll" href="#"> <div id="first" align="left"><img src="http://www.main-hosting.com/hostinger/welcome/index/folder.png"><strong> Empty-Field/</strong></div> <div id="second">-</div> <div id="third" align="right">Last Update - January 0, 2014 00:00:00</div> </a><div class="clear"></div> <a class="fll" href="#"> <div id="first" align="left"><img src="http://www.main-hosting.com/hostinger/welcome/index/folder.png"><strong> Empty-Field/</strong></div> <div id="second">-</div> <div id="third" align="right">Last Update - January 0, 2014 00:00:00</div> </a> css #first, #second, #third, .fll { float:left; } .clear:{ clear: both; } A: Use classes instead of ids, chances are your browser doesn't like your invalid markup. IDs are for unique elements used once. Classes are for multiple use. You also have to handle the float properly. By adding a clear: both; after each line you stop this "second row in the middle"-thing. Try this: <a href="#"> <div class="first" align="left"><img src="http://www.main-hosting.com/hostinger/welcome/index/folder.png"><strong> Empty-Field/</strong></div> <div class="second">-</div> <div class="third" align="right">Last Update - January 0, 2014 00:00:00</div> </a> <br class="clear" /> <a href="#"> <div class="first" align="left"><img src="http://www.main-hosting.com/hostinger/welcome/index/folder.png"><strong> Empty-Field/</strong></div> <div class="second">-</div> <div class="third" align="right">Last Update - January 0, 2014 00:00:00</div> </a> And CSS: .first { width:320px; float:left; } .second { width:320px; float:left; } .third { width:320px; float:left; } .clear { clear: both; }
{ "pile_set_name": "StackExchange" }
Q: MySQL pivot data I have data. A, STATUS, P A1, 1, P1 A1, 1, P2 A1, 1, P3 A2, 1, P3 A2, 1, P4 A2, 1, P5 A3, 0, NULL I want result same P, A1, A2, A3 P1, 1, 0, 0 P2, 1, 0, 0 P3, 1, 1, 0 P4, 0, 1, 0 P5, 0, 1, 0 How can I do it with mysql query? A: Try this;) select `P`, max(if(`A` = 'A1', `STATUS`, 0)) as `A1`, max(if(`A` = 'A2', `STATUS`, 0)) as `A2`, max(if(`A` = 'A3', `STATUS`, 0)) as `A3` from table1 where `P` IS NOT NULL group by `P` DEMO HERE Edited: SET @sql = NULL; SELECT GROUP_CONCAT(DISTINCT CONCAT( 'MAX(IF(`A` = ''', `A`, ''', `STATUS`, 0)) AS ', `A` ) ) INTO @sql FROM table1; SET @sql = CONCAT('SELECT `P`, ', @sql, ' FROM table1 WHERE `P` IS NOT NULL GROUP BY `P`'); PREPARE stmt FROM @sql; EXECUTE stmt; DEMO HERE
{ "pile_set_name": "StackExchange" }
Q: Why does Rust promote use statements with explicit imports? I see a lot of Rust code where the use statements look like this: use std::io::net::ip::{SocketAddr, Ipv4Addr}; The way I get it, this restricts the use statement to only import SocketAddr and Ipv4Addr. Looking from the perspective of languages such as Java or C# this feels odd as with such languages an import statement always imports all public types. I figured one can have the same in Rust using this statement. use std::io::net::ip::*; The only reason I could see for the explicit naming would be to avoid conflicts where two different imports would contain public APIs with the same names. However, this could be worked around with aliasing so I wonder if there's another advantage of the more strict "import only what is needed" approach? A: Rust is in this inspired by Python, which has a similar principle: importing is all explicit, and though glob imports (use x::* in Rust, from x import * in Python) are supported, they are not generally recommended. This philosophy does have some practical impacts; calling a trait method, for example, can only be done if the trait is in scope, and so calling a trait method when there are name collisions in the imported traits is rather difficult (this will be improved in the future with Uniform Function Call Syntax, where you can call Trait::function(self) rather than just self.function()). Mostly, though, it is something that is well expressed in the Zen of Python: "explicit is better than implicit". When vast swathes of things are in scope, it can be difficult to see what came from where, and intimate knowledge of the module structure, and/or tooling becomes quite important; if it is all explicit, tooling is largely unnecessary and working with files by hand in a simple text editor is entire feasible. Sure, tooling will still be able to assist, but it is not as necessary. This is why Rust has adopted Python's explicit importing philosophy. A: Mailing list thread asking why glob imports are not preferred in which Huon writes Certain aspects of them dramatically complicate the name resolution algorithm (as I understand it), and, anyway, they have various downsides for the actual code, e.g. the equivalent in Python is frowned upon: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#importing Maybe they aren't so bad in a compiled & statically typed language? I don't know; either way, I personally find code without glob imports easier to read, because I can work out which function is being called very easily, whereas glob imports require more effort. Issue to remove glob imports where nikomatsakis writes I think glob imports have their place. For example, in the borrow checker, there is a shallow tree of submodules that all make use of data types defined in borrowck/mod.rs. It seems rather tedious and silly to require manual importing of all these names, vs just writing use rustc::middle::borrowck::*. I know that there are complications in the resolution algorithm, though, and I would be more amenable to an argument based on fundamental challenges there. This then moved to RFC 305 which was rejected by steveklabnik without comment on whether they're good style: Glob imports are now stable, and so I'm going to give this a close.
{ "pile_set_name": "StackExchange" }
Q: Check whether any of the strings from one column match any of the strings from another column I have a situation like this: lst = ["Apple", "Apple", "Apple small", "Orange", "FruitX", "FruitY"] lst2 = ["Apple", "Orange", "Fruit1", "Fruit2"] Where lst and lst2 are pandas series (or columns in a dataframe I should say). I need to find which of the values from lst2 are in lst and in the end create a dataframe with the results as follows (ideally with the number of matched values and with the ability to also add other columns from lst (): lst2 lst match_count other_colum_from_lstDF other_colum_from_lstDF Apple Apple 2 info1 info2 Apple Apple 2 info1 info2 Orange Orange 1 info1 info2 Fruit1 nan 0 nan nan Fruit2 nan 0 nan nan So you can match multiple values from lst to one value from lst2, so I would need the results duplicated as per above, ideally with the number of matched values. I think the right way would be to use isin but wasn't able to figure out how. A: Use pd.merge: df_merge = pd.merge(df2, df1, how = 'left', left_on = 'lst2', right_on = 'lst') df_merge['match_count'] = df_merge.groupby(['lst'])['lst'].transform('count').fillna(0) df_merge = df_merge[['lst2','lst','match_count','info1']] Output is: lst2 lst match_count info1 0 Apple Apple 2.0 info1 1 Apple Apple 2.0 info1 2 Orange Orange 1.0 info1 3 Fruit1 NaN 0.0 NaN 4 Fruit2 NaN 0.0 NaN
{ "pile_set_name": "StackExchange" }
Q: problem solving using quadratics Ralph is mowing a yard 16 m long and 12 m wide. He mows continuously around the yard working towards the centre. He wonders how wide a strip must be cut before he is half done. A: I'm going to assume that the problem intends the following: Of a 16-by-12 rectangle, a border of width $x$ is shaded. If the area of the shaded border is equal to the unshaded rectangular region in the middle, what is $x$? Under that interpretation, the unshaded rectangle in the middle has dimensions $16-2x$ and $12-2x$, so area $(16-2x)(12-2x)$, and should have half the area of the original rectangle, so $$(16-2x)(12-2x)=\frac{1}{2}\cdot 16\cdot 12.$$ Solving gives $x=2$ or $x=12$ (which is out of range given the context), so a border of width 2 m.
{ "pile_set_name": "StackExchange" }
Q: Where to find Screen pinning option in GenyMotion emulator? As android Introduces Screen Pinning in Android 5.0 and higher, I want to access that feature in Genymotion virtual device but I can't find any option in dev setting, anybody have any idea how to find this feature in Genymotion device. A: As this site says you can go into Settings->Security and you will see this: and then when you press the overview button(recent apps button) you will come up with this screen: able to pin anything you want. But if you want to get out of the Pinned Screen you will have to press back button and overview button at the same time and i dont know how you do this in genymotion. Hope it helps!!!
{ "pile_set_name": "StackExchange" }
Q: updating label text in kivy on load I'm brand new to kivy, and trying to build small OSD for my raspberry. My .kv file looks like this: BoxLayout: orientation: 'vertical' Label: text_size: self.size text: 'OSD' font_size: 50 bold: True halign: 'center' valign: 'top' size_hint: 1, .3 GridLayout: cols: 2 Label: text_size: self.size text: 'Total entries in DB: ' font_size: 30 bold: False halign: 'left' size_hint: 1, .1 Label: id: total_db text_size: self.size text: '366 000 ' font_size: 30 bold: True color: 0, 1, 0, 1 halign: 'center' size_hint: 1, .1 Label: text_size: self.size text: 'Info 1: ' font_size: 30 bold: False halign: 'left' size_hint: 1, .1 Label: id: marked_update text_size: self.size text: '1328 ' color: 1, 0, 0, 1 font_size: 30 bold: True halign: 'center' size_hint: 1, .1 Label: text_size: self.size text: 'Activity' font_size: 50 bold: True halign: 'center' valign: 'top' size_hint: 1, .3 Label: text: '' font_size: 10 halign: 'center' valign: 'top' size_hint: 1, .08 GridLayout: cols: 4 Button: text: 'DS 01' font_size: 25 background_color: 1, 0, 0, 1 Button: text: 'DS 02' font_size: 25 background_color: 0, 1, 0, 1 Button: text: 'DS 03' font_size: 25 background_color: 0, 1, 0, 1 Button: text: 'DS 04' font_size: 25 background_color: 0, 1, 0, 1 This produce the look I want. I wan to periodically update the two labels texts with IDs with values I extract later on... but I can't even update them from python which looks like this: import kivy kivy.require('1.10.1') from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kivy.clock import Clock class BoxLayout(BoxLayout): def __init__(self, **kwargs): super(BoxLayout, self).__init__(**kwargs) Clock.schedule_once(self.update_txt, 0) def update_txt(self, *args): self.label.ids.marked_update.txt='updated from python' class osdApp(App): def build(self): self.title = 'OSD' return BoxLayout() if __name__ == '__main__': osdApp().run() I was thinking to start clock that calls the update_txt function and that could change the value, but I keep getting error that ids does not exists... and so on, I'm bread new to object oriented programming and I can't figure this simple thing out A: A few observations: As comments @eyllanesc, you shouldn't name your subclasses as the class that it inherits. self.label.ids.marked_update.txt is incorrect. It should be self.ids.marked_update.text. Declare your root widget as a kv rule. Your code could be: main.py import kivy kivy.require('1.10.0') from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.clock import Clock class RootWidget(BoxLayout): def __init__(self, **kwargs): super(BoxLayout, self).__init__(**kwargs) Clock.schedule_once(self.update_txt, 0.1) def update_txt(self, *args): self.ids.marked_update.text = 'updated from python' class OsdApp(App): def build(self): self.title = 'OSD' return RootWidget() if __name__ == '__main__': OsdApp().run() osd.kv: <RootWidget>: orientation: 'vertical' Label: text_size: self.size text: 'OSD' font_size: 50 bold: True halign: 'center' valign: 'top' size_hint: 1, .3 GridLayout: cols: 2 Label: text_size: self.size text: 'Total entries in DB: ' font_size: 30 bold: False halign: 'left' size_hint: 1, .1 Label: id: total_db text_size: self.size text: '366 000 ' font_size: 30 bold: True color: 0, 1, 0, 1 halign: 'center' size_hint: 1, .1 Label: text_size: self.size text: 'Info 1: ' font_size: 30 bold: False halign: 'left' size_hint: 1, .1 Label: id: marked_update text_size: self.size text: '1328 ' color: 1, 0, 0, 1 font_size: 30 bold: True halign: 'center' size_hint: 1, .1 Label: text_size: self.size text: 'Activity' font_size: 50 bold: True halign: 'center' valign: 'top' size_hint: 1, .3 Label: text: '' font_size: 10 halign: 'center' valign: 'top' size_hint: 1, .08 GridLayout: cols: 4 Button: text: 'DS 01' font_size: 25 background_color: 1, 0, 0, 1 Button: text: 'DS 02' font_size: 25 background_color: 0, 1, 0, 1 Button: text: 'DS 03' font_size: 25 background_color: 0, 1, 0, 1 Button: text: 'DS 04' font_size: 25 background_color: 0, 1, 0, 1 However, I recommend using kivy properties instead of ids: main.py: import kivy kivy.require('1.10.0') from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.properties import StringProperty class RootWidget(BoxLayout): marked_text = StringProperty() def __init__(self, **kwargs): super(BoxLayout, self).__init__(**kwargs) self.update_txt() def update_txt(self, *args): self.marked_text ='updated from python' class OsdApp(App): def build(self): self.title = 'OSD' return RootWidget() if __name__ == '__main__': OsdApp().run() osd.kv: <RootWidget>: id: root_layout orientation: 'vertical' marked_text: '1328 ' Label: text_size: self.size text: 'OSD' font_size: 50 bold: True halign: 'center' valign: 'top' size_hint: 1, .3 GridLayout: cols: 2 Label: text_size: self.size text: 'Total entries in DB: ' font_size: 30 bold: False halign: 'left' size_hint: 1, .1 Label: id: total_db text_size: self.size text: '366 000 ' font_size: 30 bold: True color: 0, 1, 0, 1 halign: 'center' size_hint: 1, .1 Label: text_size: self.size text: 'Info 1: ' font_size: 30 bold: False halign: 'left' size_hint: 1, .1 Label: id: marked_update text_size: self.size text: root_layout.marked_text color: 1, 0, 0, 1 font_size: 30 bold: True halign: 'center' size_hint: 1, .1 Label: text_size: self.size text: 'Activity' font_size: 50 bold: True halign: 'center' valign: 'top' size_hint: 1, .3 Label: text: '' font_size: 10 halign: 'center' valign: 'top' size_hint: 1, .08 GridLayout: cols: 4 Button: text: 'DS 01' font_size: 25 background_color: 1, 0, 0, 1 Button: text: 'DS 02' font_size: 25 background_color: 0, 1, 0, 1 Button: text: 'DS 03' font_size: 25 background_color: 0, 1, 0, 1 Button: text: 'DS 04' font_size: 25 background_color: 0, 1, 0, 1
{ "pile_set_name": "StackExchange" }
Q: In Python, how do you find the index of the first value greater than a threshold in a sorted list? In Python, how do you find the index of the first value greater than a threshold in a sorted list? I can think of several ways of doing this (linear search, hand-written dichotomy,..), but I'm looking for a clean an reasonably efficient way of doing it. Since it's probably a pretty common problem, I'm sure experienced SOers can help! Thanks! A: Have a look at bisect. import bisect l = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] bisect.bisect(l, 55) # returns 7 Compare it with linear search: timeit bisect.bisect(l, 55) # 375ns timeit next((i for i,n in enumerate(l) if n > 55), len(l)) # 2.24us timeit next((l.index(n) for n in l if n > 55), len(l)) # 1.93us A: You might get a better time than the enumerate/generator approach using itertools; I think itertools provides faster implementations of the underlying algorithms, for the performance mongers in all of us. But bisect may still be faster. from itertools import islice, dropwhile threshold = 5 seq = [1,4,6,9,11] first_val = islice(dropwhile(lambda x: x<=threshold, seq),0,1) result = seq.index(first_val) I wonder about the difference between the bisect approach shown here and the one listed for your question in the doc examples, as far as idiom/speed. They show an approach for finding the value, but truncated to first line, it returns the index. I'd guess that since it's called "bisect_right" instead of "bisect," it probably only looks from one direction. Given that your list is sorted and you want greater-than, this might be the greatest search economy. from bisect import bisect_right def find_gt(a, x): 'Find leftmost value(switching this to index) greater than x' return bisect_right(a, x) Interesting question.
{ "pile_set_name": "StackExchange" }
Q: Setting the value of a model field based on user authentication in Django I'm trying to selectively process a field in my Django/Python application based on whether a user is logged in or not. Basically, I have a model similar to the following: class Resource(models.Model): uploaded = models.DateTimeField() name = models.CharField(max_length=200) description = models.CharField(max_length=500, blank=True) file = models.CharField(max_length=200) What I want to do is for the file attribute to be set to one value if the user happens to be logged in (and has access to this resource based on a test against some permissions backend), and another value if the user is not logged in. So, when any client code tries to access Resource.file, it will get something like the following if the user is not logged in 'http://mysite.com/dummy_resource_for_people_without_access'. However, if the user is logged in and passes some tests for permissions, then the value of resource.file will actually be the true url of that resource (including any security keys etc. to access that resource). From what I've read, it seems that you can only take account of the currently logged in user by passing that through the request context from a view function to the model. However, in the above use case I am trying to control the access more closely in the model without needing the client code to call a special function. A: Just in case anyone's interested, I solved the above issue by actually creating a custom model field in django that could then have a method that takes a user to generate a URI. So, in the database, I store a key to the resource as above in the file column. However, now the file column is some custom field: class CustomFileField(models.CharField): def to_python(self, value): ... return CustomFileResource(value) class CustomFileResource: def __init__(self, *args, **kwargs): .... def uri(usr): #this method then gets the uri selectively based on the user . The pattern above is nice because I can wrap the db field and then create a specific method for getting the uri based on who is trying to access it.
{ "pile_set_name": "StackExchange" }
Q: Bash. How to get multiline text between tags I'm trying to get text in my file between two tags. But if script finds opening tag and do not finds closing tag then it prints file from opening tag to the file's end. For example text is: aaa TAG1 some right text TAG2 some text2 TAG1 some text3 some text4 and script like this: awk "/TAG1/,/TAG2/" or sed -n "/TAG1/,/TAG2/p" than output will be: some right text some text3 some text4 but I need this: some right text A: Never use range expressions as they make tirivial tasks slightly briefer but then need a complete rewrite to avoid duplicate conditions when things get even slightly more interesting, as in your case. Always use a flag instead: $ awk 'f{ if (/TAG2/){printf "%s", buf; f=0; buf=""} else buf = buf $0 ORS}; /TAG1/{f=1}' file some right text
{ "pile_set_name": "StackExchange" }
Q: Implementing variable constraints in C++ I've been looking for an example that shows how to implement constraints in C++ (or a boost library that lets me do this easily), but without much luck. The best I could come up with off the top of my head is: #include <boost/function.hpp> #include <boost/lambda/lambda.hpp> template<typename T> class constrained { public: constrained(boost::function<bool (T)> constraint, T defaultValue, T value = defaultValue) { ASSERT(constraint(defaultValue)); ASSERT(constraint(value)); this->value = value; this->defaultValue = defaultValue; this->constraint = constraint; } void operator=(const T &assignedValue) { if(constraint(assignedValue)) value = assignedValue; } private: T value; T defaultValue; boost::function<bool (T)> constraint; }; int main(int argc, char* argv[]) { constrained<int> foo(boost::lambda::_1 > 0 && boost::lambda::_1 < 100, 5, 10); foo = 20; // works foo = -20; // fails return 0; } Of course there's probably some more functionality you'd want from a constraint class. This is just an idea for a starting point. Anyway, the problem I see is that I have to overload all operators that T defines in order to make it really behave like a T, and there is no way for me to find out what those are. Now, I don't actually need constraints for that many different types, so I could just leave out the template and hard code them. Still, I'm wondering if there's a general (or at least more succint/elegant) solution or if there's anything seriously wrong with my approach. A: Looks good as for tiny example. But be sure to implement all the operators and handle somehow wrong values. foo = 100; // works ++foo; // should throw an exception or perform an assert Use boost operators to help you with operators overload. And probably it would be good to have an option as a template parameter: either exception or assertion. I'd use such class. It is always better to have an index parameter that auto check vector range and do assertion. void foo( VectorIndex i ); A: You don't need to overload all operators as others have suggested, though this is the approach that offers maximum control because expressions involving objects of type constrained<T> will remain of this type. The alternative is to only overload the mutating operators (=, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, pre and post ++, pre and post --) and provide a user-defined conversion to T: template<typename T> class constrained { ... // As before, plus overloads for all mutating operators public: operator T() const { return value; } }; This way, any expression involving a constrained<T> object (e.g. x + y where x is int and y is constrained<int>) will be an rvalue of type T, which is usually more convenient and efficient. No safety is lost, because you don't need to control the value of any expression involving a constrained<T> object -- you only need to check the constraints at a time when a T becomes a constrained<T>, namely in constrained<T>'s constructor and in any of the mutating operators.
{ "pile_set_name": "StackExchange" }
Q: Passing arrays to functions PHP I just started learning PHP, and I came across the following code, which I'm having trouble to understand: <?php function f($v, $n) { if ($n <= 0) return 1; else return $v[$n-1] * f($v, $n-2) + 1; } $a = array(0,1,2,3); print (f($a, 4)); ?> This script returns the value 7. I can't understand how the f($v, $n-2) part is returning the value 2, since $v is an array. Shouldn't I have to put something like $v[number] so it can have a value? The commands echo "$a" (or $v) and print($a) return the "array" message, followed by a PHP notice. What value would $v receive in this case? Thanks very much! A: Right, so your $f() is a lambda function and so can be triggered by just calling the value associated. In your array, you got 4 positions that go from 0 to 3; When you execute the lambda targetting the index of 4, below will happen: For index 4 v[(4-1)] = 3 3 * f($v, (4-2)) + 1 f($v, (4-2)) v[(2-1)] = 1 1 * f($v, (2-2)) + 1 f($v, (2-2)) If is triggered as $n <= 0. Returns 1 automatically; So putting them together from bottom to top, you will have: 3 * (1 * 1 + 1) + 1 Following the math rules, first resolve what is under parenthesis, then multiplication, then sum: 3 * 2 + 1 = 6 + 1 = 7 Hope it was clear!
{ "pile_set_name": "StackExchange" }
Q: Can't access nested JSON Objects in React I have a simple React Component, and am trying to display a nested JSON object in render. // React Component class NodeDetail extends React.Component { constructor(props) { super(props); const node = {}; this.state = { node } } componentDidMount() { Node.getNode(this.props.node_id).then((result) => { console.log(result.data); this.setState(() => ({node: result.data})); }).catch(function(error) { // TODO: handle error }); } render() { return ( <div> {this.state.node.node_status.name} </div> ); } }; export default NodeDetail; This is the JSON(stored in result.data) getting returned from a rails API(some fields removed for brevity): { "id":1234, "name":"some-node", "created_at":"2018-05-18T15:23:24.012Z", "hostname":"some-host", "ip":"10.XXX.XXX.XXX", "mac":"24:6e:96:XX:11:XX", "node_status":{ "id":2, "name":"Parked" } } When I access the root level attributes in React with this.state.node.mac , it returns 24:6e:96:XX:11:XX. When I try to access the name attribute in node_status using this.state.node.node_status.name, I get the the following error: Uncaught TypeError: Cannot read property 'name' of undefined I have also tried this.state.node['node_status'].name, and same error. Why can't I access this object in the JSON, when clearly it is there? A: I bet it's because your call to the Rails API is asynchronous -- so your NodeDetail component tries to render before the API returns data / state is set with the result.data...try putting in a condition for non-existent node_status as some of the other answers have suggested. So the current (wrong) data flow will be: constructor. state is set to {node: {}} componentDidMount. Calls API. render. Throws exception because this.state.node.node_status is undefined. Component breaks and won't render again... API returns. state is set to result.data. result.data gets logged to your console. What you can do is something like: render() { if (!this.state.node.node_status) { return null; } return ( <div> {this.state.node.node_status.name} </div> ); } Or any of the other suggestions to account for the undefined value of this.state.node.node_status. In general, you need to make sure that your render method will work, even with the default state values set in your constructor. A: Error is coming correct Your are fetching data after component loaded In short you are calling your API in componentDidMount You can get rid off from this error in this way <div> {this.state.node.node_status?this.state.node.node_status.name:""} </div> and I would suggest you to call fetch data API in componentWillMount or constructor which is the initial stage of component.
{ "pile_set_name": "StackExchange" }
Q: Lazy registration with RESTful routing in Rails I'm stuck figuring out the best practice... I want to create a "following" system in a way that a user can follow a car (getting email updates when car price changes, etc). The part of implementation that's giving me headaches is when I want to introduce lazy registration by only using email. Everything needs to work as AJAX requests. In the interface, there will be a button to trigger the follow action, which will check if the user is registered or not. If a user is logged in, create a new CarSubscription item, otherwise display a form where he could type his email address. Once submitted, the form should create a user with no password (if email exists, ask for the password and log in) and then it should create the relationship item. The challenge here is to use redirection after submission of the form to the CREATE action of the CarSubscriptionController. Since I can't redirect using POST I can't simulate the CREATE or DESTROY action. The non-RESTful solution would be to create 2 actions under cars_controller: follow and unfollow and let them do the logic of creating entries and deleting them. That would enable me to just store the request path and use it after the user enters their email and logs in. How can I achieve what I want using RESTful resources? After trying to describe my problem here, it seems it's way too complicated and I am indeed very stuck... There are 3 different controllers and possibly 4 requests in this scenario. Any help would be tremendously appreciated! Please see my flow chart below: A: Not an expert here, I don't know if it's the best solution, but what I have done in similar situation is : In your controller, respond with javascript instead of redirecting the user In your javascript file, use $.post(...) to issue a POST to your controller action Et voilà! You can also use ActiveResource to achieve this, but I actually never tried that solution : http://api.rubyonrails.org/classes/ActiveResource/Base.html#label-Custom+REST+methods Person.new(:name => 'Ryan').post(:register) Hope this helps
{ "pile_set_name": "StackExchange" }
Q: Almost sure convergence implications with expected value Let $(X_n)_n\in\mathbb{N}$ be independent identically distributed random variables with $\mathbb{E}[X_1]=0$. Let $\beta \in (1,2)$. Show that if $n^{-1/\beta} \sum\limits_{k=0}^n {X_n} \to 0$ almost surely then $\mathbb{E}[\vert X_1\vert^{\beta}]$ is finite. There is a hint: Why does it suffice to show that $\sum\limits_nP(\vert {X_n}\vert\gt n^{1/\beta})$ converges? My thoughts on this: I think the idea behind the hint is to indicate a way to show the finiteness of $\mathbb{E} [\vert {X_1} \vert^{\beta}]$. I also thought about using convexity but I am unable to find any idea to start. A: here is how to use the hint: First notice that $\sum_n P(|X_n| > n^{\frac{1}{\beta}}) = \sum_n P(|X_n|^{\beta} > n)$. Since $|X_n|^{\beta}$ clearly has only values $\ge$, you can use the following representation of the expectation: $E[|X_n|^{\beta}] = \int_{0}^{\infty} P(|X_n|^{\beta} > x) dx$. Since $(X_n)_{n \in \mathbb{N}}$ i.i.d, we can conclude: $E[|X_1|^{\beta}] = \int_{0}^{\infty} P(|X_1|^{\beta} > x) dx = \sum_{n = 0}^{\infty} \int_{n}^{n+1} P(|X_1|^{\beta} > x) dx \le \sum_{n = 0}^{\infty} P(|X_1|^{\beta} > n). $ Notice that the last inequality follows from the monotonicity of the probability measure. Best Diamir
{ "pile_set_name": "StackExchange" }
Q: Find max of odd positions of a vector in C++ I am trying to find the max element of the odd (or even) positions of a vector in C++. For example using the code below i can find the max elements of the vector timer_table: timer_table[ii]= *std::max_element(timer_table.begin(), timer_table.end()); Is there any way to get the max of the odd positions of the vector? For instance if timer_table = {1, 22, 6, 3, 100, 2}, I want to get 22 or 100 (for even or odd). A: The complexity of max_element() is O(n), so you could write an O(n) for loop by yourself. Use the appropriate condition while increasing the index variable (i+=2) with i=0 for even indices and i=1 initialization for odd indices. Although this is very easy, I'm adding the code for the sake of completeness. #include "iostream" #include "vector" using namespace std; vector <int> :: iterator odd_max (vector <int> &x) { vector <int> :: iterator it = x.begin() + 1; for (vector <int> :: iterator i = it + 2; i < x.end(); i+=2) if (*i > *it) it = i; return it; } vector <int> :: iterator even_max (vector <int> &x) { vector <int> :: iterator it = x.begin(); for (vector <int> :: iterator i = it + 2; i < x.end(); i+=2) if (*i > *it) it = i; return it; } int main() { vector <int> timer_table = {1, 22, 6, 3, 100, 2}; cout << *odd_max(timer_table) << '\n'; cout << *even_max(timer_table) << '\n'; }
{ "pile_set_name": "StackExchange" }
Q: Bone Heat Weighting Failed, after turning on symmetry I have a nice 3D model and a decent rig. However, problems arise as I try to set the armature to the mesh with automatic weighting. I've removed doubles, I've recalculated normals, I've even applied the decimate modifier, as well as removed all modifiers, as well as countless other advice I've come across. Could it be the way in which I'm making my model? Now, I use Sculptris to make my models, and naturally they're symmetrical. I import them into Blender, and the textures on the right side always come out looking bad, lots of black and white speckles that show up through the texture. (I haven't found a simple way to fix this.) So, what I do is I go into edit mode, I mirror it, then turn on symmetry. The only other method is cutting it in half then mirroring it, and even with hitting 5, 1, then using B to select half the model, it gets very tiring trying to be very precise. I've tried setting it perfectly in the center, as well as setting it perfectly with the object's geometry origin. Nothing I have tried works. Oddly enough, on other models where I have turned on symmetry, the rigging works just fine. But those I started off by cutting them in half, mirroring them, merging the two objects into one, and then turning on symmetry. What could possibly be the difference? I'm a complete beginner, so any help would be appreciated. Here is the file if you wish to take a look at it. https://www.mediafire.com/?33uo1xeibr5wr9q A: Ok, nvm. I figured out a way. First I import the .obj file which never seemed to have any problem being connected to the bones. It was only when I added symmetry to it that it became unusable. However, importing the .obj and centering it, then exporting as a .dae and importing that seems to have solved this issue for me. So, it's all good now.
{ "pile_set_name": "StackExchange" }
Q: How many squares can be formed by using n points? How many squares can be formed by using n points on a 3 dimensional space? Like using 4 points, there is 1 square be formed Using 5 points, still 1 square Using 6 points, 3 squares can be formed A: In the plane $n$ points can determine at most $O(n^2)$ squares. This is because any two distinct points can determine up to three squares. In $R^3$ this argument no longer holds, since two points can form the corners of arbitrarily many squares. As Gerhard points out, $O(n^3)$ is an upper bound (in any dimension) given that three points determine at most one square. One can do a bit better than this. Using the Szemerédi–Trotter theorem one can show that a set of $n$ points in $R^3$ determines at most $O(n^{7/3})$ right triangles. It follows that $n$ points determine at most $O(n^{7/3})$ squares (since a square will contain a right triangle). On the other hand, it is certainly easy to see that there exists point sets with at least $\Omega(n^2)$ squares. The bound of $O(n^{7/3})$ is known to be sharp for the less constrained problem of counting right triangles. Update: A result of Sharir, Shefer and Zahl shows that the number of mutually similar triangles in a point set in $R^3$ is at most $O(n^{\frac{15}{7}})$, where $15/7 = 2.142\ldots$, which implies the same bound for the number of squares. Closing the gap for squares, however, seems an interesting and non-trivial problem. A: In k dimensions, take a regular unit k simplex on k points, and copy it an orthogonal distance of 1. This results in k choose 2 unit squares on 2k points. I invite others to count square arrangements in a hypercube. Combinatorially, there can be no more squares than three sets of an n set. Indeed, since three points of a square determine the fourth, there are at most a fourth as many squares possible as three sets. I imagine Erdos may have an upper bound for planar arrangements, which should be on the order of n^2, since any two points in the plane determine one of three squares containing those two points. Gerhard "Dots And Spots And Knots..." Paseman, 2020.07.05.
{ "pile_set_name": "StackExchange" }
Q: Partition area using test function I am looking for an efficient algorithm that can partition an area $B \subset \mathbb{R}^2$ into disjoint subsets $B = \bigoplus_i U_i$ such that a test function is constant on each of the subsets, $f \vert_{U_i} = \mathrm{const.}$ For example, consider the following partitioning: The indicated numbers are the return values of the test function in each cell. I want to recover the partitioning, given area error bounds, with the least number of function calls. My current approach uses a recursive grid-based method that tests at each vertex of an intial $n \times n$ grid. If not all vertices of a grid cell have the same function value, the cell is subdivided and the process repeats. This needs many subdivisions, and the initial grid must be "fine enough". I am curious if a specialized approach exists, and if there is a common name for this problem. A: The discrete version of your problem has a close resemblance with the classical Clustering problem. In Clustering given a finite set of points you have to divide the set such that points belong to a partition (cluster) iff they have similar properties. We consider the continuous version, i.e, your problem. Let $2\epsilon < 1$ is error bound. And, we have a bounding box of size $n*n$ which we would like to partition based on functional values. We divide the bounding box into $n/\epsilon*n/\epsilon$ grid cells, each cell has $\epsilon$ length side. Here we apply bottom up approach where the consecutive cells having same functional values are merged together. The partitioning algorithm is as follows. i) For each grid cell $c$, compute function values in its four corner points. Let $x$ be the function value occurring most frequently among those four values (in case of tie choose one arbitrarily). Assign $x$ as a label to $c$. ii) Start with the left and topmost grid cell. Iterate over cells from top to bottom and in a single row from left to right. In each cell $c$ if the cell on left and above (if exists) have same labels add $c$ to the cluster (partition) correspond to those cells (merging). Else if one of the left or above cell has same label add $c$ to the cluster (partition) of that cell. Otherwise start a new cluster with $c$. You can see that the error may occur in boundary regions (between two partitions) of the partitioning and the merging procedure will give correct partitions. But, as the boundary consists of $\epsilon$ side length boxes the error is within tolerance limit. Time complexity is $O((\frac{n}{\epsilon})^2)$.
{ "pile_set_name": "StackExchange" }
Q: Change border color of both divs when hover on one div in css i have two divs and and i want if when i hover on one div, border color of both divs should be change... CSS : .uperdiv { width:80%; background-color:black; margin-left:10%; border-style:none solid none solid ; border-width:5px; border-color:#fff; border-top-style:none; height:170px; margin-top:-220px; transition:border-color 2s; -moz-transition:border-color 2s; -webkit-transition:border-color 2s; -o-transition:border-color 2s; } .uperdiv:hover + .lowerdiv{ border-color:#9900ff; } .lowerdiv { border-style:none solid solid solid ; border-color:#fff; border-width:5px; background-color:black; width:80%; border-bottom-left-radius:15px; border-bottom-right-radius:15px; height:50px; margin-left:10%; } HTML <div class="uperdiv"> Some text </div> <div class="lowerdiv"> </div> I tried + sign but it changes lower div border color when i hover on uper div...and you can say that i want to create effects as of one div. And now i have no idea.. is there any way to do it?? And plz don't use jquery and javascript only css and css3 Thanks in advance :) A: Unfortunately, you can't (yet) target the previous sibling using CSS. You could put the two divs in a container, though, and apply the :hover to that. html <div class="container"> <div class="upperdiv"> Some text </div> <div class="lowerdiv"> Some text 2 </div> </div> css .container:hover .upperdiv, .container:hover .lowerdiv { border-color: #9900ff; } This way, when you hover either .upperdiv or .lowerdiv, both will have the border-color applied. We might be able to do this without the container in the future, using the subject indicator It would look something like this; .upperdiv:hover, .upperdiv:hover + .lowerdiv, .lowerdiv:hover, !.upperdiv + .lowerdiv:hover { /* target .upperdiv when the next sibling is hovered */ border-color: #9900ff; }
{ "pile_set_name": "StackExchange" }
Q: Let $P$ be a polynomial of degree $k>0$ and let $f_n(x)=P(x/n),∀x∈(0,∞).$ I came across a problem which says: Let $P$ be a polynomial of degree $k>0$ with a non-zero constant term.Let $f_n(x)=P(x/n), \, \forall x \in (0,\infty)$. Then which of the following is/are true? (a) $\lim f_n(x)=\infty \quad \forall x \in (0,\infty)$ (b) $\exists x \in (0,\infty)$ such that $\lim f_n(x)>P(0)$ (c) $\lim f_n(x)=0 \quad \forall x \in (0,\infty)$ (d) $\lim f_n(x)=P(0) \quad \forall x \in (0,\infty)$ I do not know how to approach the problem. Any kind of hints will be helpful. Thanks in advance for your time. A: Hints: 1) Let the polynomial be $\sum_{j=0}^k a_j x^j$. Consider the term $a_jx^j$. Let $j\gt 0$, and let $x$ be a fixed number. How does $a_j\left(\dfrac{x}{n}\right)^j$ behave as $n$ gets large? 2) Since this is multiple choice, test the proposed "facts" against simple polynomials. For example, for (a), think of the polynomial $P(x)=x+1$. Does $\frac{x}{n}+1$ get large as $n$ gets large? The same polynomial will let you settle (b) and (c) in the negative. And it will get you close to the answer for (d).
{ "pile_set_name": "StackExchange" }
Q: Power Line interference with different Sampling frequency I've been playing around with EEG data from an online database. If the power line interference (PLI) is at 50Hz and sampling frequency is 64Hz, then according to the Nyquist theorem, the 50Hz PLI should be aliased with 14Hz. But according to the database header file, the signal from EEG channel is processed by some prefilter, which is a bandpass filter with passband 0.5Hz - 32Hz. So in the end, the raw EEG data I get from the database, is analog signal sampled at 64Hz and bandpass filtered in 0.5Hz - 32Hz range. So my question is, do I have to design a notch filter to remove the PLI at 50Hz if the signal has already been bandpass filtered (32 Hz above removed.) A: That depends if the bandpass filter was applied before or after sampling. If it was before sampling (i.e. in analog domain) it worked as an anti-aliasing filter and you dont need to filter out the PL. If it was applied in digital domain, you'd need to suppress it, because then the aliasing would occur. Have a look at the FFT of your signal to see if there is a peak or not at 14Hz, which could come from the PL. (I guess the filter was applied in analog domain, because it does not make much sense to do it after sampling, since the high cutoff is already the Nyquist frequency.)
{ "pile_set_name": "StackExchange" }
Q: jQuery - Run a function based on text match I've had a search through the site and can't find an answer, so here goes: I would like to know how one could run a function based on a text match with jQuery. Let me explain further. I have 3 groups of numbers, we'll call each group A, B and C respectively. An example scenario: A user will enter some text into an Input box, push submit and jQuery will check if the input text matches any text contained within one of the groups and if so, return some data to say 'Input text matches text from group A' and run one of 3 functions based on what's returned. How would I go about doing this? A: This is a simple matter of binding the click handler of the button to check the value of your input box and checking for a pattern match. Your JavaScript would look something like this: $('#submit_btn').bind('click',function(evt) { evt.preventDefault(); var patternCheck = [111,222,333].indexOf( parseInt($('#input_field').val()) ) if( patternCheck !== -1) { alert("Found at index "+ patternCheck); } else { alert("Not found"); } }); In this case the button has an ID of submit_btn and we are raising an alert whenever we find a match in an array of values to the value of the input field with an ID of input_field. You may want to store the array of values somewhere else but for illustrating this solution it's easy to just house them within the click handler function. Using if...elseif would also work but if you're just looking for exact matches there's no need to iterate/loop through an entire array. This is much more efficient.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to extract cell reference from a hyperlink? I've been researching this one for a while now with no luck, so thought I would open it up here... Let's say you have two worksheets in an excel workbook, e.g. sheet1 and sheet2. Now, in sheet2 cell A1, say you have a hyperlink that refers/points/links to sheet1 cell A1. In other words, the value of the cell reference of the hyperlink at sheet2!A1 is sheet1!A1 Do you know if there is a formula or function that would return the cell reference of that hyperlink. i.e. =<formula-or-function>(sheet2!A1) which returns 'sheet1!A1' as its result. A: You can retrieve the .SubAddress from the Hyperlinks.Item Property. 'by the active cell With ActiveCell Debug.Print .Hyperlinks.Item(1).SubAddress End With 'by worksheet and cell address With Worksheets("Sheet2").Range("D6") Debug.Print .Hyperlinks.Item(1).SubAddress End With This is, of course, VBA. I know of no way to perform this action with a worksheet formula short of a User Defined Function (aka UDF) written in VBA.
{ "pile_set_name": "StackExchange" }
Q: Vertically aligned text in math How do I get something like this in LaTex? I have tried the align-environment, but can't get the vertical text (argmin) right. A: You get better arrows with tikz-cd: \documentclass{article} \usepackage[sc]{mathpazo} \usepackage{amsmath} \usepackage{tikz-cd} \usepackage{graphicx} \DeclareMathOperator{\argmin}{arg\,min} \begin{document} \begin{tikzcd}[row sep=0pt] \displaystyle\frac{1}{N}\sum_{i=1}^{N} q(w_{i},\theta) \arrow[r] & \mathbb{E}[q(w,\theta)] \\ \rotatebox[origin=c]{90}{$\argmin$} & \rotatebox[origin=c]{90}{$\argmin$} \\ \hat{\theta} \arrow[r,red] & \theta \end{tikzcd} \end{document}
{ "pile_set_name": "StackExchange" }
Q: Is there any way to find the default styling for input text field glow? You know that sexy glow that surrounds an input field whenever it has focus? Without going into too much detail, I need to recreate that effect outside of an input field, but I can't seem to find the stylesheet that dictates such an effect anywhere. (I know how to do it, using the outline property and so on. I'm just wondering if there's a way I can find the EXACT values used by default for input text fields.) A: chrome has the outline style for inputs as default. i have to disable that rule for many projects. use the chrome developer tool to see the browser style rules. see how to do this here: chrome developer tool info A: It is possible to do this via CSS. Have a look at Twitter Bootstrap Forms and how they do it. Click inside any input field. See a simple working example here: http://jsbin.com/esidas/2/edit#html,live It's done using CSS3 properties for box-shadow and transition input[type=text] { background-color: #ffffff; border: 1px solid #cccccc; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -webkit-transition: border linear 0.2s, box-shadow linear 0.2s; -moz-transition: border linear 0.2s, box-shadow linear 0.2s; -ms-transition: border linear 0.2s, box-shadow linear 0.2s; -o-transition: border linear 0.2s, box-shadow linear 0.2s; transition: border linear 0.2s, box-shadow linear 0.2s; } input[type=text]:focus { border-color: rgba(82, 168, 236, 0.8); outline: 0; outline: thin dotted \9; /* IE6-9 */ -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); }
{ "pile_set_name": "StackExchange" }
Q: Using writeUnshared & readUnshared to communicate with sockets... reading the object I sent before and not the one I am sending right now I have a Server, a RMI Server and a Client... I am using writeUnshared and readUnshared to communicate with sockets, but when I am reading, I read the object I sent (from the client to the server) before and not the one I am sending right now... I know that I am sending, from the Client, the object I want to send... But in the Server side I am reading the object I sent before... try { while (true) { postCard = null; postCard = (ClientRequest) reciver.readUnshared(); alterRequest = postCard.getRequestID() + ("_" + myUserID); postCard.setRequestID(alterRequest); System.out.println(postCard.getRequestID()); System.out.println("[Server] Li a mensagem do cliente na boa."); //mudar depois para um switch if (postCard.getRequest()[0].equals("log")) { postCard.setStage(1); myMail = remoteConection.verificaLogIn(postCard); if (myMail.getResponse()[0].equals("userrec")) { myUserID = (int) myMail.getResponse()[1]; } myMail.setStage(4); } else if (postCard.getRequest()[0].equals("new")) { System.out.println("Fui chamado!"); if(postCard.getResponse()!=null){ System.out.println("Não és null por que caralho!&"); } postCard.setStage(1); myMail = remoteConection.novoUtilizador(postCard); if (myMail.getResponse()[0].equals("infosave")) { System.out.println("myUserID:" + (int) myMail.getResponse()[1]); myUserID = (int) myMail.getResponse()[1]; } else if (myMail.getResponse()[0].equals("erro")){ System.out.println("ERRO!\n"); //Temos que tratar o erro } else if(myMail.getResponse()[0].equals("user_already_exists")){ System.out.println("User: "+ (String)myMail.getResponse()[1]+" already exists!"); } myMail.setStage(4); } else if (postCard.getRequest()[0].equals("new_project")) { postCard.setStage(1); myMail = remoteConection.novoProjecto(postCard); if (myMail.getResponse()[0].equals("infosave")) { System.out.println("myProjectID:" + (int) myMail.getResponse()[1]); myProjectID = (int) myMail.getResponse()[1]; } myMail.setStage(4); } else if (postCard.getRequest()[0].equals("seesal")) { System.out.println("Esteve aqui, como era suposto\n"); postCard.getRequest()[1] = myUserID; postCard.setStage(1); myMail = remoteConection.getUserSaldo(postCard); myMail.setStage(4); } sender.writeUnshared(myMail); } } catch (Exception e) { System.out.print("[Server]"); e.printStackTrace(); } } What am I doing wrong? A: read/writeUnshared() only avoid sharing the actual object being written. All dependent (reachable, member) objects remain shared. Try a reset() before each write.
{ "pile_set_name": "StackExchange" }
Q: How could I retrieve all the relationships from a (spring-data-)neo4j database? Is there a way to simply retrieve all relationships of a certain type - where type is a @RelationshipEntity annotated class - from a spring-data-neo4j [SDN] database? (working with 2.0.0.RC1 & embedded DB) When I try the method provided by SDN : relationShipRepository.findAll() it gives me the following error: org.neo4j.graphdb.NotFoundException: __type__ property not found for RelationshipImpl #9672 of type 7 between Node[4844] and Node[4875]. Full stacktrace: http://pastebin.com/j2gqcjxh (though looking A solution would be to use the low level (neo4j) API (namely GraphDatabaseService ) to retreive all nodes, and then for each node retreive all their relationships and verify if their __type__ field matches the type of relationship I'm interested in. But then why provide findAll method for relationships? Simple explanation is that the the advised interface is the same for nodes and relationships - but does any documentation say that we are not allowed to use findAll for relationships? Or: examining the relationship entity in the db, it contradicts the exception, because type is defined correctly as expected and it is possible to retreive the relationship through highlevel (SDN) API once you retrieved the node and you call getRelationship*(..) On other note: does anyone know if ImpermanentDataGraph service will be included in v 2+? A: Are you looking for the relationships that are created as Relationship-entities in SDN or all relationships? What is your use-case? Relationship-Entites are also added to the index. Is the relationship 9672 a relationship-entity? For the Relationship-Repository - that depends on the TypeRepresentationStrategy, if the "indexed-strategy" is used, Relationship-Enties are also available in their respective repository (but not globally). In Neo4j 1.6.M01 there is a new [GlobalGraphOperations][1] class that also has getAllRelationships(). ImpermanentGraphDatabase is out of the Neo4j-testing toolchain. And it will stay there (and improve in performance) in v2+.
{ "pile_set_name": "StackExchange" }
Q: Call methods of childclasses only when child is casted into parent? Suppose I have a class train, two child classes intercity and sprinter which are types of trains. Now say I want to print a list of trains. When it is an intercity it shoud print intercity and when it is a sprinter it shoud print sprinter. I thought this would imply that I create a method print in intercity and in sprinter. However as the program is iterating throug a list with trains java insists on creating a print method in the class train aswell. So how do I cope with this. I thought of creating the print method which checks whether it is an instance of intercity or sprinter, then casts it into the corresponding type and then calls the print method of that type. However I want to become a better programmer and it does not look like the best solution to me. So my question therefore is how should deal with the above described situation? A: You create a print method in the Train super-class and override it in the sub-classes. This way you don't have to check the type of a Train object before printing it, and no casting is required. public class Train { public void print () { // here you might have a default printing logic, or you could keep this // method abstract and leave the implementation to the sub-classes } } public class Sprinter extends Train { @Override public void print () { } } public class InterCity extends Train { @Override public void print () { } }
{ "pile_set_name": "StackExchange" }
Q: Chart.js line chart set background color I'm working with Chart.js and want to convert a line chart to a PNG. The problem is that the image always downloads with a transparent background, which is not what I need. I tried many options, nothing really worked. And suggestions? A: Here's a solution that works perfectly, also when saving to an image file (like png). I'm blatantly copying this from @etimberg at the chartjs issue tracker. Chart.plugins.register({ beforeDraw: function(chartInstance) { var ctx = chartInstance.chart.ctx; ctx.fillStyle = "white"; ctx.fillRect(0, 0, chartInstance.chart.width, chartInstance.chart.height); } }); This should go before your chart in the source. A: Here's one way to get a fully-opaque version of your ChartJS: Wait until the chart is fully animated out and complete. You can do this by adding the onAnimationComplete property to the chart. In the onAnimationComplete function: Create an in-memory temporary canvas of equal size as your chart. Fill the temp canvas with white drawImage the ChartJS canvas over the white-filled temp canvas Create an image from the temp canvas. Here's how that might be done: var ctx = document.getElementById("canvas").getContext("2d"); window.myLine = new Chart(ctx).Line(lineChartData, { responsive: true, onAnimationComplete:function(){ var tcanvas=document.createElement('canvas'); var tctx=tcanvas.getContext('2d'); tcanvas.width=ctx.canvas.width; tcanvas.height=ctx.canvas.height; tctx.fillStyle='white'; tctx.fillRect(0,0,tcanvas.width,tcanvas.height); tctx.drawImage(canvas,0,0); var img=new Image(); img.onload=function(){ document.body.appendChild(img); } img.src=tcanvas.toDataURL(); } }); Here's example code and a Demo: var randomScalingFactor = function(){ return Math.round(Math.random()*100)}; var randomColorFactor = function(){ return Math.round(Math.random()*255)}; var lineChartData = { labels : ["January","February","March","April","May","June","July"], datasets : [ { label: "My First dataset", fillColor : "rgba(220,220,220,0.2)", strokeColor : "rgba(220,220,220,1)", pointColor : "rgba(220,220,220,1)", pointStrokeColor : "#fff", pointHighlightFill : "#fff", pointHighlightStroke : "rgba(220,220,220,1)", data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()] }, { label: "My Second dataset", fillColor : "rgba(151,187,205,0.2)", strokeColor : "rgba(151,187,205,1)", pointColor : "rgba(151,187,205,1)", pointStrokeColor : "#fff", pointHighlightFill : "#fff", pointHighlightStroke : "rgba(151,187,205,1)", data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()] } ] } var ctx = document.getElementById("canvas").getContext("2d"); window.myLine = new Chart(ctx).Line(lineChartData, { responsive: true, onAnimationComplete:function(){ var tcanvas=document.createElement('canvas'); var tctx=tcanvas.getContext('2d'); tcanvas.width=ctx.canvas.width; tcanvas.height=ctx.canvas.height; tctx.fillStyle='white'; tctx.fillRect(0,0,tcanvas.width,tcanvas.height); tctx.drawImage(canvas,0,0); var img=new Image(); img.onload=function(){ document.body.appendChild(img); } img.src=tcanvas.toDataURL(); } }); <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script> <h4>ChartJS line chart</h4> <div style="width:30%"> <div> <canvas id="canvas" height="450" width="600"></canvas> </div> </div> <h4>Fully opaque chart as image</h4> A: Why don't you try to use css? A canvas element is just like a normal HTML element right? So you can either set it's background colour or set it's background to an image using css. $('#myChart').css('background-color', 'rgba(0, 0, 0, 0)'); // this worked for me but I'm guessing you can set a background image using css like you normally do.
{ "pile_set_name": "StackExchange" }
Q: Understanding int() and mod() functions as used in this formula Context: SCOM metric to measure software class cohesion Paper: A SENSITIVE METRIC OF CLASS COHESION by Luis Fernández and Rosalía Peña. The equation in question is on page 86: $S(m,a) = \frac 12[1 + int(\frac {m-1}a)][mod(\frac {m-1}a) + m -1]$ Where m is the number of methods of a class and a is the number of attributes of the class. I believe the int() function used here is the Integer Part function. But what is the meaning of the mod() function? I can't find a reference to the modulus function where it takes just one argument therefore I can't say for sure that that's what it means. A: By comparing with the line immediately above it in the paper, and assuming the authors didn't make a typo, it must be the fractional part, which is sometimes considered as "modulo 1". I suppose for these authors, the second argument of "mod" can be dropped when it is 1.
{ "pile_set_name": "StackExchange" }
Q: How do I get github to syntax highlight Solidity code? I uploaded a smart contract written in Solidity to github but it is not syntax highlighted. Instead it looks like a regular text file. I would like syntax highlighting to be shown on Github. How do I achieve that? A: You need to tell github that this file is a Solidity file. Github will not recongnize .sol files automatically at the moment. Add this line to your .gitattributes file: *.sol linguist-language=Solidity If you do not have a .gitattributes file you need to create one and place it in the root directory of your git project.
{ "pile_set_name": "StackExchange" }
Q: Tizen .net application. How to access device hard buttons I am working on a Tizen .net application for wearable devices. I cannot find information on how to gain access to the device hardware such as the menu or back button. I have found how to access the hardware and software bezel in the Wearable CircularUI documentation noted below. https://developer.tizen.org/zh-hans/development/guides/.net-application/application-management/applications/watch-application There appear to be at least a few other references to this for native or web applications, but I could not find any API for .net applications. Please advise A: First, Application can't handle home hardware key only can handle Back hardware key. if You use Xamarin.forms, you can override OnBackButtonPressed method to handle Back hardware key Here is guide to use Bezel event https://samsung.github.io/Tizen.CircularUI/guide/IRotaryEventReceiver.html
{ "pile_set_name": "StackExchange" }
Q: laravel - get parameters from http request I want to pass in multiple parameters from my Angular app to my Laravel API, namely the id and choices array supplied by user. Angular: http request: verifyAnswer: function(params) { return $http({ method: 'GET', url: 'http://localhost:8888/api/questions/check', cache: true, params: { id: params.question_id, choices: params.answer_choices } }); Laravel 5: routes.php: $router->get('/api/questions/check/(:any)', 'ApiController@getAnswer'); ApiController.php: public function getAnswer(Request $request) { die(print_r($request)); } I thought I should use :any within my URI to indicate I'll be passing in an arbitrary amount of parameters of various data structure (id is a number, choices is an array of choices). How can I make this request? [200]: /api/questions/check?choices= choice+1 &choices= choice+2 &choices= choice+3 &id=1 A: Change this: $router->get('/api/questions/check/(:any)', 'ApiController@getAnswer'); to $router->get('/api/questions/check', 'ApiController@getAnswer'); And fetch the values with echo $request->id; echo $request->choices; in your controller. There is no need to specify that you will receive parameters, they will all be in $request when you inject Request to your method.
{ "pile_set_name": "StackExchange" }
Q: Something like Mojolicious for PHP? Mojolicious is a very good web framework for Perl. Does anyone perhaps know if there is something similar to it for PHP? A: I would prefer Slim to write small web apps in PHP. Snippet from docs: <?php use \Psr\Http\Message\ServerRequestInterface as Request; use \Psr\Http\Message\ResponseInterface as Response; require 'vendor/autoload.php'; $app = new \Slim\App; $app->get('/hello/{name}', function (Request $request, Response $response) { $name = $request->getAttribute('name'); $response->getBody()->write("Hello, $name"); return $response; }); $app->run();
{ "pile_set_name": "StackExchange" }
Q: Maximum length of addition line in VBA Is there a maximum length of a line when adding numbers in VBA? For example in MS Access: Dim L As Long ' this works L = 2696 + 2630 + 2860 + 2860 + 2860 + 2860 + 2795 + 2795 + 2630 + 2630 + 2630 + 263 ' this gives an Overflow error L = 2696 + 2630 + 2860 + 2860 + 2860 + 2860 + 2795 + 2795 + 2630 + 2630 + 2630 + 2630 Debug.Print L I have never seen this documented. Also, it doesn't throw an overflow error in C# in Visual Studio. A: The type of an integer literal is an Integer (Max +32767): ?typename(2696) Integer The result of adding n Integers is also of type Integer: ?typename(2696 + 2630) Integer As soon as the accumulation exceeds the bounds of an Integer you will get an Overflow exception, it does not matter that the variable you are assigning to is a Long because the accumulation is performed before the assignment. The way to fix this is to make one of the values in the addition a Long which you can easily do with the & Type Suffix: L = 2696& + 2630 + ..
{ "pile_set_name": "StackExchange" }
Q: Examples of Richardson orbit closures not having a symplectic resolution? This is a follow-up to a recent question asked by Peter Crooks here. The answer by Ben Webster includes a helpful link to the corrected arXiv version of Baohua Fu's 2003 Invent. Math. paper Symplectic resolutions for nilpotent orbits. Most of this literature is unfamiliar to me, so I may be overlooking something. I've encountered nilpotent orbits mainly in connection with various types of representation theory (sometimes in good prime characteristic, where most properties of the orbits are the same as over $\mathbb{C}$). At this point I'm still confused about some details, such as: Are there Richardson orbits whose closures fail to have a symplectic resolution (and if so, what is the lowest rank Lie algebra in which an example appears)? EDIT: Here I'm using shorthand to avoid normality questions: read "for which the normalizations of their closures fail to have ...? (Apparently the sorting out of normal orbits isn't complete yet for some exceptional types.) As Fu notes in Prop. 3.16, it follows from the main theorem of the paper that a nilpotent orbit whose closure admits a symplectic resolution must be Richardson (intersecting the nilradical of some parabolic subalgebra in a dense orbit). In turn a reviewer states: "But the converse is not always true." I don't see direct evidence of that in Fu's paper. Here the simple Lie algebras are studied case-by-case: all orbits in type $A_n$ are Richardson, with trivial component groups, forcing their closures to have symplectic resolutions. In types $G_2, F_4, E_6$, all Richardson orbits also have trivial component groups, whereas a few such orbits in types $E_7, E_8$ have component groups of order 2 and are left unsettled in the paper. (These cases were later treated geometrically here.) The discussion of types $B_n, C_n, D_n$ leaves me somewhat confused, since the explicit examples mentioned between Prop. 3.21 and Prop. 3.22 aren't Richardson orbits. This prompts the question above. ADDED: Fu reduces the problem (for a Richardson orbit) to the question of whether or not there exists a parabolic $P$ defining the orbit for which $N(P)=1$. This is the index in the full component group in $G$ (topologically, fundamental group) of the component group in $P$ of an orbit element $X$. (Here "component group" means the group $C_G(X)/C_G(X)^\circ$.) It's not clear how to compute $N(P)$ in all cases, which may be why Fu gave up on the leftover cases in types $E_7,E_8$. I'm wondering about the naive (presumably false?) statement that an orbit closure has a symplectic resolution iff the orbit is Richardson. What bothers me is that Fu seems to mention only examples of non-Richardson orbits such as minimal orbits in types other than $A_n$, etc. A: The relevant information is in the article of Hesselink: Polarizations in the classical groups. Fix a parabolic $P$ and a Richardson element $u$. Let $N(u,P)$ be the the number of conjugates of $P$ that contain $u$ (the number of polarizations of $u$). In Hesselink's notation, this is $N_1(P)$. EDIT: I realized I had misread Hesselink; $N(P)$ is not the same for all polarizations. Theorem (Fu): A nilpotent orbit closure $\bar{O}$ has a symplectic resolution if and only if $O$ is normal and Richardson with a polarization such that $N(P)=1$. I misunderstood what was going on in Hesselink's tables. You should look for entries that only have one conjugacy class of polarizations which have $N_1=2$ (this is stronger than what you need, but all of Hesselink's examples have this form). It looks as though the first bad examples in each series are the Richardson orbits for the stabilizer of a line in $Sp(6)$ (denoted $C_2$), the stabilizer of a 4-space in $SO(9)$ (denoted $A_3$), and the stabilizer of a 5-space in $SO(12)$ (denoted $A_4$; that one I'm less confident I got right). If I understand correctly, inducing these up should give bad examples of higher rank in these series.
{ "pile_set_name": "StackExchange" }
Q: How to get the returned reference to a vector? I found two ways to get the reference returned by the function. vector<int> vec1 = {4,5,6}; vector<int>& rtn_vec(void) { return vec1; } int main() { vector<int> &vec2 = rtn_vec(); //way 1 vector<int> vec3 = rtn_vec(); //way2 vec2[0] = 3; return 0; } I understand way 1 means passing the reference to vec1 to &vec2, so vec2[0] = 3; changes vec1 to {3,5,6}. But about way 2, I have 2 questions: Why can I pass a reference (vector<int>&) to an instance (vector<int>), how does it work? Does way 2 involve deep copy? Because I run this code and vector<int> vec3 = rtn_vec(); seems just copy vec1 to vec3. A: vector<int> vec3 = rtn_vec(); //way2 This allocates a new vector and invokes a copy constructor, so yes, this is "deep" copy. Actually, this is in no way different from simply writing vector<int> &vec2 = vec1; vector<int> vec3 = vec1; Or to make things even clearer vector<int> &return_value = vec1; vector<int> &vec2 = return_value; vector<int> vec3 = return_value; (Though be careful with term "deep". If it was vector<int*>, then only the pointers would be copied, not the ints themselves.)
{ "pile_set_name": "StackExchange" }
Q: JSF components not parsed inside a I had to change a <script> ... </script> in an JSF page and tried to evaluate a JSF component inside of the script. The EL was evaluated but the tag itself was untouched. What is the reason for this behaviour? Example: <script type="text/javascript"> //<![CDATA[ function doSomething() { $('.userNode').droppable({ activeClass : 'ui-state-active', hoverClass : 'ui-state-highlight', tolerance : 'intersect', drop : function(event, ui) { <h:panelGroup rendered="#{myBean.useThis}"> alert("code A"); </h:panelGroup> <h:panelGroup rendered="#{!myBean.useThis}"> alert("code B"); </h:panelGroup> } }); }; //]]> </script> The EL #{!myBean.useThis} was evaluated to true/false but the <h:panelGroup> was in the result of the rendering. Why? A: It's because you placed it inside a CDATA block. Anything inside a CDATA block is considered character data, not as XML data. Better don't do this at all. This is a poor practice. Put the JS function in its own .js file. Use JSF/EL only to prepare JavaScript variables which the JS functions will then ask for (as method argument) or access by itself (in window scope), not to fill parts of JS functions. E.g. <h:outputScript>var useThis = #{myBean.useThis};</h:outputScript> <h:outputScript name="script.js" /> function doSomething() { $('.userNode').droppable({ activeClass : 'ui-state-active', hoverClass : 'ui-state-highlight', tolerance : 'intersect', drop : function(event, ui) { if (useThis) { alert("code A"); } else { alert("code B"); } } }); } To prevent pollution of global scope, consider creating a namespace. <h:outputScript>var my = my||{}; my.useThis = #{myBean.useThis};</h:outputScript> if (my.useThis) { alert("code A"); } else { alert("code B"); } See also: Error parsing XHTML: The content of elements must consist of well-formed character data or markup
{ "pile_set_name": "StackExchange" }
Q: What is the maximum number of bytes that can be sent through USB-to-serial COM port at one go? Suppose someone uses hyper-terminal to send a very long ASCII string at a COM port. This COM port is created by FTDI USB-to-serial port cable. The cable used is http://www.ftdichip.com/Support/Documents/DataSheets/Cables/DS_TTL-232RG_CABLES.pdf. Is there a limitation imposed by the UART driver for PC? For example, Arduino UART tx buffer is 64 bytes only. What is the maximum number of bytes that can be sent through a PC serial port at one go? A: In full-speed USB, the maximum packet size is 64 bytes. In high-speed USB, the maximum packet size is 512 bytes. Most USB/serial converters, including yours, use full speed. However, if you are looking at the serial output, the USB packet size does not matter, because USB packets can be sent faster than the speed of the serial line, and are buffered. For example, if the PC sends 100 bytes, it will use two packets, but what you are seeing at the other end, on the serial line, is again a continuous stream of 100 bytes. Similarly, if you are sending data from an Arduino, you can buffer a new TX byte as soon as some previous byte is being sent, so the size of the TX buffer does not really matter. (However, a larger buffer size allows the pre-buffer more data, which allows continuous transmission even if the microcontroller must do something else for a longer time.) PCs, most microcontrollers, and USB/serial converters are fast enough so that the only bottleneck is the speed of the serial line, so you will never see a gap in the data, regardless of how many bytes are transmitted.
{ "pile_set_name": "StackExchange" }
Q: Finding the periods of a sequence of integers reduced mod m I'm interested to know if there is a standard method to prove that a given sequence of integers has period $p_m\in \mathbb{Z}$ when reduced modulo $m\in\mathbb{Z}$. For example, let $t_n=\dfrac{n(n+1)}{2}$ be the sequence of triangular numbers. Then by examination it appears that the period $p_m$ is given by $m$ when $m$ is odd and $2m$ when $m$ is even. I suppose that a proof using divisibility arguments is possible, but I'm not sure how to start. References for books or articles that discuss this topic would be greatly appreciated. To prove that $t_n$ is periodic when reduced modulo $m$, we can use the recurrence relation $t_n=t_{n-1}+n$, or a bootstrapping argument, but I don't see how either method can give the actual lengths of the periods. A: There is no simple general method. Consider the sequence $t_n = a^n$ where $\gcd(a,m)=1$. The period of this sequence mod $m$ is the order of $a$ mod $m$ and there is no known formula for that, not even for $a=2$ and $m$ prime.
{ "pile_set_name": "StackExchange" }
Q: How do I get to work my Atheros AR9485 Wireless card in Ubuntu 14.04 LTS? I've recently installed Ubuntu 14.04 LTS in my ASUS D550CA, and so far things have gone great. The only problem I've got is the Wi-Fi. It doesn't work. I've got an Qualcomm Atheros AR9485. I've tried installing the drivers, but the sytem says it doesn't find any. So I started looking around this forum for solutions. I've read every single post from this forum about my Wi-Fi network adapter, and I've found nothing that solves my problem. Let me give you some info about my configuration. Disclaimer: my configuration is in spanish, so if you don't understand something you can either use Google translate, or use your imagination. :D When I run $ sudo lshw -C network this is what I get: *-network DEACTIVATED descripción: Interfaz inalámbrica producto: AR9485 Wireless Network Adapter fabricante: Qualcomm Atheros id físico: 0 información del bus: pci@0000:02:00.0 nombre lógico: wlan0 versión: 01 serie: 28:e3:47:5c:5d:3f anchura: 64 bits reloj: 33MHz capacidades: pm msi pciexpress bus_master cap_list rom ethernet physical wireless configuración: broadcast=yes driver=ath9k driverversion=3.13.0-34-generic firmware=N/A latency=0 link=no multicast=yes wireless=IEEE 802.11bgn recursos: irq:17 memoria:f7d00000-f7d7ffff memoria:f7d80000-f7d8ffff *-network descripción: Ethernet interface producto: RTL8101E/RTL8102E PCI Express Fast Ethernet controller fabricante: Realtek Semiconductor Co., Ltd. id físico: 0.2 información del bus: pci@0000:03:00.2 nombre lógico: eth0 versión: 06 serie: e0:3f:49:ce:57:49 tamaño: 100Mbit/s capacidad: 100Mbit/s anchura: 64 bits reloj: 33MHz capacidades: pm msi pciexpress msix vpd bus_master cap_list ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd autonegotiation configuración: autonegotiation=on broadcast=yes driver=r8169 driverversion=2.3LK-NAPI duplex=full firmware=rtl8402-1_0.0.1 10/26/11 ip=181.165.245.39 latency=0 link=yes multicast=yes port=MII speed=100Mbit/s recursos: irq:41 ioport:e000(size=256) memoria:f0004000-f0004fff memoria:f0000000-f0003fff At the beginning, you'll see that it says "*-network DEACTIVATED" (or at least that's what I translated), is that something bad? Then, when I run ipconfig this is what I get: eth0 Link encap:Ethernet direcciónHW e0:3f:49:ce:57:49 Direc. inet:181.165.245.39 Difus.:181.165.245.255 Másc:255.255.255.0 Dirección inet6: fe80::e23f:49ff:fece:5749/64 Alcance:Enlace ACTIVO DIFUSIÓN FUNCIONANDO MULTICAST MTU:1500 Métrica:1 Paquetes RX:221199 errores:0 perdidos:0 overruns:0 frame:0 Paquetes TX:62025 errores:0 perdidos:0 overruns:0 carrier:0 colisiones:0 long.colaTX:1000 Bytes RX:124409589 (124.4 MB) TX bytes:7471899 (7.4 MB) lo Link encap:Bucle local Direc. inet:127.0.0.1 Másc:255.0.0.0 Dirección inet6: ::1/128 Alcance:Anfitrión ACTIVO BUCLE FUNCIONANDO MTU:65536 Métrica:1 Paquetes RX:2977 errores:0 perdidos:0 overruns:0 frame:0 Paquetes TX:2977 errores:0 perdidos:0 overruns:0 carrier:0 colisiones:0 long.colaTX:0 Bytes RX:397158 (397.1 KB) TX bytes:397158 (397.1 KB) When I put iwconfig: eth0 no wireless extensions. lo no wireless extensions. wlan0 IEEE 802.11bgn ESSID:off/any Mode:Managed Access Point: Not-Associated Tx-Power=off Retry long limit:7 RTS thr:off Fragment thr:off Power Management:off Finally, when I put sudo rfkill list all, I got: 0: phy0: Wireless LAN Soft blocked: no Hard blocked: yes 1: asus-wlan: Wireless LAN Soft blocked: no Hard blocked: no 2: asus-bluetooth: Bluetooth Soft blocked: no Hard blocked: no I hope anyone can help me solve this, I've searched a lot and found no solution. Thanks a lot. A: Your wireless is blocked by the wireless switch or key combination; please see: Hard blocked: yes Please try the key combination, Fn+F2 or similar and run again: rfkill list all Any change? If not, is the module asus_nb_wmi loaded? Check: lsmod | grep asus If so, please try: echo "options asus_nb_wmi wapf=1" | sudo tee /etc/modprobe.d/asus.conf Reboot and see if your wireless key combination is working as expected.
{ "pile_set_name": "StackExchange" }
Q: How Divide and Conquer algorithms work with a given input? I've written a divide and conquer algorithm in java. The problem is, I've tested it an it works, except I'm not really sure why or what it does with the data. I know the it splits the array into sub parts, but apart from that i'm confused what happens what they're returning everything. For example, does the smallest base case return its number and compare that? Also what order does the recursive take place if theres more than one recursion call in a function? My code is: public static int FindMin(int[] array, int low, int high) { int min = 0, min1 = 0, min2 = 0; int mid = 0; if (low == high) { min = array[low]; } else if (low == (high - 1)) { if (array[low] < array[high]) { min = array[low]; } else if (array[low] > array[high]); { min = array[high]; } } else { mid = (low + high)/2; min1 = FindMin(array, low, mid); min2 = FindMin(array, mid+1, high); if (min1 < min2) { min = min1; } else { min = min2; } } return min; } Basically what I want to know is: how the algorithm would work if it was given the input: 3,6,1,5,7,2,1. Like what it returns and things like that. I'm sorry if the question is somewhat ambiguous but I know how to code it, I just cant seem to understand how it returns everything, regardless of all the google pages and pdfs i've started at. Thanks for all the help anyway! :D A: Okay, so now I got a grasp what it does and how it works. It's quite simple. For a given array, you divide it into two parts further and further. Now every recursive code has to stop at some point, yours stop in two situation. A) When the part this recursive needs to process is sized one. B) When the part this recursive needs to process is sized two. So when condition A is met, your function simply returns low, which is equal to high. When condition B is met, your function compares array[low] and array[high], and returns the index of the value which is lower. If the recursive function has to process a range of more than 2, it divides into two part, and hand those two part to two more recursive parts. For example, for a given array like this. array[] = {1, 2, 3, 4, 5} You will first split it to two parts of {1, 2} [0...1] and {3, 4, 5} [2...4]. And now since the first part is of size 2, the index 0 gets returned because 1 is smaller than 2, obviously. And then the other part {3, 4, 5} gets divided again, to two parts, {3} [2...2], and {4, 5} [3...4]. The first subpart of sized one, gets returned immediately, because it's of size one, return value = 2. And then the second part which is sized two, get compared and returned, return value = 3. Now these two return values (2 and 3) gets processed, comparing array[2] and array[3], array[2] is definitely smaller, so it returns 2. Now those two return values (0 and 2) gets processed, comparing the two, we can see the minima is at index 0, of value 1. There's a flaw in your code, at the last part, you should compare array[min1] and array[min2] and return min1 or min2. It's quite a mess, hope you can understand. Another things is my syntax, {data}[index range]
{ "pile_set_name": "StackExchange" }
Q: Recovering a partial PostgreSQL archive I have $PGDATA/base but nothing else. It was taken from an installation after the postgreSQL service was shutdown, so is clean. Is there any way to recreate the other elements in $PGDATA that allow it to be used again - pg_tblspc/, global/ ? FWIW I am running 8.1.23. Thanks A: You've left out so much that your chances of recovering useful data are negligible. pg_clog contains the commit/rollback logs. Without these, the system doesn't know which parts of the database files are valid and which are not. (gross oversimplification, but hey). pg_xlog, the write-ahead logs. Without these, the database can't handle incomplete writes, so it'll see the database files in an incomplete state that might be damaged. Indexes may be corrupt, heap pages might be partially written, etc. global/pg_control, the file that contains the system identifier, transaction wrap-around value, transaction log checkpoint position, and a whole lot more. ... and more. It is vital to follow the instructions in the documentation on how to back up a database. Failure to follow the instructions will result in a useless, unrecoverable backup. Testing backups is also vital. With in-depth analysis and a hacked version of the postgres server binary that was modified for data recovery I expect it might be possible to recover a corrupted version of your data, with duplicate entries in primary keys, broken foreign keys, multiple copies of data that was updated, reappearing deleted rows, etc. This would require some in-depth knowledge of the PostgreSQL server and take some significant time - so you'd be looking at a non-trivial cost and you'd only get back a mangled copy of your data.
{ "pile_set_name": "StackExchange" }
Q: CasperJS script never exits My CasperJS script never stops executing. var casper = require('casper').create(); casper.userAgent('Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36(KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36'); casper.start('https://www.google.co.in/',function(){ casper.wait(3000,function(){ this.echo(this.getTitle()); }); }); casper.run(); A: It only looks as if CasperJS never exits. This is only an issue on windows. You probably see something like this: C:\> casperjs script.js C:\> Some script output More script output _ It has something to do with how CasperJS is installed and invoked. This happens usually when you have something like cygwin installed and then you install CasperJS through NPM. NPM will detect that you have cygwin and create a special batch file to start CasperJS with. There is somewhere a bug how that whole situation is handled, but it doesn't affect the functionality of CasperJS. If you press Enter, you will see the prompt again: C:\> casperjs script.js C:\> Some script output More script output C:\> _ If you would use CasperJS from the master branch on GitHub, you would get a proper exe file which executes without those issues. See Installing from git. This has the advantage that you now can use PhantomJS 2, because it is not possible with the current release of version 1.1-beta3.
{ "pile_set_name": "StackExchange" }
Q: Counting error while calculating large number(e.g. 50!) My code is doing well when I enter small numbers like 10 choose 2, but when it comes to 50 choose 10, its result is wrong, can you tell me what's wrong here? #include <stdio.h> long long int factorial(int n); long long int combn(int n, int k); int main(void) { int n = 0; int k = 0; printf("Enter n and k:\n"); scanf("%d %d", &n, &k); combn(n, k); } long long int combn(int n, int k) { long long int C = 0; C = factorial(n) / (factorial(k) * factorial(n - k)); printf("C %d choose %d = %ld\n", n, k, C); } long long int factorial(int n) { if (n == 1) return 1; else return n * factorial(n - 1); } combn(50, 10) should be 10272278170. A: 50! is a very large number, taking almost 150 bits to represent, The long long datatype provides only 64 bits. So, C can't do the computation the way you're doing it; it overflows. You can use an arbitrary-precision arithmetic package library for this purpose. This kind of library represents numbers with variable numbers of bits, and offers operations that don't overflow. gmp -- the Gnu MP Bignum library, is an example of such a library. There are others. Here's how you might do it with gmp. (not debugged). #include "gmp.h" #include <stdio.h> #include <stdlib.h> #include <assert.h> int main(int argc, char * argv[]){ uint n; uint m; mpz_t nn; mpz_t mmn; mpz_t mmm; mpz_t denom; mpz_t result; char * str; if (argc <= 2){ printf ("Usage: %s <number> <number> \n", argv[0]); return 1; } n = atoi(argv[1]); m = atoi(argv[2]); mpz_fac_ui (nn,n); /* nn = n! */ mpz_fac_ui (mmn,n-m); /* mmn = (n-m)! */ mpz_fac_ui (mmm,m); /* mmm = m! */ mpz_mul(denom, mmm, mmn); /* denom = mmn * mmm */ mpz_fdiv_q(result, nn, denom); /* result = nn / denom */ str = mpz_get_str (null, 10, const mpz_t result); printf ("deal %d from %d: %s combinations\n", n,m, str); free (str); mpz_clear(nn); mpz_clear(mmm); mpz_clear(mmn); mpz_clear(denom); mpz_clear(result); return 0; } Another possibility: take advantage of the fact that (n!) / (n-m)! is equal to the product of the integers from (m+1 to n). For example 50!/ 47! is 48 * 49 * 50. That should, in many cases, keep your integers representable in 64 bits. And, even better when you're doing this kind of computer arithmetic, you don't have to perform an actual division operation because it falls right out of the formulas.
{ "pile_set_name": "StackExchange" }
Q: Turbo shaft broken Ford Fiesta 1.4 diesel TDCI There was a rattling noise. Checked and found that noise is due to damaged turbo turbine. So turbo replaced. But after replacement with new turbo and 10KMS road test, the noise returned. Checked and found the turbo turbine damaged from same side. A: A common problem is that gunk builds up in the oil feed pipes to the turbo which restricts the flow of oil to the turbo bearings. This then causes rapid failure of the new turbo. Some manufactures require that you replace the oil feed pipes when fitting a new turbo for this reason.
{ "pile_set_name": "StackExchange" }
Q: How to open and read a file in the src/my/package folder? I would like to load the contents of a text file in a String. The text file should stay in the same folder src/my/package as the .java. However, I can't find the path to this file: I have tried: File f = new File("src/my/package/file.js"); File f = new File("file.js"); and many others but nothing worked. What is the correct path to my file? A: To open files located on the classpath, use the Class.getResource() family of methods. They work even if the file is inside a jar file with your classes. So something like InputStream is = getClass().getResourceAsStream("/my/package/file.js");
{ "pile_set_name": "StackExchange" }
Q: Stuck at ElasticSearch GroupBy query I have this SQL query and EVENT table in my Oracle database. SELECT * FROM (SELECT CITY, max(DATE) AS eventdate FROM EVENT WHERE TYPE = 'CRASH' GROUP BY CITY ORDER BY eventdate DESC, CITY ASC) WHERE ROWNUM < 6; NEW YORK 15/02/27 LONDON 15/02/27 LONDON 15/02/27 LONDON 15/02/11 LONDON 15/02/19 EVENT: ID, NAME, DATE, CITY, TYPE I want to do the same query in ElasticSearch using JavaAPI. Is it possible? I am a beginner, don't know how to start. The documentation doesnt have any examples for my case or I'cant see them. I must know 6 cities that have the latest events and their dates. Then I will ask ElasticSearch for 3 last events for these cities. I think I must do two queries as it is not possible to have result like this in one response: CITY->listOf3LastEvents, CITY2->listOf3LastEvents, City3->listOf3LastEvents A: Ok, let's say your event documents are simply modeled like this: { "id": 123, "name": "Some event name", "event_date": "2016-09-02T12:00:00.000Z", "city": "New York", "type": "CRASH" } Now let's create an index with a reasonable mapping for the above document: PUT events { "mappings": { "event": { "properties": { "id": { "type": "long" }, "type": { "type": "string", "index": "not_analyzed" }, "event_date": { "type": "date" }, "city": { "type": "string", "fields": { "raw": { "type": "string", "index": "not_analyzed" } } }, "name": { "type": "string" } } } } } We can now index the above document (+ a few others) with the following command: PUT events/event/123 { "id": 123, "name": "Some event name", "event_date": "2016-09-02T12:00:00.000Z", "city": "New York", "type": "CRASH" } Finally, you'll be able to send a query that is equivalent to your SQL query like this: POST events/event/_search { "size": 0, "query": { "term": { "type": "CRASH" } }, "aggs": { "cities": { "terms": { "field": "city.raw", "size": 6, "order": { "latest": "desc" } }, "aggs": { "latest": { "max": { "field": "event_date" } }, "last_3_events": { "top_hits": { "size": 3, "sort": { "event_date": "desc" } } } } } } }
{ "pile_set_name": "StackExchange" }