qid
int64
1
74.7M
question
stringlengths
22
28.7k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
24
26.4k
response_k
stringlengths
25
24.2k
24,153
We have bought a few different kinds of cloth napkins for our dinner table and they seem to always come out of the dryer covered in tiny fine hairs. [![hairs](https://i.stack.imgur.com/qfdFK.jpg)](https://i.stack.imgur.com/qfdFK.jpg) How do I get rid of these? I wash them with our kitchen towels and dry them on high with a dryer sheet.
2020/10/22
[ "https://lifehacks.stackexchange.com/questions/24153", "https://lifehacks.stackexchange.com", "https://lifehacks.stackexchange.com/users/24887/" ]
The rubberized printing responds well to several applications of felt marker. In your case, choose a permanent marker in dark blue. Use a hatching stroke at 45 degree angle to completely cover the printing. If the marker touches the base fabric, it will not be too noticeable. Repeat this the next day or two. The colour does a good job of camouflaging the logo. I have done this method on T-shirt logos, usually black polypropylene. The marker fades a bit and can be touched up.
One approach would be to avoid *removing* the logo, and rather, sew some kind of patch over it. Like maybe a RISC-V logo for good measure. Unfortunately, this would be non-trivial to do without puncturing the insulation - you would have to only pierce the fabric and not go any deeper, coming back out through it.
5,492,739
I have the following pesudocode: ``` public void sendPB(ObjectId userId, Message.Builder mb) { if (userId is logged in to server) { set mb.ackId to random chars lookup socket and send mb.build() } else { forward message to user's server via RMI } } ``` The problem is Message.Builders do not implement Serializable, so you cannot send it directly via RMI. Is there an easy way to do this? I've tried building partial PB from the builder and sending that over, but in order to reconstruct it you need to know the type or the Descriptor. Descriptor doesn't implement Serializable either. Thanks
2011/03/30
[ "https://Stackoverflow.com/questions/5492739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/417819/" ]
You could host a [WebBrowser](http://msdn.microsoft.com/en-us/library/cc491073.aspx) control in it's own window and open that window from your button click: Window Hosting the BrowserControl: ``` <Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <DockPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <WebBrowser x:Name="Browser" ></WebBrowser> </DockPanel> ``` In the click event of your button, use the WebBrowser control's [Navigate](http://msdn.microsoft.com/en-us/library/cc491252.aspx) method: ``` Window1 w = new Window1(); w.Browser.Navigate(new Uri("http://stackoverflow.com")); w.Show(); ```
To launch the user's default browser to a specific web page you can do the following: ``` System.Diagnostics.Process.Start("http://www.google.com"); ```
5,492,739
I have the following pesudocode: ``` public void sendPB(ObjectId userId, Message.Builder mb) { if (userId is logged in to server) { set mb.ackId to random chars lookup socket and send mb.build() } else { forward message to user's server via RMI } } ``` The problem is Message.Builders do not implement Serializable, so you cannot send it directly via RMI. Is there an easy way to do this? I've tried building partial PB from the builder and sending that over, but in order to reconstruct it you need to know the type or the Descriptor. Descriptor doesn't implement Serializable either. Thanks
2011/03/30
[ "https://Stackoverflow.com/questions/5492739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/417819/" ]
You could host a [WebBrowser](http://msdn.microsoft.com/en-us/library/cc491073.aspx) control in it's own window and open that window from your button click: Window Hosting the BrowserControl: ``` <Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <DockPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <WebBrowser x:Name="Browser" ></WebBrowser> </DockPanel> ``` In the click event of your button, use the WebBrowser control's [Navigate](http://msdn.microsoft.com/en-us/library/cc491252.aspx) method: ``` Window1 w = new Window1(); w.Browser.Navigate(new Uri("http://stackoverflow.com")); w.Show(); ```
``` Process.Start(new ProcessStartInfo("https://www.example.com") { UseShellExecute = true }); ``` Note that I'm setting `UseShellExecute = true` The default is `true` on **.Net Framework**, and `false` on **.Net Core** apps. You need to set UseShellExecute to `true` if you want to open a url using the default browser.
5,492,739
I have the following pesudocode: ``` public void sendPB(ObjectId userId, Message.Builder mb) { if (userId is logged in to server) { set mb.ackId to random chars lookup socket and send mb.build() } else { forward message to user's server via RMI } } ``` The problem is Message.Builders do not implement Serializable, so you cannot send it directly via RMI. Is there an easy way to do this? I've tried building partial PB from the builder and sending that over, but in order to reconstruct it you need to know the type or the Descriptor. Descriptor doesn't implement Serializable either. Thanks
2011/03/30
[ "https://Stackoverflow.com/questions/5492739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/417819/" ]
To launch the user's default browser to a specific web page you can do the following: ``` System.Diagnostics.Process.Start("http://www.google.com"); ```
``` Process.Start(new ProcessStartInfo("https://www.example.com") { UseShellExecute = true }); ``` Note that I'm setting `UseShellExecute = true` The default is `true` on **.Net Framework**, and `false` on **.Net Core** apps. You need to set UseShellExecute to `true` if you want to open a url using the default browser.
2,597,610
What are cons to write and manage CSS in notepad? in compare to any css IDE? specially in team environment? How much it will effect to project timeline if we are forced to use notepad. should we always use an IDE for CSS?
2010/04/08
[ "https://Stackoverflow.com/questions/2597610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84201/" ]
1. No Auto-intelligence 2. Need to remember each keyword and syntax 3. No Formatting and alignment 4. No Rapid Development 5. No Syntax Highlighter 6. No CSS Checker and Validator 7. No CSS Beautifier 8. No Code collapse functionality
I use [Notepad++](http://notepad-plus.sourceforge.net/uk/site.htm) for editing my CSS and one of the things it does better than Notepad is syntax highlighting and occassionally formatting and indentation. Syntax highlighting isn't that important for CSS but at least having an editor with that does cut down on typo errors.
2,597,610
What are cons to write and manage CSS in notepad? in compare to any css IDE? specially in team environment? How much it will effect to project timeline if we are forced to use notepad. should we always use an IDE for CSS?
2010/04/08
[ "https://Stackoverflow.com/questions/2597610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84201/" ]
1. No Auto-intelligence 2. Need to remember each keyword and syntax 3. No Formatting and alignment 4. No Rapid Development 5. No Syntax Highlighter 6. No CSS Checker and Validator 7. No CSS Beautifier 8. No Code collapse functionality
If it's only cons: * you're not able to automatically format your CSS code you will need to do indentation yourself * prone to errors nobody writes perfect codes, and without an IDE, chances is there will be errors here and there * No inline code hinting you probably need to know what to type, for there are no hinting what values are able to be entered for that property. * no syntax highlighting stop straining your eyes! But for me, time is precious. I'll rather open CSS files and edit them in Notepad, rather than spending some time opening, saving code and closing an IDE just to edit few lines of CSS code.
50,032,511
I get error. The reason i get the error is when there are no more files with .mp4 in directory. My goal is for it start when there is a .mp4 file in the directory, but having trouble figuring out loops. ``` File "C:\PUBG\nn.py", line 8, in <module> newest = max(glob.iglob('*.[Mm][Pp]4'), ke ValueError: max() arg is an empty sequence ``` --- ``` import os import glob import numpy as np import cv2 os.chdir('C:/Users/Main/Videos/PUBG/') newest = max(glob.iglob('*.[Mm][Pp]4'), key=os.path.getctime) os.replace((newest), 'replay.mp4') if newest != max(glob.iglob('*.[Mm][Pp]4'), key=os.path.getctime): cap = cv2.VideoCapture('C:/Users/Main/Videos/PUBG/replay.mp4') def rescale_frame(frame, percent=25): width = int(frame.shape[1] * percent/ 100) height = int(frame.shape[0] * percent/ 100) dim = (width, height) return cv2.resize(frame, dim, interpolation =cv2.INTER_AREA) while True: ret ,frame = cap.read() if type(frame) == type(None): break frame25 = rescale_frame(frame, percent=25) cv2.imshow('frame25',frame25) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() os.remove('replay.mp4') ```
2018/04/25
[ "https://Stackoverflow.com/questions/50032511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9699843/" ]
Asterisk is PBX, main goal is manage calls, not provide you "very simple" api for access it. If you want work with asterisk, you HAVE understand how dialplan and channels works, so you need read general book like ORelly's "Asterisk the future of telephony". After that you can use db-driven dialplan or **AGI** script(but still need dialplan). You also can use **AMI** interface or **ARI**(very similar to REST you know). But anyway for any control method you have understand dialplan, sorry. <https://wiki.asterisk.org/wiki/display/AST/Getting+Started+with+ARI> <https://wiki.asterisk.org/wiki/display/AST/Getting+Started+with+ARI> <https://wiki.asterisk.org/wiki/display/AST/AMI+Libraries+and+Frameworks>
bro sorry to tell you here you post code errors and they will tell the answer if you want to learn than go to brad Traversy Tutorials and if you wanna do it on some MVC like Laravel then use php artisan make:Auth
21,452,238
I have following JS method which variable percentageValue returns correct if the number is positive number but if the number is negative it returns NaN. I don't know how to solve it. ``` function Test() { debugger; var catLength= $("[id$=lblCat]").length; for (var i = 0; i < catLength- 1; i++) { var categoryValue = Number.parseLocale($("[id$=" + i + "_lblCat]")[0].title); var percentageValue = Number.parseLocale(($("[id$=" + i + "_txtPercentage]")[0].value).replace("%", "")); } } ```
2014/01/30
[ "https://Stackoverflow.com/questions/21452238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1301587/" ]
You can use standard `parseInt` : ``` var a = parseInt("-2"); var b = parseInt("2"); ``` <http://jsfiddle.net/AV4rB/> Standard number object does not have `parseLocale` method: ``` Object.getOwnPropertyNames(Number) ["length", "name", "arguments", "caller", "prototype", "MAX_VALUE", "MIN_VALUE", "NaN", "NEGATIVE_INFINITY", "POSITIVE_INFINITY", "isFinite", "isNaN"] ```
try this ``` function Test() { debugger; var catLength= $("[id$=lblCat]").length; for (var i = 0; i < catLength- 1; i++) { var categoryValue = parseFloat($("[id$=" + i + "_lblCat]")[0].title, 2); var percentageValue = parseFloat(($("[id$=" + i + "_txtPercentage]")[0].value, 2).replace("%", "")); } } ```
21,452,238
I have following JS method which variable percentageValue returns correct if the number is positive number but if the number is negative it returns NaN. I don't know how to solve it. ``` function Test() { debugger; var catLength= $("[id$=lblCat]").length; for (var i = 0; i < catLength- 1; i++) { var categoryValue = Number.parseLocale($("[id$=" + i + "_lblCat]")[0].title); var percentageValue = Number.parseLocale(($("[id$=" + i + "_txtPercentage]")[0].value).replace("%", "")); } } ```
2014/01/30
[ "https://Stackoverflow.com/questions/21452238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1301587/" ]
Is this what you were trying to do ``` var num = $("[id$=" + i + "_txtPercentage]")[0].value).replace("%", ""); //lets say num is 3500 num.toLocaleString();//returns for me 3 500 ``` Documentation: [Number.prototype.toLocaleString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString)
You can use standard `parseInt` : ``` var a = parseInt("-2"); var b = parseInt("2"); ``` <http://jsfiddle.net/AV4rB/> Standard number object does not have `parseLocale` method: ``` Object.getOwnPropertyNames(Number) ["length", "name", "arguments", "caller", "prototype", "MAX_VALUE", "MIN_VALUE", "NaN", "NEGATIVE_INFINITY", "POSITIVE_INFINITY", "isFinite", "isNaN"] ```
21,452,238
I have following JS method which variable percentageValue returns correct if the number is positive number but if the number is negative it returns NaN. I don't know how to solve it. ``` function Test() { debugger; var catLength= $("[id$=lblCat]").length; for (var i = 0; i < catLength- 1; i++) { var categoryValue = Number.parseLocale($("[id$=" + i + "_lblCat]")[0].title); var percentageValue = Number.parseLocale(($("[id$=" + i + "_txtPercentage]")[0].value).replace("%", "")); } } ```
2014/01/30
[ "https://Stackoverflow.com/questions/21452238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1301587/" ]
Is this what you were trying to do ``` var num = $("[id$=" + i + "_txtPercentage]")[0].value).replace("%", ""); //lets say num is 3500 num.toLocaleString();//returns for me 3 500 ``` Documentation: [Number.prototype.toLocaleString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString)
try this ``` function Test() { debugger; var catLength= $("[id$=lblCat]").length; for (var i = 0; i < catLength- 1; i++) { var categoryValue = parseFloat($("[id$=" + i + "_lblCat]")[0].title, 2); var percentageValue = parseFloat(($("[id$=" + i + "_txtPercentage]")[0].value, 2).replace("%", "")); } } ```
21,452,238
I have following JS method which variable percentageValue returns correct if the number is positive number but if the number is negative it returns NaN. I don't know how to solve it. ``` function Test() { debugger; var catLength= $("[id$=lblCat]").length; for (var i = 0; i < catLength- 1; i++) { var categoryValue = Number.parseLocale($("[id$=" + i + "_lblCat]")[0].title); var percentageValue = Number.parseLocale(($("[id$=" + i + "_txtPercentage]")[0].value).replace("%", "")); } } ```
2014/01/30
[ "https://Stackoverflow.com/questions/21452238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1301587/" ]
As you will have gathered, JavaScript's `Number` **has** no `parseLocale` function. You'll need to go back to whatever library you're using that's adding it. If you need to create your own, you may be able to do it like this: ``` (function() { var thousandsep, decimalsep, rexFindThousands, rexFindDecimal; thousandsep = (1200).toLocaleString().replace(/\d/g, '').substring(0, 1); decimalsep = (1.2).toLocaleString().repalce(/\d/g, '').substring(0, 1); if (!thousandsep) { // Big assumption here thousandsep = decimalsep === "." ? "," : "."; } rexFindThousands = new RegExp("\\" + thousandsep, "g"); rexFindDecimals = new RegExp("\\" + decimalsep, "g"); Number.prototype.parseLocaleString = function(str) { str = String(str).replace(rexFindThousands, '').replace(rexFindDecimals, '.'); return parseFloat(str); }; })(); ``` That *attempts* to detect the locale-specific thousands and decimal separators, and then adds a function to `Number` that removes the thousands separator entirely and replaces the decimal separator with `.` (the one used by `parseFloat`), and then returns the result of parsing that using `parseFloat`. But I'll stress that the output of `toLocaleString` is implementation-dependent. The decimal thing is likely to work, but I have no idea how reliable it is for `toLocaleString` to return a string containing a thousands separator, hence the fallback assumption above. Also note that if the string you're parsing has a `%` in it, you'll want to remove that before parsing it. `parseFloat` will stop when it reaches it (returning the number up to that point), but still, it's cleaner. See: * [`Number#toLocaleString`](http://www.ecma-international.org/ecma-262/5.1/#sec-15.7.4.3) * [`parseFloat`](http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.2.3)
try this ``` function Test() { debugger; var catLength= $("[id$=lblCat]").length; for (var i = 0; i < catLength- 1; i++) { var categoryValue = parseFloat($("[id$=" + i + "_lblCat]")[0].title, 2); var percentageValue = parseFloat(($("[id$=" + i + "_txtPercentage]")[0].value, 2).replace("%", "")); } } ```
21,452,238
I have following JS method which variable percentageValue returns correct if the number is positive number but if the number is negative it returns NaN. I don't know how to solve it. ``` function Test() { debugger; var catLength= $("[id$=lblCat]").length; for (var i = 0; i < catLength- 1; i++) { var categoryValue = Number.parseLocale($("[id$=" + i + "_lblCat]")[0].title); var percentageValue = Number.parseLocale(($("[id$=" + i + "_txtPercentage]")[0].value).replace("%", "")); } } ```
2014/01/30
[ "https://Stackoverflow.com/questions/21452238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1301587/" ]
Is this what you were trying to do ``` var num = $("[id$=" + i + "_txtPercentage]")[0].value).replace("%", ""); //lets say num is 3500 num.toLocaleString();//returns for me 3 500 ``` Documentation: [Number.prototype.toLocaleString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString)
As you will have gathered, JavaScript's `Number` **has** no `parseLocale` function. You'll need to go back to whatever library you're using that's adding it. If you need to create your own, you may be able to do it like this: ``` (function() { var thousandsep, decimalsep, rexFindThousands, rexFindDecimal; thousandsep = (1200).toLocaleString().replace(/\d/g, '').substring(0, 1); decimalsep = (1.2).toLocaleString().repalce(/\d/g, '').substring(0, 1); if (!thousandsep) { // Big assumption here thousandsep = decimalsep === "." ? "," : "."; } rexFindThousands = new RegExp("\\" + thousandsep, "g"); rexFindDecimals = new RegExp("\\" + decimalsep, "g"); Number.prototype.parseLocaleString = function(str) { str = String(str).replace(rexFindThousands, '').replace(rexFindDecimals, '.'); return parseFloat(str); }; })(); ``` That *attempts* to detect the locale-specific thousands and decimal separators, and then adds a function to `Number` that removes the thousands separator entirely and replaces the decimal separator with `.` (the one used by `parseFloat`), and then returns the result of parsing that using `parseFloat`. But I'll stress that the output of `toLocaleString` is implementation-dependent. The decimal thing is likely to work, but I have no idea how reliable it is for `toLocaleString` to return a string containing a thousands separator, hence the fallback assumption above. Also note that if the string you're parsing has a `%` in it, you'll want to remove that before parsing it. `parseFloat` will stop when it reaches it (returning the number up to that point), but still, it's cleaner. See: * [`Number#toLocaleString`](http://www.ecma-international.org/ecma-262/5.1/#sec-15.7.4.3) * [`parseFloat`](http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.2.3)
10,163,862
My binding does not work. I searched for the error but I don't understand how to fix it in my case. > > System.Windows.Data Error: 1 : Cannot create default converter to perform 'one-way' conversions between types 'MyApplication.MyUserControl' and 'MyApplication.Person'. Consider using Converter property of Binding. BindingExpression:Path=; DataItem='MyUserControl' (Name=''); target element is 'MyUserControl' (Name=''); target property is 'PersonInfo' (type 'Person') > > > System.Windows.Data Error: 5 : Value produced by BindingExpression is not valid for target property.; Value='MyApplication.MyUserControl' BindingExpression:Path=; DataItem='MyUserControl' (Name=''); target element is 'MyUserControl' (Name=''); target property is 'PersonInfo' (type 'Person') > > > Basically it's a ListView that is bound to a ObservableCollection of the class Person. **MainWindow.xaml.cs** ``` public partial class MainWindow : Window { public ObservableCollection<Person> PersonCollection { set; get; } public MainWindow() { PersonCollection = new ObservableCollection<Person>(); InitializeComponent(); PersonCollection.Add(new Person() { Name = "Bob", Age = 20 }); } } ``` **MainWindow.xaml** ``` <Window DataContext="{Binding RelativeSource={RelativeSource Self}}" xmlns:self="clr-namespace:MyApplication" x:Class="MyApplication.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <ListView ItemsSource="{Binding PersonCollection}"> <ListView.ItemTemplate> <DataTemplate> <StackPanel> <self:MyUserControl PersonInfo="{Binding}" /> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> </Window> ``` **MyUserControl.xaml.cs** ``` public partial class MyUserControl : UserControl { public static readonly DependencyProperty PersonProperty = DependencyProperty.Register("PersonInfo", typeof(Person), typeof(MyUserControl)); public Person PersonInfo { get { return (Person)GetValue(PersonProperty); } set { SetValue(PersonProperty, value); } } public MyUserControl() { InitializeComponent(); } } ``` **MyUserControl.xaml** ``` <UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}" x:Class="MyApplication.MyUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"> <TextBlock Text="{Binding PersonInfo.Name}" /> </UserControl> ``` **Person.cs** ``` public class Person : INotifyPropertyChanged { public int Age { set; get; } public string Name { set; get; } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String info) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(info)); } } ```
2012/04/15
[ "https://Stackoverflow.com/questions/10163862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989715/" ]
I can't quite understand why you would make it that complicated. You could easily bind your UserControl without the `PersonInfo` property and without modifying its DataContext. ``` <UserControl x:Class="MyApplication.MyUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"> <TextBlock Text="{Binding Name}" /> </UserControl> ``` Then place the UserControl in a DataTemplate without an explicit binding. Its DataContext will then already contain a Person object. ``` <DataTemplate> <StackPanel> <self:MyUserControl /> </StackPanel> </DataTemplate> ```
Change your UserControl XAML to ``` <UserControl x:Class="MyApplication.MyUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"> <TextBlock DataContext="{Binding RelativeSource={RelativeSource AncestorType=UserControl}}" Text="{Binding PersonInfo.Name}" /> </UserControl> ``` Here is a [good explanation](http://www.scottlogic.co.uk/blog/colin/2012/02/a-simple-pattern-for-creating-re-useable-usercontrols-in-wpf-silverlight/) for the problem with DataContext.
10,163,862
My binding does not work. I searched for the error but I don't understand how to fix it in my case. > > System.Windows.Data Error: 1 : Cannot create default converter to perform 'one-way' conversions between types 'MyApplication.MyUserControl' and 'MyApplication.Person'. Consider using Converter property of Binding. BindingExpression:Path=; DataItem='MyUserControl' (Name=''); target element is 'MyUserControl' (Name=''); target property is 'PersonInfo' (type 'Person') > > > System.Windows.Data Error: 5 : Value produced by BindingExpression is not valid for target property.; Value='MyApplication.MyUserControl' BindingExpression:Path=; DataItem='MyUserControl' (Name=''); target element is 'MyUserControl' (Name=''); target property is 'PersonInfo' (type 'Person') > > > Basically it's a ListView that is bound to a ObservableCollection of the class Person. **MainWindow.xaml.cs** ``` public partial class MainWindow : Window { public ObservableCollection<Person> PersonCollection { set; get; } public MainWindow() { PersonCollection = new ObservableCollection<Person>(); InitializeComponent(); PersonCollection.Add(new Person() { Name = "Bob", Age = 20 }); } } ``` **MainWindow.xaml** ``` <Window DataContext="{Binding RelativeSource={RelativeSource Self}}" xmlns:self="clr-namespace:MyApplication" x:Class="MyApplication.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <ListView ItemsSource="{Binding PersonCollection}"> <ListView.ItemTemplate> <DataTemplate> <StackPanel> <self:MyUserControl PersonInfo="{Binding}" /> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> </Window> ``` **MyUserControl.xaml.cs** ``` public partial class MyUserControl : UserControl { public static readonly DependencyProperty PersonProperty = DependencyProperty.Register("PersonInfo", typeof(Person), typeof(MyUserControl)); public Person PersonInfo { get { return (Person)GetValue(PersonProperty); } set { SetValue(PersonProperty, value); } } public MyUserControl() { InitializeComponent(); } } ``` **MyUserControl.xaml** ``` <UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}" x:Class="MyApplication.MyUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"> <TextBlock Text="{Binding PersonInfo.Name}" /> </UserControl> ``` **Person.cs** ``` public class Person : INotifyPropertyChanged { public int Age { set; get; } public string Name { set; get; } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String info) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(info)); } } ```
2012/04/15
[ "https://Stackoverflow.com/questions/10163862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989715/" ]
Although you fixed your problem, your entire Binding code seems wrong to me, so I propose this alternative: Have a base class for all binding source objects - **ObservableObject.cs** ``` public abstract class ObservableObject : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { var handler = this.PropertyChanged; if (handler != null) handler(this, e); } protected void SetValue<T>(ref T field, T value, string propertyName) { if (!EqualityComparer<T>.Default.Equals(field, value)) { field = value; this.OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); } } } ``` Have a view model for your MainWindow - **MainWindowModel.cs** ``` public class MainWindowModel : ObservableObject { private readonly ObservableCollection<Person> personCollection = new ObservableCollection<Person>() { new Person() { Name = "Bob", Age = 20 } }; public ObservableCollection<Person> PersonCollection { get { return this.personCollection; } } } ``` **MainWindow.xaml.cs** is now basically empty. ``` public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } } ``` **MainWindow.xaml** sets DataContext to new MainWindowModel instance. ``` <Window x:Class="MyApplication.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:self="clr-namespace:MyApplication"> <Window.DataContext> <self:MainWindowModel/> </Window.DataContext> <ListView ItemsSource="{Binding PersonCollection}"> <ListView.ItemTemplate> <DataTemplate> <StackPanel> <self:MyUserControl/> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> </Window> ``` **MyUserControl.xaml.cs** is also basically empty (contains only auto-generated code). ``` public partial class MyUserControl : UserControl { public MyUserControl() { InitializeComponent(); } } ``` **MyUserControl.xaml** ``` <UserControl x:Class="MyApplication.MyUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <TextBlock Text="{Binding Name}"/> </UserControl> ``` **Person.cs** ``` public class Person : ObservableObject { private int age; private string name; public int Age { get { return this.age; } set { this.SetValue(ref this.age, value, "Age"); } } public string Name { get { return this.name; } set { this.SetValue(ref this.name, value, "Name"); } } } ```
Change your UserControl XAML to ``` <UserControl x:Class="MyApplication.MyUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"> <TextBlock DataContext="{Binding RelativeSource={RelativeSource AncestorType=UserControl}}" Text="{Binding PersonInfo.Name}" /> </UserControl> ``` Here is a [good explanation](http://www.scottlogic.co.uk/blog/colin/2012/02/a-simple-pattern-for-creating-re-useable-usercontrols-in-wpf-silverlight/) for the problem with DataContext.
10,163,862
My binding does not work. I searched for the error but I don't understand how to fix it in my case. > > System.Windows.Data Error: 1 : Cannot create default converter to perform 'one-way' conversions between types 'MyApplication.MyUserControl' and 'MyApplication.Person'. Consider using Converter property of Binding. BindingExpression:Path=; DataItem='MyUserControl' (Name=''); target element is 'MyUserControl' (Name=''); target property is 'PersonInfo' (type 'Person') > > > System.Windows.Data Error: 5 : Value produced by BindingExpression is not valid for target property.; Value='MyApplication.MyUserControl' BindingExpression:Path=; DataItem='MyUserControl' (Name=''); target element is 'MyUserControl' (Name=''); target property is 'PersonInfo' (type 'Person') > > > Basically it's a ListView that is bound to a ObservableCollection of the class Person. **MainWindow.xaml.cs** ``` public partial class MainWindow : Window { public ObservableCollection<Person> PersonCollection { set; get; } public MainWindow() { PersonCollection = new ObservableCollection<Person>(); InitializeComponent(); PersonCollection.Add(new Person() { Name = "Bob", Age = 20 }); } } ``` **MainWindow.xaml** ``` <Window DataContext="{Binding RelativeSource={RelativeSource Self}}" xmlns:self="clr-namespace:MyApplication" x:Class="MyApplication.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <ListView ItemsSource="{Binding PersonCollection}"> <ListView.ItemTemplate> <DataTemplate> <StackPanel> <self:MyUserControl PersonInfo="{Binding}" /> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> </Window> ``` **MyUserControl.xaml.cs** ``` public partial class MyUserControl : UserControl { public static readonly DependencyProperty PersonProperty = DependencyProperty.Register("PersonInfo", typeof(Person), typeof(MyUserControl)); public Person PersonInfo { get { return (Person)GetValue(PersonProperty); } set { SetValue(PersonProperty, value); } } public MyUserControl() { InitializeComponent(); } } ``` **MyUserControl.xaml** ``` <UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}" x:Class="MyApplication.MyUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"> <TextBlock Text="{Binding PersonInfo.Name}" /> </UserControl> ``` **Person.cs** ``` public class Person : INotifyPropertyChanged { public int Age { set; get; } public string Name { set; get; } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String info) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(info)); } } ```
2012/04/15
[ "https://Stackoverflow.com/questions/10163862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989715/" ]
I can't quite understand why you would make it that complicated. You could easily bind your UserControl without the `PersonInfo` property and without modifying its DataContext. ``` <UserControl x:Class="MyApplication.MyUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"> <TextBlock Text="{Binding Name}" /> </UserControl> ``` Then place the UserControl in a DataTemplate without an explicit binding. Its DataContext will then already contain a Person object. ``` <DataTemplate> <StackPanel> <self:MyUserControl /> </StackPanel> </DataTemplate> ```
Although you fixed your problem, your entire Binding code seems wrong to me, so I propose this alternative: Have a base class for all binding source objects - **ObservableObject.cs** ``` public abstract class ObservableObject : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { var handler = this.PropertyChanged; if (handler != null) handler(this, e); } protected void SetValue<T>(ref T field, T value, string propertyName) { if (!EqualityComparer<T>.Default.Equals(field, value)) { field = value; this.OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); } } } ``` Have a view model for your MainWindow - **MainWindowModel.cs** ``` public class MainWindowModel : ObservableObject { private readonly ObservableCollection<Person> personCollection = new ObservableCollection<Person>() { new Person() { Name = "Bob", Age = 20 } }; public ObservableCollection<Person> PersonCollection { get { return this.personCollection; } } } ``` **MainWindow.xaml.cs** is now basically empty. ``` public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } } ``` **MainWindow.xaml** sets DataContext to new MainWindowModel instance. ``` <Window x:Class="MyApplication.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:self="clr-namespace:MyApplication"> <Window.DataContext> <self:MainWindowModel/> </Window.DataContext> <ListView ItemsSource="{Binding PersonCollection}"> <ListView.ItemTemplate> <DataTemplate> <StackPanel> <self:MyUserControl/> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> </Window> ``` **MyUserControl.xaml.cs** is also basically empty (contains only auto-generated code). ``` public partial class MyUserControl : UserControl { public MyUserControl() { InitializeComponent(); } } ``` **MyUserControl.xaml** ``` <UserControl x:Class="MyApplication.MyUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <TextBlock Text="{Binding Name}"/> </UserControl> ``` **Person.cs** ``` public class Person : ObservableObject { private int age; private string name; public int Age { get { return this.age; } set { this.SetValue(ref this.age, value, "Age"); } } public string Name { get { return this.name; } set { this.SetValue(ref this.name, value, "Name"); } } } ```
8,959,338
I draw the sphere by OpenGL. This program can draw sphere when "SLIED = STACK". But It's doesn't work when "SLIED not equal STACK". I may be mistake "index array". I want to use VBO and DMA(Dynamic memory allocate.use flat array). But If You have another good idea, teach me. ``` //#pragma comment(linker, "/SUBSYSTEM:WINDOWS /ENTRY:mainCRTStartup") #pragma comment(lib,"glew32.lib") #include <gl/glew.h> #include <math.h> #include <GL/freeglut/freeglut.h> #define WIDTH 640 #define HEIGHT 480 #define M_PI 3.14159265358979323846 float angle=0.0f; //functions----------------------------------------------// void Shere_dma(double radius, int nSlice, int nStack); void setSphereData(double radius, int nSlice, int nStack); void DrawSphereVBO(void); //-------------------------------------------------------// //variabless---------------------------------------------// int SLICE=0; int STACK=0; GLuint SVboId[3]; GLfloat* Svertex;//Vertex GLfloat* Snormal;//Normal GLfloat* Scolor; //Color GLuint* indices_top; //TOP indices GLuint* indices_bottom; //BOTTOM indies GLuint* indices_side; //SIDE indices //-------------------------------------------------------// //Memory Allocate void Shere_dma(double radius, int nSlice, int nStack){ Svertex = new GLfloat[(nSlice+1)*(nStack+1)*3]; Snormal = new GLfloat[(nSlice+1)*(nStack+1)*3]; Scolor = new GLfloat[(nSlice+1)*(nStack+1)*3]; indices_top = new GLuint[(nSlice+1)*(nStack+1)*3]; indices_bottom = new GLuint[(nSlice+1)*(nStack+1)*3]; indices_side = new GLuint[(nSlice+1)*(nStack+1)*4]; } //inputData void setSphereData(double radius, int nSlice, int nStack){ double phi; //Azimuth double theta; //long int coordinates=0; int Slice_current_point_no=0; int Slice_next_point_no=0; const int x = 0; const int y = 1; const int z = 2; const int p1 = 0; const int p2 = 1; const int p3 = 2; const int p4 = 3; //Vertex for(int i = 0;i <= nSlice;i++) { phi = 2.0 * M_PI * (double)i / (double)nSlice; for(int j = 0;j <= nStack;j++) { theta = M_PI * (double)j / (double)nStack; Svertex[coordinates+x] = (float)(radius * sin(theta) * cos(phi)); //x Svertex[coordinates+y] = (float)(radius * sin(theta) * sin(phi)); //y Svertex[coordinates+z] = (float)(radius * cos(theta)); //z Snormal[coordinates+x] = (float)(radius * sin(theta) * cos(phi)); //x Snormal[coordinates+y] = (float)(radius * sin(theta) * sin(phi)); //y Snormal[coordinates+z] = (float)(radius * cos(theta)); //z Scolor[coordinates+x] = 1.0; //x Scolor[coordinates+y] = 0.0; //y Scolor[coordinates+z] = 0.0; //z coordinates += 3; } } //TOP coordinates = 0; Slice_current_point_no = 0; Slice_next_point_no = nSlice; for(int i = 0; i < nSlice; i++){ indices_top[coordinates+p1] = Slice_current_point_no; indices_top[coordinates+p2] = indices_top[coordinates]+1; indices_top[coordinates+p3] = Slice_next_point_no+2; coordinates+=3; Slice_current_point_no += nSlice+1; Slice_next_point_no += nSlice+1; } //BOTTOM coordinates =0; Slice_current_point_no = 0; Slice_next_point_no = nSlice; for(int i = 0; i < nSlice; i++){ indices_bottom[coordinates+p1] = Slice_current_point_no+(nStack-1); indices_bottom[coordinates+p2] = indices_bottom[coordinates]+1; indices_bottom[coordinates+p3] = Slice_next_point_no+(nStack); coordinates+=3; Slice_current_point_no += nSlice+1; Slice_next_point_no += nSlice+1; } //↓May be wrong ********************************************************************************// //SIDE coordinates=0; Slice_current_point_no = 0; Slice_next_point_no = nSlice+1; for(int i=0; i < nSlice;i++){ for(int j=1; j < nStack-1; j++){ indices_side[coordinates+p1] = Slice_current_point_no+j; indices_side[coordinates+p2] = indices_side[coordinates]+1; indices_side[coordinates+p3] = Slice_next_point_no+(j+1); indices_side[coordinates+p4] = Slice_next_point_no+j; coordinates+=4; } Slice_current_point_no += nSlice+1; Slice_next_point_no += nSlice+1; } //↑May be wrong ********************************************************************************// glGenBuffers(3,&SVboId[0]); //Vertex glBindBuffer(GL_ARRAY_BUFFER,SVboId[0]); glBufferData(GL_ARRAY_BUFFER,sizeof(GLfloat)*(nSlice+1)*(nStack+1)*3, Svertex,GL_DYNAMIC_DRAW); //Normal glBindBuffer(GL_ARRAY_BUFFER,SVboId[1]); glBufferData(GL_ARRAY_BUFFER,sizeof(GLfloat)*(nSlice+1)*(nStack+1)*3, Snormal,GL_DYNAMIC_DRAW); //Color glBindBuffer(GL_ARRAY_BUFFER,SVboId[2]); glBufferData(GL_ARRAY_BUFFER,sizeof(GLfloat)*(nSlice+1)*(nStack+1)*3, Scolor,GL_STREAM_DRAW); } //Draw void DrawSphereVBO(void) { int point=0; //Enable glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_COLOR_ARRAY); //Vertex glBindBuffer(GL_ARRAY_BUFFER,SVboId[0]); glVertexPointer(3, GL_FLOAT, 0, 0); //Normal glBindBuffer(GL_ARRAY_BUFFER,SVboId[1]); glNormalPointer(GL_FLOAT, 0, 0); //Color glBindBuffer(GL_ARRAY_BUFFER,SVboId[2]); glColorPointer(3,GL_FLOAT, 0, 0); //---------------------------------Draw---------------------------------------------------// //TOP for(int i=0; i<SLICE;i++){ glDrawRangeElements(GL_TRIANGLES, point, point+2, 3, GL_UNSIGNED_INT, indices_top+i*3); point+=3; } //BOTTOM point=0; for(int i=0; i<SLICE;i++){ glDrawRangeElements(GL_TRIANGLES, point, point+2, 3, GL_UNSIGNED_INT, indices_bottom+i*3); point+=3; } //↓May be wrong ********************************************************************************// //SIDE point=0; for(int i=0; i< (SLICE*(STACK-2));i++){ glDrawRangeElements(GL_QUADS, point, point+3, 4, GL_UNSIGNED_INT, indices_side+i*4); point+=4; } //↑May be wrong ********************************************************************************// //---------------------------------Draw---------------------------------------------------// //Disable glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); } void display(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glViewport(0,0,WIDTH,HEIGHT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(30.0, (double)WIDTH / (double)HEIGHT, 1.0, 1000.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(5.0, 5.0,5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); glRotatef(angle,0.0f,1.0f,0.0f); DrawSphereVBO(); glutSwapBuffers(); } void idle(void) { glutPostRedisplay(); angle+=0.2f; } void Init(){ glewInit(); glClearColor(1.0, 1.0, 1.0, 1.0); glEnable(GL_DEPTH_TEST); glColorMaterial(GL_FRONT,GL_AMBIENT_AND_DIFFUSE); glEnable(GL_COLOR_MATERIAL); glEnable(GL_LIGHT0); glEnable(GL_LIGHTING); glEnable(GL_NORMALIZE); SLICE = 5; STACK = 5; Shere_dma(1,SLICE,STACK); //MemoryAllocate setSphereData(1,SLICE,STACK); //InputData } int main(int argc, char *argv[]) { glutInitWindowPosition(100, 100); glutInitWindowSize(WIDTH, HEIGHT); glutInit(&argc, argv); glutCreateWindow("VBO"); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE); glutDisplayFunc(display); glutIdleFunc(idle); Init(); glutMainLoop(); return 0; } ``` I refer to this code. ``` void drawSphere(double radius, int nSlice, int nStack) { int i, j; double phi; // double theta; //long float p[31][31][3]; //Vertex float *p1,*p2,*p3,*p4; if(nSlice > 30) nSlice = 30; if(nStack > 30) nStack = 30; //Vertex for(i = 0;i <= nSlice;i++) { phi = 2.0 * M_PI * (double)i / (double)nSlice; for(j = 0;j <= nStack;j++) { theta = M_PI * (double)j / (double)nStack; p[i][j][0] = (float)(radius * sin(theta) * cos(phi));//x p[i][j][1] = (float)(radius * sin(theta) * sin(phi));//y p[i][j][2] = (float)(radius * cos(theta)); //z } } //Top(j=0) for(i = 0;i < nSlice; i++) { p1 = p[i][0]; p2 = p[i][1]; p3 = p[i+1][1]; glBegin(GL_TRIANGLES); glNormal3fv(p1); glVertex3fv(p1); glNormal3fv(p2); glVertex3fv(p2); glNormal3fv(p3); glVertex3fv(p3); glEnd(); } //Bottom j=nStack-1; for(i = 0;i < nSlice; i++) { p1 = p[i][j]; p2 = p[i][j+1]; p3 = p[i+1][j]; glBegin(GL_TRIANGLES); glNormal3fv(p1); glVertex3fv(p1); glNormal3fv(p2); glVertex3fv(p2); glNormal3fv(p3); glVertex3fv(p3); glEnd(); } for(i = 0;i < nSlice;i++){ for(j = 1;j < nStack-1; j++) { p1 = p[i][j]; p2 = p[i][j+1]; p3 = p[i+1][j+1]; p4 = p[i+1][j]; glBegin(GL_QUADS); glNormal3fv(p1); glVertex3fv(p1); glNormal3fv(p2); glVertex3fv(p2); glNormal3fv(p3); glVertex3fv(p3); glNormal3fv(p4); glVertex3fv(p4); glEnd(); } } } ```
2012/01/22
[ "https://Stackoverflow.com/questions/8959338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1159979/" ]
I've written a tutorial on generating sphere meshes - it doesn't come with source code, but describes the process and walks you through the issues you'll encounter. You can find the tutorial at: <http://sol.gfxile.net/sphere/index.html>
I would recommend using spherical coordinates using two angles phi (elevation) and theta (around) or by using the equation of the sphere: ``` x2 + y2 + z2 = r2 ``` were you keep one of the values constant and increment later as you replace values in the 2nd to find the 3rd value.
6,833,181
I have a text file that contains a years worth of dates with associated dates. I am working with the file from 2009 but its structure is the same in the 2011 file, and will be in the 2012 file. As you can see each date section starts with a 1 and a space followed by a date in mmddyy format: ``` 1 070109 MON JUN 29........ THU JUL 09 TUE JUN 30........ MON JUL 13 WED JUL 01........ MON JUL 13 THU JUL 02........ TUE JUL 14 FRI JUL 03........ TUE JUL 14 CIVIL TRAFFIC MON JUN 29........ WED JUL 29 TUE JUN 30........ THU JUL 30 WED JUL 01........ FRI JUL 31 THU JUL 02........ MON AUG 03 FRI JUL 03........ MON AUG 03 1 070209 TUE JUN 30........ MON JUL 13 WED JUL 01........ MON JUL 13 THU JUL 02........ TUE JUL 14 FRI JUL 03........ TUE JUL 14 SAT JUL 04........ WED JUL 15 CIVIL TRAFFIC TUE JUN 30........ THU JUL 30 WED JUL 01........ FRI JUL 31 THU JUL 02........ MON AUG 03 FRI JUL 03........ MON AUG 03 SAT JUL 04........ TUE AUG 04 ``` What I need to be able to do is retrieve the associated dates listed below each heading date. I want it set up so if the user just wants the dates for 070109, they could just select the button for "Todays Court Dates". If they need court dates for a different date, they would enter the date they want, the text file would be searched for "1 $date" and the associated information would be retrieved and displayed. There's my problem... I have been able to read the file and even diplay the entire file, but I have not figured out how to locate the "1 070109" and then display only the following 12 lines of information
2011/07/26
[ "https://Stackoverflow.com/questions/6833181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/863838/" ]
I would do the following: Place EditText and ListView in your layout. Use BaseAdapter instead of ArrayAdapter. Actually it's the same, but I don't call base.getView(): ``` private class StudentListAdapter : BaseAdapter { private IList<Student> items; private Context outer_context; public StudentListAdapter(Context context, IList<Student> items) { this.items = items; this.outer_context = context; } public override View GetView(int position, View convertView, ViewGroup parent) { LayoutInflater vi = (LayoutInflater)outer_context.GetSystemService(Context.LayoutInflaterService); View v = vi.Inflate(Resource.Layout.ItemStudent, null); Student s = items[position]; v.FindViewById<TextView>(R.id.text_view_id).setText(s.Name); // determine correct risk image ImageView listRisk = v.FindViewById<ImageView>(Resource.Id.listRisk); if (s.R != null) { switch ((int)s.R.Value) { case 1: listRisk.SetImageResource(Resource.Drawable.risk_green); break; case 0: listRisk.SetImageResource(Resource.Drawable.risk_yellow); break; case -1: listRisk.SetImageResource(Resource.Drawable.risk_red); break; case -2: listRisk.SetImageResource(Resource.Drawable.risk_red2); break; default: listRisk.SetImageResource(Resource.Drawable.risk_gray); break; } } else { listRisk.SetImageResource(Resource.Drawable.risk_gray); } return v; } void displayNewData(IList<Student> new_items) { items=new_items; notifyDatasetChanged(); } } ``` So when filter text is changed you just need to put new data to adapter using displayNewData() method: ``` public class StudentsActivity extends Activity { public override void onCreate(Bundle savedInstanceState) { ... filterEditText.addTextChangedListener(filterTextWatcher); } private TextWatcher filterTextWatcher = new TextWatcher() { public void afterTextChanged(Editable s) {} public void beforeTextChanged(CharSequence s, int start, int count,int after) {} public void onTextChanged(CharSequence filter, int start, int before, int count) { IList<Student> items = getStudentsFiltered(filter); adapter.displayNewData(items); } }; //getStudentsFiltered() method may look like that: getStudentsFiltered(String filter) { IList<Student> students_filtered=new List<Students>(); foreach(Student student in students) if(student.Name.Contains(filter)) students_filtered.Add(student); return students_filtered; } } ``` I'm pretty sure this approach will work fine. Feel free to ask any questions. I didn't compile the code so there may be some minor mistakes.
Try instantiating `ImageView listRisk = v.FindViewById<ImageView>(Resource.Id.listRisk)` and then setting the resources, in each case.
6,833,181
I have a text file that contains a years worth of dates with associated dates. I am working with the file from 2009 but its structure is the same in the 2011 file, and will be in the 2012 file. As you can see each date section starts with a 1 and a space followed by a date in mmddyy format: ``` 1 070109 MON JUN 29........ THU JUL 09 TUE JUN 30........ MON JUL 13 WED JUL 01........ MON JUL 13 THU JUL 02........ TUE JUL 14 FRI JUL 03........ TUE JUL 14 CIVIL TRAFFIC MON JUN 29........ WED JUL 29 TUE JUN 30........ THU JUL 30 WED JUL 01........ FRI JUL 31 THU JUL 02........ MON AUG 03 FRI JUL 03........ MON AUG 03 1 070209 TUE JUN 30........ MON JUL 13 WED JUL 01........ MON JUL 13 THU JUL 02........ TUE JUL 14 FRI JUL 03........ TUE JUL 14 SAT JUL 04........ WED JUL 15 CIVIL TRAFFIC TUE JUN 30........ THU JUL 30 WED JUL 01........ FRI JUL 31 THU JUL 02........ MON AUG 03 FRI JUL 03........ MON AUG 03 SAT JUL 04........ TUE AUG 04 ``` What I need to be able to do is retrieve the associated dates listed below each heading date. I want it set up so if the user just wants the dates for 070109, they could just select the button for "Todays Court Dates". If they need court dates for a different date, they would enter the date they want, the text file would be searched for "1 $date" and the associated information would be retrieved and displayed. There's my problem... I have been able to read the file and even diplay the entire file, but I have not figured out how to locate the "1 070109" and then display only the following 12 lines of information
2011/07/26
[ "https://Stackoverflow.com/questions/6833181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/863838/" ]
I would do the following: Place EditText and ListView in your layout. Use BaseAdapter instead of ArrayAdapter. Actually it's the same, but I don't call base.getView(): ``` private class StudentListAdapter : BaseAdapter { private IList<Student> items; private Context outer_context; public StudentListAdapter(Context context, IList<Student> items) { this.items = items; this.outer_context = context; } public override View GetView(int position, View convertView, ViewGroup parent) { LayoutInflater vi = (LayoutInflater)outer_context.GetSystemService(Context.LayoutInflaterService); View v = vi.Inflate(Resource.Layout.ItemStudent, null); Student s = items[position]; v.FindViewById<TextView>(R.id.text_view_id).setText(s.Name); // determine correct risk image ImageView listRisk = v.FindViewById<ImageView>(Resource.Id.listRisk); if (s.R != null) { switch ((int)s.R.Value) { case 1: listRisk.SetImageResource(Resource.Drawable.risk_green); break; case 0: listRisk.SetImageResource(Resource.Drawable.risk_yellow); break; case -1: listRisk.SetImageResource(Resource.Drawable.risk_red); break; case -2: listRisk.SetImageResource(Resource.Drawable.risk_red2); break; default: listRisk.SetImageResource(Resource.Drawable.risk_gray); break; } } else { listRisk.SetImageResource(Resource.Drawable.risk_gray); } return v; } void displayNewData(IList<Student> new_items) { items=new_items; notifyDatasetChanged(); } } ``` So when filter text is changed you just need to put new data to adapter using displayNewData() method: ``` public class StudentsActivity extends Activity { public override void onCreate(Bundle savedInstanceState) { ... filterEditText.addTextChangedListener(filterTextWatcher); } private TextWatcher filterTextWatcher = new TextWatcher() { public void afterTextChanged(Editable s) {} public void beforeTextChanged(CharSequence s, int start, int count,int after) {} public void onTextChanged(CharSequence filter, int start, int before, int count) { IList<Student> items = getStudentsFiltered(filter); adapter.displayNewData(items); } }; //getStudentsFiltered() method may look like that: getStudentsFiltered(String filter) { IList<Student> students_filtered=new List<Students>(); foreach(Student student in students) if(student.Name.Contains(filter)) students_filtered.Add(student); return students_filtered; } } ``` I'm pretty sure this approach will work fine. Feel free to ask any questions. I didn't compile the code so there may be some minor mistakes.
Check tmpView and v. I don't have the Mono stuff so I can't look at the implementation of ArrayAdapter<>. I have seen the issue arise because my view ends up getting added to the parent before I do my population stuff. Default implementations of GetView() will add the view to the parent and return the parent, not the newly inflated view. Doing findViewById() on the parent always returned the same ImageView (the first one in the list perhaps) instead of the ImageView in my newly inflated view. If this is the case don't pass parent to base.GetView(), pass null instead. Add your newly inflated view to the parent at the end of your GetView() implementation.
6,833,181
I have a text file that contains a years worth of dates with associated dates. I am working with the file from 2009 but its structure is the same in the 2011 file, and will be in the 2012 file. As you can see each date section starts with a 1 and a space followed by a date in mmddyy format: ``` 1 070109 MON JUN 29........ THU JUL 09 TUE JUN 30........ MON JUL 13 WED JUL 01........ MON JUL 13 THU JUL 02........ TUE JUL 14 FRI JUL 03........ TUE JUL 14 CIVIL TRAFFIC MON JUN 29........ WED JUL 29 TUE JUN 30........ THU JUL 30 WED JUL 01........ FRI JUL 31 THU JUL 02........ MON AUG 03 FRI JUL 03........ MON AUG 03 1 070209 TUE JUN 30........ MON JUL 13 WED JUL 01........ MON JUL 13 THU JUL 02........ TUE JUL 14 FRI JUL 03........ TUE JUL 14 SAT JUL 04........ WED JUL 15 CIVIL TRAFFIC TUE JUN 30........ THU JUL 30 WED JUL 01........ FRI JUL 31 THU JUL 02........ MON AUG 03 FRI JUL 03........ MON AUG 03 SAT JUL 04........ TUE AUG 04 ``` What I need to be able to do is retrieve the associated dates listed below each heading date. I want it set up so if the user just wants the dates for 070109, they could just select the button for "Todays Court Dates". If they need court dates for a different date, they would enter the date they want, the text file would be searched for "1 $date" and the associated information would be retrieved and displayed. There's my problem... I have been able to read the file and even diplay the entire file, but I have not figured out how to locate the "1 070109" and then display only the following 12 lines of information
2011/07/26
[ "https://Stackoverflow.com/questions/6833181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/863838/" ]
I would do the following: Place EditText and ListView in your layout. Use BaseAdapter instead of ArrayAdapter. Actually it's the same, but I don't call base.getView(): ``` private class StudentListAdapter : BaseAdapter { private IList<Student> items; private Context outer_context; public StudentListAdapter(Context context, IList<Student> items) { this.items = items; this.outer_context = context; } public override View GetView(int position, View convertView, ViewGroup parent) { LayoutInflater vi = (LayoutInflater)outer_context.GetSystemService(Context.LayoutInflaterService); View v = vi.Inflate(Resource.Layout.ItemStudent, null); Student s = items[position]; v.FindViewById<TextView>(R.id.text_view_id).setText(s.Name); // determine correct risk image ImageView listRisk = v.FindViewById<ImageView>(Resource.Id.listRisk); if (s.R != null) { switch ((int)s.R.Value) { case 1: listRisk.SetImageResource(Resource.Drawable.risk_green); break; case 0: listRisk.SetImageResource(Resource.Drawable.risk_yellow); break; case -1: listRisk.SetImageResource(Resource.Drawable.risk_red); break; case -2: listRisk.SetImageResource(Resource.Drawable.risk_red2); break; default: listRisk.SetImageResource(Resource.Drawable.risk_gray); break; } } else { listRisk.SetImageResource(Resource.Drawable.risk_gray); } return v; } void displayNewData(IList<Student> new_items) { items=new_items; notifyDatasetChanged(); } } ``` So when filter text is changed you just need to put new data to adapter using displayNewData() method: ``` public class StudentsActivity extends Activity { public override void onCreate(Bundle savedInstanceState) { ... filterEditText.addTextChangedListener(filterTextWatcher); } private TextWatcher filterTextWatcher = new TextWatcher() { public void afterTextChanged(Editable s) {} public void beforeTextChanged(CharSequence s, int start, int count,int after) {} public void onTextChanged(CharSequence filter, int start, int before, int count) { IList<Student> items = getStudentsFiltered(filter); adapter.displayNewData(items); } }; //getStudentsFiltered() method may look like that: getStudentsFiltered(String filter) { IList<Student> students_filtered=new List<Students>(); foreach(Student student in students) if(student.Name.Contains(filter)) students_filtered.Add(student); return students_filtered; } } ``` I'm pretty sure this approach will work fine. Feel free to ask any questions. I didn't compile the code so there may be some minor mistakes.
One thing I've noticed (while coding in Java and not Mono) is that if you try to do something like this: ``` imageView.setImageResource(R.myResourceID1); imageView.setImageResource(R.myResourceID2); ``` The image displayed will always be myResourceID1. To get around this, someone I work with suggested using this code when you want to set an imageView's resource that is already set. So: ``` imageView.setImageResource(R.myResourceID1); imageView.setImageResource(0); //supposedly invalidates the image resource imageView.setImageResource(R.myResourceID2); ``` Though after reading your update, it seems that if you are filtering after you are setting the imageViews in your getView() method, that this may not be your problem. Thought I would share since setting an already used imageView's resource a 2nd time through getView() sounds like the problem I described above.
7,738,871
``` using System; static class Program { static event Action A = delegate { }; static event Action B = delegate { }; static void Main() { A += B; B += ()=>Console.WriteLine("yeah"); A.Invoke(); } } ``` This doesn't print anything, but if I swap the first two lines of Main, it does.
2011/10/12
[ "https://Stackoverflow.com/questions/7738871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122687/" ]
Events are immutable, i.e. you get a copy when assigning, like integers ``` int a = 1; int b = 2; a += b; // a == 3 b += 1; // a is still 3 ```
A += B; is appending the list of delegates from B into A. It is copying the contents of B, not a reference to B. It is the same as: ``` A = (Action)System.Delegate.Combine(A, B); ``` So the order is definitely important.
25,839,761
I need help with a linq statement. I need to `select * from ZipCodeCarrierRoute` table but only retrieve the child objects from `Contact_CarrierCodeAssignments` and `contacts where Contacts.Active = true`. and help would be appreciated. ![enter image description here](https://i.stack.imgur.com/yZmTx.png) UPDATE: Here is the json response for the solution @Yuliam offered. It;s still not quite right. ![enter image description here](https://i.stack.imgur.com/I6xCM.png)
2014/09/15
[ "https://Stackoverflow.com/questions/25839761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/591208/" ]
If I understand you correctly you want to retrieve `ZipCodeCarrierRoute` that includes only active `Contact_CarrierCodeAssignments`. ``` var query = db.ZipCodeCarrierRoute .Where(x => x.ZipCode == ZipCode) .Select(x => new { ZipCodeCarrierRoute = x, Contact_CarrierCodeAssignments = x.Contact_CarrierCodeAssignments .Where(y => y.Contact.Active) }) .AsEnumerable() .Select(a => a.ZipCodeCarrierRoute); var list = query.ToList(); ```
Here is something I think on top of my head, I didn't test it on a computer or linqpad ``` var query = from zipCodeCR in db.ZipCodeCarrierRoute. where zipCodeCR.Contact_CarrierCodeAssignments.All(contact_codeAssignment => contact_codeAssignment.Contact.Active==true) select zipCodeCR; ```
16,787,038
I am new to R but have turned to it to solve a problem with a large data set I am trying to process. Currently I have a 4 columns of data (Y values) set against minute-interval timestamps (month/day/year hour:min) (X values) as below: ``` timestamp tr tt sr st 1 9/1/01 0:00 1.018269e+02 -312.8622 -1959.393 4959.828 2 9/1/01 0:01 1.023567e+02 -313.0002 -1957.755 4958.935 3 9/1/01 0:02 1.018857e+02 -313.9406 -1956.799 4959.938 4 9/1/01 0:03 1.025463e+02 -310.9261 -1957.347 4961.095 5 9/1/01 0:04 1.010228e+02 -311.5469 -1957.786 4959.078 ``` The problem I have is that some timestamp values are missing - e.g. there may be a gap between 9/1/01 0:13 and 9/1/01 0:27 and such gaps are irregular through the data set. I need to put several of these series into the same database and because the missing values are different for each series, the dates do not currently align on each row. I would like to generate rows for these missing timestamps and fill the Y columns with blank values (no data, not zero), so that I have a continuous time series. I'm honestly not quite sure where to start (not really used R before so learning as I go along!) but any help would be much appreciated. I have thus far installed chron and zoo, since it seems they might be useful. Thanks!
2013/05/28
[ "https://Stackoverflow.com/questions/16787038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2427578/" ]
I think this can accomplished by using `complete` in `tidyr` package. ``` library(tidyverse) df <- df %>% complete(timestamp = seq.POSIXt(min(timestamp), max(timestamp), by = "minute"), tr, tt, sr,st) ``` you can also initialize your start date and end date instead of using `min(timestamp)` and `max(timestamp)`.
In case you want to substitute the NA values acquired by any method mentioned above with zeroes, you can do this: ``` df[is.na(df)] <- 0 ``` (I orginally wanted to comment this on Ibollar's answer but I lack the necessary reputation, thus I posted as an answer)
16,787,038
I am new to R but have turned to it to solve a problem with a large data set I am trying to process. Currently I have a 4 columns of data (Y values) set against minute-interval timestamps (month/day/year hour:min) (X values) as below: ``` timestamp tr tt sr st 1 9/1/01 0:00 1.018269e+02 -312.8622 -1959.393 4959.828 2 9/1/01 0:01 1.023567e+02 -313.0002 -1957.755 4958.935 3 9/1/01 0:02 1.018857e+02 -313.9406 -1956.799 4959.938 4 9/1/01 0:03 1.025463e+02 -310.9261 -1957.347 4961.095 5 9/1/01 0:04 1.010228e+02 -311.5469 -1957.786 4959.078 ``` The problem I have is that some timestamp values are missing - e.g. there may be a gap between 9/1/01 0:13 and 9/1/01 0:27 and such gaps are irregular through the data set. I need to put several of these series into the same database and because the missing values are different for each series, the dates do not currently align on each row. I would like to generate rows for these missing timestamps and fill the Y columns with blank values (no data, not zero), so that I have a continuous time series. I'm honestly not quite sure where to start (not really used R before so learning as I go along!) but any help would be much appreciated. I have thus far installed chron and zoo, since it seems they might be useful. Thanks!
2013/05/28
[ "https://Stackoverflow.com/questions/16787038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2427578/" ]
I think the easiest thing ist to set Date first as already described, convert to zoo, and then just set a merge: ``` df$timestamp<-as.POSIXct(df$timestamp,format="%m/%d/%y %H:%M") df1.zoo<-zoo(df[,-1],df[,1]) #set date to Index df2 <- merge(df1.zoo,zoo(,seq(start(df1.zoo),end(df1.zoo),by="min")), all=TRUE) ``` Start and end are given from your df1 (original data) and you are setting by - e.g min - as you need for your example. all=TRUE sets all missing values at the missing dates to NAs.
There are some advances in handling time series data in R, e.g. the `tsibble` [package](https://github.com/tidyverts/tsibble) added such time series manipulations in tidy way: ``` library(tsibble) library(lubridate) ts <- lubridate::dmy_hm(c("9/1/01 0:00","9/1/01 0:01","9/1/01 0:03","9/1/01 0:27")) originaldf <- tsibble(timestamp = ts, tr = rnorm(4,0,1), tt = rnorm(4,0,1), index = timestamp) originaldf %>% fill_gaps() ```
16,787,038
I am new to R but have turned to it to solve a problem with a large data set I am trying to process. Currently I have a 4 columns of data (Y values) set against minute-interval timestamps (month/day/year hour:min) (X values) as below: ``` timestamp tr tt sr st 1 9/1/01 0:00 1.018269e+02 -312.8622 -1959.393 4959.828 2 9/1/01 0:01 1.023567e+02 -313.0002 -1957.755 4958.935 3 9/1/01 0:02 1.018857e+02 -313.9406 -1956.799 4959.938 4 9/1/01 0:03 1.025463e+02 -310.9261 -1957.347 4961.095 5 9/1/01 0:04 1.010228e+02 -311.5469 -1957.786 4959.078 ``` The problem I have is that some timestamp values are missing - e.g. there may be a gap between 9/1/01 0:13 and 9/1/01 0:27 and such gaps are irregular through the data set. I need to put several of these series into the same database and because the missing values are different for each series, the dates do not currently align on each row. I would like to generate rows for these missing timestamps and fill the Y columns with blank values (no data, not zero), so that I have a continuous time series. I'm honestly not quite sure where to start (not really used R before so learning as I go along!) but any help would be much appreciated. I have thus far installed chron and zoo, since it seems they might be useful. Thanks!
2013/05/28
[ "https://Stackoverflow.com/questions/16787038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2427578/" ]
This is an old question, but I just wanted to post a dplyr way of handling this, as I came across this post while searching for an answer to a similar problem. I find it more intuitive and easier on the eyes than the zoo approach. ``` library(dplyr) ts <- seq.POSIXt(as.POSIXct("2001-09-01 0:00",'%m/%d/%y %H:%M'), as.POSIXct("2001-09-01 0:07",'%m/%d/%y %H:%M'), by="min") ts <- seq.POSIXt(as.POSIXlt("2001-09-01 0:00"), as.POSIXlt("2001-09-01 0:07"), by="min") ts <- format.POSIXct(ts,'%m/%d/%y %H:%M') df <- data.frame(timestamp=ts) data_with_missing_times <- full_join(df,original_data) timestamp tr tt sr st 1 09/01/01 00:00 15 15 78 42 2 09/01/01 00:01 20 64 98 87 3 09/01/01 00:02 31 84 23 35 4 09/01/01 00:03 21 63 54 20 5 09/01/01 00:04 15 23 36 15 6 09/01/01 00:05 NA NA NA NA 7 09/01/01 00:06 NA NA NA NA 8 09/01/01 00:07 NA NA NA NA ``` Also using dplyr, this makes it easier to do something like change all those missing values to something else, which came in handy for me when plotting in ggplot. ``` data_with_missing_times %>% group_by(timestamp) %>% mutate_each(funs(ifelse(is.na(.),0,.))) timestamp tr tt sr st 1 09/01/01 00:00 15 15 78 42 2 09/01/01 00:01 20 64 98 87 3 09/01/01 00:02 31 84 23 35 4 09/01/01 00:03 21 63 54 20 5 09/01/01 00:04 15 23 36 15 6 09/01/01 00:05 0 0 0 0 7 09/01/01 00:06 0 0 0 0 8 09/01/01 00:07 0 0 0 0 ```
I think this can accomplished by using `complete` in `tidyr` package. ``` library(tidyverse) df <- df %>% complete(timestamp = seq.POSIXt(min(timestamp), max(timestamp), by = "minute"), tr, tt, sr,st) ``` you can also initialize your start date and end date instead of using `min(timestamp)` and `max(timestamp)`.
16,787,038
I am new to R but have turned to it to solve a problem with a large data set I am trying to process. Currently I have a 4 columns of data (Y values) set against minute-interval timestamps (month/day/year hour:min) (X values) as below: ``` timestamp tr tt sr st 1 9/1/01 0:00 1.018269e+02 -312.8622 -1959.393 4959.828 2 9/1/01 0:01 1.023567e+02 -313.0002 -1957.755 4958.935 3 9/1/01 0:02 1.018857e+02 -313.9406 -1956.799 4959.938 4 9/1/01 0:03 1.025463e+02 -310.9261 -1957.347 4961.095 5 9/1/01 0:04 1.010228e+02 -311.5469 -1957.786 4959.078 ``` The problem I have is that some timestamp values are missing - e.g. there may be a gap between 9/1/01 0:13 and 9/1/01 0:27 and such gaps are irregular through the data set. I need to put several of these series into the same database and because the missing values are different for each series, the dates do not currently align on each row. I would like to generate rows for these missing timestamps and fill the Y columns with blank values (no data, not zero), so that I have a continuous time series. I'm honestly not quite sure where to start (not really used R before so learning as I go along!) but any help would be much appreciated. I have thus far installed chron and zoo, since it seems they might be useful. Thanks!
2013/05/28
[ "https://Stackoverflow.com/questions/16787038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2427578/" ]
Date padding is implemented in the `padr` package in R. If you store your data frame, with your date-time variable stored as `POSIXct` or `POSIXlt`. All you need to do is: ``` library(padr) pad(df_name) ``` See vignette("padr") or this blog post for its working.
There are some advances in handling time series data in R, e.g. the `tsibble` [package](https://github.com/tidyverts/tsibble) added such time series manipulations in tidy way: ``` library(tsibble) library(lubridate) ts <- lubridate::dmy_hm(c("9/1/01 0:00","9/1/01 0:01","9/1/01 0:03","9/1/01 0:27")) originaldf <- tsibble(timestamp = ts, tr = rnorm(4,0,1), tt = rnorm(4,0,1), index = timestamp) originaldf %>% fill_gaps() ```
16,787,038
I am new to R but have turned to it to solve a problem with a large data set I am trying to process. Currently I have a 4 columns of data (Y values) set against minute-interval timestamps (month/day/year hour:min) (X values) as below: ``` timestamp tr tt sr st 1 9/1/01 0:00 1.018269e+02 -312.8622 -1959.393 4959.828 2 9/1/01 0:01 1.023567e+02 -313.0002 -1957.755 4958.935 3 9/1/01 0:02 1.018857e+02 -313.9406 -1956.799 4959.938 4 9/1/01 0:03 1.025463e+02 -310.9261 -1957.347 4961.095 5 9/1/01 0:04 1.010228e+02 -311.5469 -1957.786 4959.078 ``` The problem I have is that some timestamp values are missing - e.g. there may be a gap between 9/1/01 0:13 and 9/1/01 0:27 and such gaps are irregular through the data set. I need to put several of these series into the same database and because the missing values are different for each series, the dates do not currently align on each row. I would like to generate rows for these missing timestamps and fill the Y columns with blank values (no data, not zero), so that I have a continuous time series. I'm honestly not quite sure where to start (not really used R before so learning as I go along!) but any help would be much appreciated. I have thus far installed chron and zoo, since it seems they might be useful. Thanks!
2013/05/28
[ "https://Stackoverflow.com/questions/16787038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2427578/" ]
This is an old question, but I just wanted to post a dplyr way of handling this, as I came across this post while searching for an answer to a similar problem. I find it more intuitive and easier on the eyes than the zoo approach. ``` library(dplyr) ts <- seq.POSIXt(as.POSIXct("2001-09-01 0:00",'%m/%d/%y %H:%M'), as.POSIXct("2001-09-01 0:07",'%m/%d/%y %H:%M'), by="min") ts <- seq.POSIXt(as.POSIXlt("2001-09-01 0:00"), as.POSIXlt("2001-09-01 0:07"), by="min") ts <- format.POSIXct(ts,'%m/%d/%y %H:%M') df <- data.frame(timestamp=ts) data_with_missing_times <- full_join(df,original_data) timestamp tr tt sr st 1 09/01/01 00:00 15 15 78 42 2 09/01/01 00:01 20 64 98 87 3 09/01/01 00:02 31 84 23 35 4 09/01/01 00:03 21 63 54 20 5 09/01/01 00:04 15 23 36 15 6 09/01/01 00:05 NA NA NA NA 7 09/01/01 00:06 NA NA NA NA 8 09/01/01 00:07 NA NA NA NA ``` Also using dplyr, this makes it easier to do something like change all those missing values to something else, which came in handy for me when plotting in ggplot. ``` data_with_missing_times %>% group_by(timestamp) %>% mutate_each(funs(ifelse(is.na(.),0,.))) timestamp tr tt sr st 1 09/01/01 00:00 15 15 78 42 2 09/01/01 00:01 20 64 98 87 3 09/01/01 00:02 31 84 23 35 4 09/01/01 00:03 21 63 54 20 5 09/01/01 00:04 15 23 36 15 6 09/01/01 00:05 0 0 0 0 7 09/01/01 00:06 0 0 0 0 8 09/01/01 00:07 0 0 0 0 ```
In case you want to substitute the NA values acquired by any method mentioned above with zeroes, you can do this: ``` df[is.na(df)] <- 0 ``` (I orginally wanted to comment this on Ibollar's answer but I lack the necessary reputation, thus I posted as an answer)
16,787,038
I am new to R but have turned to it to solve a problem with a large data set I am trying to process. Currently I have a 4 columns of data (Y values) set against minute-interval timestamps (month/day/year hour:min) (X values) as below: ``` timestamp tr tt sr st 1 9/1/01 0:00 1.018269e+02 -312.8622 -1959.393 4959.828 2 9/1/01 0:01 1.023567e+02 -313.0002 -1957.755 4958.935 3 9/1/01 0:02 1.018857e+02 -313.9406 -1956.799 4959.938 4 9/1/01 0:03 1.025463e+02 -310.9261 -1957.347 4961.095 5 9/1/01 0:04 1.010228e+02 -311.5469 -1957.786 4959.078 ``` The problem I have is that some timestamp values are missing - e.g. there may be a gap between 9/1/01 0:13 and 9/1/01 0:27 and such gaps are irregular through the data set. I need to put several of these series into the same database and because the missing values are different for each series, the dates do not currently align on each row. I would like to generate rows for these missing timestamps and fill the Y columns with blank values (no data, not zero), so that I have a continuous time series. I'm honestly not quite sure where to start (not really used R before so learning as I go along!) but any help would be much appreciated. I have thus far installed chron and zoo, since it seems they might be useful. Thanks!
2013/05/28
[ "https://Stackoverflow.com/questions/16787038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2427578/" ]
I think the easiest thing ist to set Date first as already described, convert to zoo, and then just set a merge: ``` df$timestamp<-as.POSIXct(df$timestamp,format="%m/%d/%y %H:%M") df1.zoo<-zoo(df[,-1],df[,1]) #set date to Index df2 <- merge(df1.zoo,zoo(,seq(start(df1.zoo),end(df1.zoo),by="min")), all=TRUE) ``` Start and end are given from your df1 (original data) and you are setting by - e.g min - as you need for your example. all=TRUE sets all missing values at the missing dates to NAs.
``` df1.zoo <- zoo(df1[,-1], as.POSIXlt(df1[,1], format = "%Y-%m-%d %H:%M:%S")) #set date to Index: Notice that column 1 is Timestamp type and is named as "TS" full.frame.zoo <- zoo(NA, seq(start(df1.zoo), end(df1.zoo), by="min")) # zoo object full.frame.df <- data.frame(TS = as.POSIXlt(index(full.frame.zoo), format = "%Y-%m-%d %H:%M:%S")) # conver zoo object to data frame full.vancouver <- merge(full.frame.df, df1, all = TRUE) # merge ```
16,787,038
I am new to R but have turned to it to solve a problem with a large data set I am trying to process. Currently I have a 4 columns of data (Y values) set against minute-interval timestamps (month/day/year hour:min) (X values) as below: ``` timestamp tr tt sr st 1 9/1/01 0:00 1.018269e+02 -312.8622 -1959.393 4959.828 2 9/1/01 0:01 1.023567e+02 -313.0002 -1957.755 4958.935 3 9/1/01 0:02 1.018857e+02 -313.9406 -1956.799 4959.938 4 9/1/01 0:03 1.025463e+02 -310.9261 -1957.347 4961.095 5 9/1/01 0:04 1.010228e+02 -311.5469 -1957.786 4959.078 ``` The problem I have is that some timestamp values are missing - e.g. there may be a gap between 9/1/01 0:13 and 9/1/01 0:27 and such gaps are irregular through the data set. I need to put several of these series into the same database and because the missing values are different for each series, the dates do not currently align on each row. I would like to generate rows for these missing timestamps and fill the Y columns with blank values (no data, not zero), so that I have a continuous time series. I'm honestly not quite sure where to start (not really used R before so learning as I go along!) but any help would be much appreciated. I have thus far installed chron and zoo, since it seems they might be useful. Thanks!
2013/05/28
[ "https://Stackoverflow.com/questions/16787038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2427578/" ]
Date padding is implemented in the `padr` package in R. If you store your data frame, with your date-time variable stored as `POSIXct` or `POSIXlt`. All you need to do is: ``` library(padr) pad(df_name) ``` See vignette("padr") or this blog post for its working.
``` # some made-up data originaldf <- data.frame(timestamp=c("9/1/01 0:00","9/1/01 0:01","9/1/01 0:03","9/1/01 0:04"), tr = rnorm(4,0,1), tt = rnorm(4,0,1)) originaldf$minAsPOSIX <- as.POSIXct(originaldf$timestamp, format="%m/%d/%y %H:%M", tz="GMT") # Generate vector of all minutes ndays <- 1 # number of days to generate minAsNumeric <- 60*60*24*243 + seq(0,60*60*24*ndays,by=60) # convert those minutes to POSIX minAsPOSIX <- as.POSIXct(minAsNumeric, origin="2001-01-01", tz="GMT") # new df newdf <- merge(data.frame(minAsPOSIX),originaldf,all.x=TRUE, by="minAsPOSIX") ```
16,787,038
I am new to R but have turned to it to solve a problem with a large data set I am trying to process. Currently I have a 4 columns of data (Y values) set against minute-interval timestamps (month/day/year hour:min) (X values) as below: ``` timestamp tr tt sr st 1 9/1/01 0:00 1.018269e+02 -312.8622 -1959.393 4959.828 2 9/1/01 0:01 1.023567e+02 -313.0002 -1957.755 4958.935 3 9/1/01 0:02 1.018857e+02 -313.9406 -1956.799 4959.938 4 9/1/01 0:03 1.025463e+02 -310.9261 -1957.347 4961.095 5 9/1/01 0:04 1.010228e+02 -311.5469 -1957.786 4959.078 ``` The problem I have is that some timestamp values are missing - e.g. there may be a gap between 9/1/01 0:13 and 9/1/01 0:27 and such gaps are irregular through the data set. I need to put several of these series into the same database and because the missing values are different for each series, the dates do not currently align on each row. I would like to generate rows for these missing timestamps and fill the Y columns with blank values (no data, not zero), so that I have a continuous time series. I'm honestly not quite sure where to start (not really used R before so learning as I go along!) but any help would be much appreciated. I have thus far installed chron and zoo, since it seems they might be useful. Thanks!
2013/05/28
[ "https://Stackoverflow.com/questions/16787038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2427578/" ]
This is an old question, but I just wanted to post a dplyr way of handling this, as I came across this post while searching for an answer to a similar problem. I find it more intuitive and easier on the eyes than the zoo approach. ``` library(dplyr) ts <- seq.POSIXt(as.POSIXct("2001-09-01 0:00",'%m/%d/%y %H:%M'), as.POSIXct("2001-09-01 0:07",'%m/%d/%y %H:%M'), by="min") ts <- seq.POSIXt(as.POSIXlt("2001-09-01 0:00"), as.POSIXlt("2001-09-01 0:07"), by="min") ts <- format.POSIXct(ts,'%m/%d/%y %H:%M') df <- data.frame(timestamp=ts) data_with_missing_times <- full_join(df,original_data) timestamp tr tt sr st 1 09/01/01 00:00 15 15 78 42 2 09/01/01 00:01 20 64 98 87 3 09/01/01 00:02 31 84 23 35 4 09/01/01 00:03 21 63 54 20 5 09/01/01 00:04 15 23 36 15 6 09/01/01 00:05 NA NA NA NA 7 09/01/01 00:06 NA NA NA NA 8 09/01/01 00:07 NA NA NA NA ``` Also using dplyr, this makes it easier to do something like change all those missing values to something else, which came in handy for me when plotting in ggplot. ``` data_with_missing_times %>% group_by(timestamp) %>% mutate_each(funs(ifelse(is.na(.),0,.))) timestamp tr tt sr st 1 09/01/01 00:00 15 15 78 42 2 09/01/01 00:01 20 64 98 87 3 09/01/01 00:02 31 84 23 35 4 09/01/01 00:03 21 63 54 20 5 09/01/01 00:04 15 23 36 15 6 09/01/01 00:05 0 0 0 0 7 09/01/01 00:06 0 0 0 0 8 09/01/01 00:07 0 0 0 0 ```
There are some advances in handling time series data in R, e.g. the `tsibble` [package](https://github.com/tidyverts/tsibble) added such time series manipulations in tidy way: ``` library(tsibble) library(lubridate) ts <- lubridate::dmy_hm(c("9/1/01 0:00","9/1/01 0:01","9/1/01 0:03","9/1/01 0:27")) originaldf <- tsibble(timestamp = ts, tr = rnorm(4,0,1), tt = rnorm(4,0,1), index = timestamp) originaldf %>% fill_gaps() ```
16,787,038
I am new to R but have turned to it to solve a problem with a large data set I am trying to process. Currently I have a 4 columns of data (Y values) set against minute-interval timestamps (month/day/year hour:min) (X values) as below: ``` timestamp tr tt sr st 1 9/1/01 0:00 1.018269e+02 -312.8622 -1959.393 4959.828 2 9/1/01 0:01 1.023567e+02 -313.0002 -1957.755 4958.935 3 9/1/01 0:02 1.018857e+02 -313.9406 -1956.799 4959.938 4 9/1/01 0:03 1.025463e+02 -310.9261 -1957.347 4961.095 5 9/1/01 0:04 1.010228e+02 -311.5469 -1957.786 4959.078 ``` The problem I have is that some timestamp values are missing - e.g. there may be a gap between 9/1/01 0:13 and 9/1/01 0:27 and such gaps are irregular through the data set. I need to put several of these series into the same database and because the missing values are different for each series, the dates do not currently align on each row. I would like to generate rows for these missing timestamps and fill the Y columns with blank values (no data, not zero), so that I have a continuous time series. I'm honestly not quite sure where to start (not really used R before so learning as I go along!) but any help would be much appreciated. I have thus far installed chron and zoo, since it seems they might be useful. Thanks!
2013/05/28
[ "https://Stackoverflow.com/questions/16787038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2427578/" ]
Date padding is implemented in the `padr` package in R. If you store your data frame, with your date-time variable stored as `POSIXct` or `POSIXlt`. All you need to do is: ``` library(padr) pad(df_name) ``` See vignette("padr") or this blog post for its working.
I was looking for something similar where instead of filling out missing timestamps my data was in months and days. So I wanted to generate a sequence of months that would cater for leap years et cetera. I used `lubridate`: ``` date <- df$timestamp[1] date_list <- c(date) while (date < df$timestamp[nrow(df)]){ date <- date %m+% months(1) date_list <- c(date_list,date) } date_list <- format(as.Date(date_list),"%Y-%m-%d") df_1 <- data.frame(months=date_list, stringsAsFactors = F) ``` This will give me a list of dates in incremental months. Then I join ``` df_with_missing_months <- full_join(df_1,df) ```
16,787,038
I am new to R but have turned to it to solve a problem with a large data set I am trying to process. Currently I have a 4 columns of data (Y values) set against minute-interval timestamps (month/day/year hour:min) (X values) as below: ``` timestamp tr tt sr st 1 9/1/01 0:00 1.018269e+02 -312.8622 -1959.393 4959.828 2 9/1/01 0:01 1.023567e+02 -313.0002 -1957.755 4958.935 3 9/1/01 0:02 1.018857e+02 -313.9406 -1956.799 4959.938 4 9/1/01 0:03 1.025463e+02 -310.9261 -1957.347 4961.095 5 9/1/01 0:04 1.010228e+02 -311.5469 -1957.786 4959.078 ``` The problem I have is that some timestamp values are missing - e.g. there may be a gap between 9/1/01 0:13 and 9/1/01 0:27 and such gaps are irregular through the data set. I need to put several of these series into the same database and because the missing values are different for each series, the dates do not currently align on each row. I would like to generate rows for these missing timestamps and fill the Y columns with blank values (no data, not zero), so that I have a continuous time series. I'm honestly not quite sure where to start (not really used R before so learning as I go along!) but any help would be much appreciated. I have thus far installed chron and zoo, since it seems they might be useful. Thanks!
2013/05/28
[ "https://Stackoverflow.com/questions/16787038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2427578/" ]
``` # some made-up data originaldf <- data.frame(timestamp=c("9/1/01 0:00","9/1/01 0:01","9/1/01 0:03","9/1/01 0:04"), tr = rnorm(4,0,1), tt = rnorm(4,0,1)) originaldf$minAsPOSIX <- as.POSIXct(originaldf$timestamp, format="%m/%d/%y %H:%M", tz="GMT") # Generate vector of all minutes ndays <- 1 # number of days to generate minAsNumeric <- 60*60*24*243 + seq(0,60*60*24*ndays,by=60) # convert those minutes to POSIX minAsPOSIX <- as.POSIXct(minAsNumeric, origin="2001-01-01", tz="GMT") # new df newdf <- merge(data.frame(minAsPOSIX),originaldf,all.x=TRUE, by="minAsPOSIX") ```
I was looking for something similar where instead of filling out missing timestamps my data was in months and days. So I wanted to generate a sequence of months that would cater for leap years et cetera. I used `lubridate`: ``` date <- df$timestamp[1] date_list <- c(date) while (date < df$timestamp[nrow(df)]){ date <- date %m+% months(1) date_list <- c(date_list,date) } date_list <- format(as.Date(date_list),"%Y-%m-%d") df_1 <- data.frame(months=date_list, stringsAsFactors = F) ``` This will give me a list of dates in incremental months. Then I join ``` df_with_missing_months <- full_join(df_1,df) ```
16,079,730
A union is a user-defined data or class type that, at any given time, contains only one object from its list of members. Suppose all the possible candidate members are needed to be allocated dynamically. For Eg. ``` // Union Destructor #include <string> using namespace std; union Person { private: char* szName; char* szJobTitle; public: Person() : szName (nullptr), szJobTitle (nullptr) {} Person (const string& strName, const string& strJob) { szName = new char[strName.size()]; strcpy (szName, strName.c_str()); szJobTitle = new char [strJob.size()]; strcpy (szJobTitle, strJob.c_str()); // obvious, both fields points at same location i.e. szJobTitle } ~Person() // Visual Studio 2010 shows that both szName and szJobTitle { // points to same location. if (szName) { delete[] szName; // Program crashes here. szName = nullptr; // to avoid deleting already deleted location(!) } if (szJobTitle) delete[] szJobTitle; } }; int main() { Person you ("your_name", "your_jobTitle"); return 0; } ``` Above program get crashed at 1st delete statement in ~Person (at moment when szName contains valid memory location, WHY?). What will be the correct implementation for the destructor? Same way, how to destruct a class object, if my class contains an union member ([how to wrtie destructor for class including a Union](https://stackoverflow.com/q/16025132/2243384))?
2013/04/18
[ "https://Stackoverflow.com/questions/16079730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2243384/" ]
You're using `delete` when you should use `delete []`, because you have used `new []`, not `new`. Change these: ``` delete szName; delete szJobTitle; ``` to these: ``` delete [] szName; delete [] szJobTitle; ``` By the way, the `if` condition in the destructor is pointless. I mean, if a pointer is `nullptr`, then it is safe to write `delete ptr;`, that is, ``` A *ptr = nullptr; delete ptr; //Okay! No need to ensure ptr is non-null ``` Apart from that, you're violating rule of three (or five, in C++11): * [What is The Rule of Three?](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) * [Rule-of-Three becomes Rule-of-Five with C++11?](https://stackoverflow.com/questions/4782757/rule-of-three-becomes-rule-of-five-with-c11) Implement them.
You don't respect that new-delete pairing: `new` pairs with `delete`, `new[]` pairs with `delete[]`. You're doing `new[]`, but calling `delete`; that's incompatible. As a side note, the constructor has a memory leak: the memory assigned to `szName` is never freed once that pointer is overwritten by the assignment to `szJobTitle`). And as this is C++, you should generally be using `std::string` instead of `char*` for strings.
16,079,730
A union is a user-defined data or class type that, at any given time, contains only one object from its list of members. Suppose all the possible candidate members are needed to be allocated dynamically. For Eg. ``` // Union Destructor #include <string> using namespace std; union Person { private: char* szName; char* szJobTitle; public: Person() : szName (nullptr), szJobTitle (nullptr) {} Person (const string& strName, const string& strJob) { szName = new char[strName.size()]; strcpy (szName, strName.c_str()); szJobTitle = new char [strJob.size()]; strcpy (szJobTitle, strJob.c_str()); // obvious, both fields points at same location i.e. szJobTitle } ~Person() // Visual Studio 2010 shows that both szName and szJobTitle { // points to same location. if (szName) { delete[] szName; // Program crashes here. szName = nullptr; // to avoid deleting already deleted location(!) } if (szJobTitle) delete[] szJobTitle; } }; int main() { Person you ("your_name", "your_jobTitle"); return 0; } ``` Above program get crashed at 1st delete statement in ~Person (at moment when szName contains valid memory location, WHY?). What will be the correct implementation for the destructor? Same way, how to destruct a class object, if my class contains an union member ([how to wrtie destructor for class including a Union](https://stackoverflow.com/q/16025132/2243384))?
2013/04/18
[ "https://Stackoverflow.com/questions/16079730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2243384/" ]
You're using `delete` when you should use `delete []`, because you have used `new []`, not `new`. Change these: ``` delete szName; delete szJobTitle; ``` to these: ``` delete [] szName; delete [] szJobTitle; ``` By the way, the `if` condition in the destructor is pointless. I mean, if a pointer is `nullptr`, then it is safe to write `delete ptr;`, that is, ``` A *ptr = nullptr; delete ptr; //Okay! No need to ensure ptr is non-null ``` Apart from that, you're violating rule of three (or five, in C++11): * [What is The Rule of Three?](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) * [Rule-of-Three becomes Rule-of-Five with C++11?](https://stackoverflow.com/questions/4782757/rule-of-three-becomes-rule-of-five-with-c11) Implement them.
> > Above program get crashed at 1st delete statement in ~Person (at moment when szName contains valid memory location, WHY?). > > > I don't have a compiler with me (or time to compile your code) but (apart from [the problems addressed by Nawaz](https://stackoverflow.com/a/16079788/186997)) I would guess it's because you treat the union members as class members. In your union, szName and szJobTitle should be looked like two variables with the same address: ``` Person (const string& strName, const string& strJob) { szName = new char[strName.size()]; strcpy (szName, strName.c_str()); szJobTitle = new char [strJob.size()]; // this creates memory leak (1) strcpy (szJobTitle, strJob.c_str()); } ``` You get a memory leak because you allocate new memory and place it in szJobTitle. &szJobTitle uses the same memory location as &szName, so with the assignment in line (1) you loose the address allocated in szName. If szName and szJobTitle were of different types (with non-matching memory footprints), setting szJobTitle would also corrupt (or only partially overwrite szTitle). > > What will be the correct implementation for the destructor? > > > I think you do not have enough details for implementing the destructor. Look into the concept of [discriminated unions in C++](http://blog.aaronballman.com/2011/07/discriminated-unions/) to see how to implement this correctly. Normally your union members should manage their own memory (use std::string, not char\*) and then your destructor would only delete what was allocated (but you will have to call it explicitly). > > Same way, how to destruct a class object, if my class contains an union member (how to wrtie destructor for class including a Union)? > > > Again, look at discriminated unions. It is basically the association of a union and an enum, where the enum maps to the members of the union and is set to specify which of the members of the union was set.
16,079,730
A union is a user-defined data or class type that, at any given time, contains only one object from its list of members. Suppose all the possible candidate members are needed to be allocated dynamically. For Eg. ``` // Union Destructor #include <string> using namespace std; union Person { private: char* szName; char* szJobTitle; public: Person() : szName (nullptr), szJobTitle (nullptr) {} Person (const string& strName, const string& strJob) { szName = new char[strName.size()]; strcpy (szName, strName.c_str()); szJobTitle = new char [strJob.size()]; strcpy (szJobTitle, strJob.c_str()); // obvious, both fields points at same location i.e. szJobTitle } ~Person() // Visual Studio 2010 shows that both szName and szJobTitle { // points to same location. if (szName) { delete[] szName; // Program crashes here. szName = nullptr; // to avoid deleting already deleted location(!) } if (szJobTitle) delete[] szJobTitle; } }; int main() { Person you ("your_name", "your_jobTitle"); return 0; } ``` Above program get crashed at 1st delete statement in ~Person (at moment when szName contains valid memory location, WHY?). What will be the correct implementation for the destructor? Same way, how to destruct a class object, if my class contains an union member ([how to wrtie destructor for class including a Union](https://stackoverflow.com/q/16025132/2243384))?
2013/04/18
[ "https://Stackoverflow.com/questions/16079730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2243384/" ]
You can only use one member of the union at a time because they share the same memory. In the constructor, however, you initialize both members, which overwrites each other, and then in the destructor you end up releasing it two times. You're trying to use it as if it were a struct (based on the names of the fields you need to use a struct). Nevertheless, if you need a union then you probably need a struct as a kind of envelope which has some id representing the member being used, as well as a constructor and a destructor that handles the resources. Also - your arrays are too small. `size()` returns the number of characters, but if you use `char*` as your string type then you need space for the null-character (`\0`) to handle termination. If you need unions, try using Boost.Variant. It is a lot easier to use than normal unions.
You don't respect that new-delete pairing: `new` pairs with `delete`, `new[]` pairs with `delete[]`. You're doing `new[]`, but calling `delete`; that's incompatible. As a side note, the constructor has a memory leak: the memory assigned to `szName` is never freed once that pointer is overwritten by the assignment to `szJobTitle`). And as this is C++, you should generally be using `std::string` instead of `char*` for strings.
16,079,730
A union is a user-defined data or class type that, at any given time, contains only one object from its list of members. Suppose all the possible candidate members are needed to be allocated dynamically. For Eg. ``` // Union Destructor #include <string> using namespace std; union Person { private: char* szName; char* szJobTitle; public: Person() : szName (nullptr), szJobTitle (nullptr) {} Person (const string& strName, const string& strJob) { szName = new char[strName.size()]; strcpy (szName, strName.c_str()); szJobTitle = new char [strJob.size()]; strcpy (szJobTitle, strJob.c_str()); // obvious, both fields points at same location i.e. szJobTitle } ~Person() // Visual Studio 2010 shows that both szName and szJobTitle { // points to same location. if (szName) { delete[] szName; // Program crashes here. szName = nullptr; // to avoid deleting already deleted location(!) } if (szJobTitle) delete[] szJobTitle; } }; int main() { Person you ("your_name", "your_jobTitle"); return 0; } ``` Above program get crashed at 1st delete statement in ~Person (at moment when szName contains valid memory location, WHY?). What will be the correct implementation for the destructor? Same way, how to destruct a class object, if my class contains an union member ([how to wrtie destructor for class including a Union](https://stackoverflow.com/q/16025132/2243384))?
2013/04/18
[ "https://Stackoverflow.com/questions/16079730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2243384/" ]
You can only use one member of the union at a time because they share the same memory. In the constructor, however, you initialize both members, which overwrites each other, and then in the destructor you end up releasing it two times. You're trying to use it as if it were a struct (based on the names of the fields you need to use a struct). Nevertheless, if you need a union then you probably need a struct as a kind of envelope which has some id representing the member being used, as well as a constructor and a destructor that handles the resources. Also - your arrays are too small. `size()` returns the number of characters, but if you use `char*` as your string type then you need space for the null-character (`\0`) to handle termination. If you need unions, try using Boost.Variant. It is a lot easier to use than normal unions.
> > Above program get crashed at 1st delete statement in ~Person (at moment when szName contains valid memory location, WHY?). > > > I don't have a compiler with me (or time to compile your code) but (apart from [the problems addressed by Nawaz](https://stackoverflow.com/a/16079788/186997)) I would guess it's because you treat the union members as class members. In your union, szName and szJobTitle should be looked like two variables with the same address: ``` Person (const string& strName, const string& strJob) { szName = new char[strName.size()]; strcpy (szName, strName.c_str()); szJobTitle = new char [strJob.size()]; // this creates memory leak (1) strcpy (szJobTitle, strJob.c_str()); } ``` You get a memory leak because you allocate new memory and place it in szJobTitle. &szJobTitle uses the same memory location as &szName, so with the assignment in line (1) you loose the address allocated in szName. If szName and szJobTitle were of different types (with non-matching memory footprints), setting szJobTitle would also corrupt (or only partially overwrite szTitle). > > What will be the correct implementation for the destructor? > > > I think you do not have enough details for implementing the destructor. Look into the concept of [discriminated unions in C++](http://blog.aaronballman.com/2011/07/discriminated-unions/) to see how to implement this correctly. Normally your union members should manage their own memory (use std::string, not char\*) and then your destructor would only delete what was allocated (but you will have to call it explicitly). > > Same way, how to destruct a class object, if my class contains an union member (how to wrtie destructor for class including a Union)? > > > Again, look at discriminated unions. It is basically the association of a union and an enum, where the enum maps to the members of the union and is set to specify which of the members of the union was set.
64,509
I was trying to understand the [Wikipedia](https://en.wikipedia.org/wiki/Subgraph_isomorphism_problem) proof for NP-completeness of subgraph isomorphism by reduction from the clique problem. It's really just one sentence: > > Let $H$ be the complete graph $K\_k$; then, the answer to the subgraph isomorphism problem for $G$ and $H$ is equal to the answer to the clique problem for $G$ and $k$. > > > In the subgraph isomorphism problem, $G$ and $H$ are not constrained in any way (e.g., $H$ is not constrained to complete graphs). Yet, in the proof, Wikipedia just states "let $H$ be the complete graph $K\_k$". It's not defined what $K\_k$ represents or why $H$ suddenly becomes constrained to a complete graph.
2016/10/11
[ "https://cs.stackexchange.com/questions/64509", "https://cs.stackexchange.com", "https://cs.stackexchange.com/users/47642/" ]
The decision version of the clique problem asks whether a given graph $G$ contains a complete graph with $k$ vertices as subgraph. The wikipedia article just explains why the decision version of the clique problem is a special case of the subgraph isomorphism problem. Namely if the graph $H$ is the complete graph with $k$ vertices, then the answer to this special subgraph isomorphism problem is just the answer to the decision version of the clique problem. This shows that subgraph isomorphism is NP-hard, since the clique problem is NP-complete. But the subgraph isomorphism is obviously in NP, since it a given monomorphism from $H$ to $G$ can efficiently be checked to be a monomorphism. So we can conclude that subgraph isomorphism is NP-complete.
You misunderstood the proof of NP-completeness of Subgraph Isomorphism (SI). 1. We know that SI $\in$ NP because we can check its solution in polynomial time. 2. **Any** instance of clique problem (which is NP-complete) can be reduced in polynomial time to **some** instance of SI. This concludes that **any** problem in NP can be reduced to **some** instance of SI. If you read the [definition](https://en.wikipedia.org/wiki/NP-completeness#Formal_definition) of NP-completeness, you will find out that its requirement satisfied by word **any**. The word **some** doesn't contradict it in any way.
27,686,304
I am trying to convert my javascript to Typescript and came up with another problem. Here's the code I have: ``` var util = {}; ``` Then later in the code: ``` util.extendRegExp = function (regex, pre, post) { if (pre === null || pre === undefined) { pre = ""; } if (post === null || post === undefined) { post = ""; } ``` I tried to declare an interface like this: ``` interface Iutil = { extendRegExp (any) } ... ... var util: Iutil = {}; ``` but now I am getting an error message saying: ``` Can't convert {} to Iutil. util is missing the property extendRegExp ``` Is there a way I can do the `var util = {}`
2014/12/29
[ "https://Stackoverflow.com/questions/27686304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1422604/" ]
You can assert the empty object as your interface type when you assign it: ``` var util: Iutil = {} as Iutil; ``` Then you can assign the function later. If TypeScript still complains (e.g. no overlap between type or something like that) then you can do an assertion to `any` and then to your interface: ``` var util: Iutil = {} as any as Iutil; ```
An alternative (I prefer) is to mark it as `optional` using `?` because to be honest it is something that may or may not exist as soon as you start using type assertions: ``` interface Iutil { extendRegExp? (any) } var util: Iutil = {}; // No error ```
33,377,457
I have a simple math function ``` private int Doyle(LogArguments args) { return Convert.ToInt32(Math.Round(Math.Pow((args.Diameter - 4) , 2.0) * (args.Length / 16),0)); } ``` that should always return an int > 0 but my problem is if `args.Length` <= 16 it `args.Length/16` = 0. I have tried: ``` decimal d = args.length/16 ``` and `double d = args.length/16;` which both turn out to 0 when Length <16
2015/10/27
[ "https://Stackoverflow.com/questions/33377457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5197739/" ]
If `args.length` is an `int` you are doing integer division regardless of what the type of the output variable is. To force `decimal` division the simplest way is to specify a decimal literal in the denominator: ``` decimal d = args.length / 16M; ``` Or for a `double` use a floating-point literal: ``` double d = args.length / 16.0; ```
``` double d = args.length/16; ``` > > which both turn out to 0 when Length <16 > > > That is because args.Length and 16 are both integers. You get integer division (result 0), which is *then* cast to a double. Instead, try ``` double d = args.length/16.0; ```
33,377,457
I have a simple math function ``` private int Doyle(LogArguments args) { return Convert.ToInt32(Math.Round(Math.Pow((args.Diameter - 4) , 2.0) * (args.Length / 16),0)); } ``` that should always return an int > 0 but my problem is if `args.Length` <= 16 it `args.Length/16` = 0. I have tried: ``` decimal d = args.length/16 ``` and `double d = args.length/16;` which both turn out to 0 when Length <16
2015/10/27
[ "https://Stackoverflow.com/questions/33377457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5197739/" ]
If `args.length` is an `int` you are doing integer division regardless of what the type of the output variable is. To force `decimal` division the simplest way is to specify a decimal literal in the denominator: ``` decimal d = args.length / 16M; ``` Or for a `double` use a floating-point literal: ``` double d = args.length / 16.0; ```
If you are trying to multiply by a float value such as this: ``` 5 / 16 = 0.3125 ``` Then you should turn `(args.Length / 16)` into `(args.Length / 16f)`. This will force the division to be does as a floating point, and keep any remainder. Without the `f` added, it will do it as an integer division which truncates the remainder, so any value less than 16 will be less than 1 and get reduced to 0.
33,377,457
I have a simple math function ``` private int Doyle(LogArguments args) { return Convert.ToInt32(Math.Round(Math.Pow((args.Diameter - 4) , 2.0) * (args.Length / 16),0)); } ``` that should always return an int > 0 but my problem is if `args.Length` <= 16 it `args.Length/16` = 0. I have tried: ``` decimal d = args.length/16 ``` and `double d = args.length/16;` which both turn out to 0 when Length <16
2015/10/27
[ "https://Stackoverflow.com/questions/33377457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5197739/" ]
``` double d = args.length/16; ``` > > which both turn out to 0 when Length <16 > > > That is because args.Length and 16 are both integers. You get integer division (result 0), which is *then* cast to a double. Instead, try ``` double d = args.length/16.0; ```
If you are trying to multiply by a float value such as this: ``` 5 / 16 = 0.3125 ``` Then you should turn `(args.Length / 16)` into `(args.Length / 16f)`. This will force the division to be does as a floating point, and keep any remainder. Without the `f` added, it will do it as an integer division which truncates the remainder, so any value less than 16 will be less than 1 and get reduced to 0.
9,702,997
I have an application that will be accessing the web. I've decided to use Spring Android as the RestAPI, and with the help of a `Thread` have got this simple demo working. My question is, how do I go about changing it to populating an actual `ListView` rather than just logging the output of the object? Some other questions on here have led me to believe that `AsyncTask` may be the answer, but I'm still a bit confused as to how I update the UI, as it is my understanding that other threads can't touch it. Here is what I have now, minus the function that creates the RestTemplate, and makes the request, as I believe it is not relevant: ``` public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); new Thread( new Runnable() { public void run() { // create a RestTemplate. This is used to communicate with the server. RestTemplate restTemplate = getRestTemplate(); String url = "http://192.168.2.14:8888/"; JSONData[] jsonData = restTemplate.getForObject( url, JSONData[].class ); for( JSONData d : jsonData ) { Log.d( "TEST", d.getName() + " " + d.getId() ); } } } ).start(); setContentView( R.layout.main ); } ```
2012/03/14
[ "https://Stackoverflow.com/questions/9702997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/420001/" ]
There are several options, listed in the very nice article [(Android) Painless Threading](http://developer.android.com/resources/articles/painless-threading.html). `AsyncTask` is one of the options and it seems to fit your needs, and there are several methods of it that run on the UI thread, such as `onPreExecute`, `onPostExecute` and `onProgressUpdate`.
if want to change the UI from a different thread, you can use Handler or Activity.runOnUiThread().
748,614
I would like to write a Ruby on Rails application that consumes a RESTful web service API performs some logic on the result and then displays that data on my view. For example, let's say I wanted to write a program that did a search on search.twitter.com. Using pure ruby I might create the following method: ``` def run(search_term='', last_id=0) @results = [] url = URI.parse("http://search.twitter.com") res = Net::HTTP.start(url.host, url.port) do |http| http.get("/search.json?q=#{search_term}&since_id=#{last_id.to_s}") end @results = JSON.parse res.body end ``` I'm tempted to just drop that method into my Rails controller as a private method, but part of me thinks that there is a better, more "Rails" way to do this. Is there a best practice approach or is this really the best way?
2009/04/14
[ "https://Stackoverflow.com/questions/748614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4082/" ]
if the remote RESTful web service was also created with Ruby on Rails, [ActiveResource](https://github.com/rails/activeresource) is the way to go.
In response to your Twitter example, there is a [Twitter Gem](http://twitter.rubyforge.org/) that would help to automate this for you.
748,614
I would like to write a Ruby on Rails application that consumes a RESTful web service API performs some logic on the result and then displays that data on my view. For example, let's say I wanted to write a program that did a search on search.twitter.com. Using pure ruby I might create the following method: ``` def run(search_term='', last_id=0) @results = [] url = URI.parse("http://search.twitter.com") res = Net::HTTP.start(url.host, url.port) do |http| http.get("/search.json?q=#{search_term}&since_id=#{last_id.to_s}") end @results = JSON.parse res.body end ``` I'm tempted to just drop that method into my Rails controller as a private method, but part of me thinks that there is a better, more "Rails" way to do this. Is there a best practice approach or is this really the best way?
2009/04/14
[ "https://Stackoverflow.com/questions/748614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4082/" ]
There is a plugin/gem called HTTParty that I've used for several projects. <http://johnnunemaker.com/httparty/> HTTParty lets you easily consume any web service and parses results into a hash for you. Then you can use the hash itself or instantiate one or more model instances with the results. I've done it both ways. For the twitter example, your code would look like this: ``` class Twitter include HTTParty base_uri 'twitter.com' def initialize(u, p) @auth = {:username => u, :password => p} end # which can be :friends, :user or :public # options[:query] can be things like since, since_id, count, etc. def timeline(which=:friends, options={}) options.merge!({:basic_auth => @auth}) self.class.get("/statuses/#{which}_timeline.json", options) end def post(text) options = { :query => {:status => text}, :basic_auth => @auth } self.class.post('/statuses/update.json', options) end end # usage examples. twitter = Twitter.new('username', 'password') twitter.post("It's an HTTParty and everyone is invited!") twitter.timeline(:friends, :query => {:since_id => 868482746}) twitter.timeline(:friends, :query => 'since_id=868482746') ``` As a last point, you could use your code above also, but definitely include the code in a model as opposed to a controller.
if the remote RESTful web service was also created with Ruby on Rails, [ActiveResource](https://github.com/rails/activeresource) is the way to go.
748,614
I would like to write a Ruby on Rails application that consumes a RESTful web service API performs some logic on the result and then displays that data on my view. For example, let's say I wanted to write a program that did a search on search.twitter.com. Using pure ruby I might create the following method: ``` def run(search_term='', last_id=0) @results = [] url = URI.parse("http://search.twitter.com") res = Net::HTTP.start(url.host, url.port) do |http| http.get("/search.json?q=#{search_term}&since_id=#{last_id.to_s}") end @results = JSON.parse res.body end ``` I'm tempted to just drop that method into my Rails controller as a private method, but part of me thinks that there is a better, more "Rails" way to do this. Is there a best practice approach or is this really the best way?
2009/04/14
[ "https://Stackoverflow.com/questions/748614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4082/" ]
[Restclient](https://github.com/rest-client/rest-client) is a really nice solution to this problem. ``` require 'rest_client' RestClient.get 'http://example.com/resource' RestClient.get 'http://example.com/resource', {:params => {:id => 50, 'foo' => 'bar'}} ``` From the [readme](https://github.com/rest-client/rest-client/blob/master/README.md).
if the remote RESTful web service was also created with Ruby on Rails, [ActiveResource](https://github.com/rails/activeresource) is the way to go.
748,614
I would like to write a Ruby on Rails application that consumes a RESTful web service API performs some logic on the result and then displays that data on my view. For example, let's say I wanted to write a program that did a search on search.twitter.com. Using pure ruby I might create the following method: ``` def run(search_term='', last_id=0) @results = [] url = URI.parse("http://search.twitter.com") res = Net::HTTP.start(url.host, url.port) do |http| http.get("/search.json?q=#{search_term}&since_id=#{last_id.to_s}") end @results = JSON.parse res.body end ``` I'm tempted to just drop that method into my Rails controller as a private method, but part of me thinks that there is a better, more "Rails" way to do this. Is there a best practice approach or is this really the best way?
2009/04/14
[ "https://Stackoverflow.com/questions/748614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4082/" ]
if the remote RESTful web service was also created with Ruby on Rails, [ActiveResource](https://github.com/rails/activeresource) is the way to go.
I think Faraday deserves a mention here. Really nice interface, and powerful concept of middleware. <https://github.com/lostisland/faraday>
748,614
I would like to write a Ruby on Rails application that consumes a RESTful web service API performs some logic on the result and then displays that data on my view. For example, let's say I wanted to write a program that did a search on search.twitter.com. Using pure ruby I might create the following method: ``` def run(search_term='', last_id=0) @results = [] url = URI.parse("http://search.twitter.com") res = Net::HTTP.start(url.host, url.port) do |http| http.get("/search.json?q=#{search_term}&since_id=#{last_id.to_s}") end @results = JSON.parse res.body end ``` I'm tempted to just drop that method into my Rails controller as a private method, but part of me thinks that there is a better, more "Rails" way to do this. Is there a best practice approach or is this really the best way?
2009/04/14
[ "https://Stackoverflow.com/questions/748614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4082/" ]
There is a plugin/gem called HTTParty that I've used for several projects. <http://johnnunemaker.com/httparty/> HTTParty lets you easily consume any web service and parses results into a hash for you. Then you can use the hash itself or instantiate one or more model instances with the results. I've done it both ways. For the twitter example, your code would look like this: ``` class Twitter include HTTParty base_uri 'twitter.com' def initialize(u, p) @auth = {:username => u, :password => p} end # which can be :friends, :user or :public # options[:query] can be things like since, since_id, count, etc. def timeline(which=:friends, options={}) options.merge!({:basic_auth => @auth}) self.class.get("/statuses/#{which}_timeline.json", options) end def post(text) options = { :query => {:status => text}, :basic_auth => @auth } self.class.post('/statuses/update.json', options) end end # usage examples. twitter = Twitter.new('username', 'password') twitter.post("It's an HTTParty and everyone is invited!") twitter.timeline(:friends, :query => {:since_id => 868482746}) twitter.timeline(:friends, :query => 'since_id=868482746') ``` As a last point, you could use your code above also, but definitely include the code in a model as opposed to a controller.
In response to your Twitter example, there is a [Twitter Gem](http://twitter.rubyforge.org/) that would help to automate this for you.
748,614
I would like to write a Ruby on Rails application that consumes a RESTful web service API performs some logic on the result and then displays that data on my view. For example, let's say I wanted to write a program that did a search on search.twitter.com. Using pure ruby I might create the following method: ``` def run(search_term='', last_id=0) @results = [] url = URI.parse("http://search.twitter.com") res = Net::HTTP.start(url.host, url.port) do |http| http.get("/search.json?q=#{search_term}&since_id=#{last_id.to_s}") end @results = JSON.parse res.body end ``` I'm tempted to just drop that method into my Rails controller as a private method, but part of me thinks that there is a better, more "Rails" way to do this. Is there a best practice approach or is this really the best way?
2009/04/14
[ "https://Stackoverflow.com/questions/748614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4082/" ]
[Restclient](https://github.com/rest-client/rest-client) is a really nice solution to this problem. ``` require 'rest_client' RestClient.get 'http://example.com/resource' RestClient.get 'http://example.com/resource', {:params => {:id => 50, 'foo' => 'bar'}} ``` From the [readme](https://github.com/rest-client/rest-client/blob/master/README.md).
In response to your Twitter example, there is a [Twitter Gem](http://twitter.rubyforge.org/) that would help to automate this for you.
748,614
I would like to write a Ruby on Rails application that consumes a RESTful web service API performs some logic on the result and then displays that data on my view. For example, let's say I wanted to write a program that did a search on search.twitter.com. Using pure ruby I might create the following method: ``` def run(search_term='', last_id=0) @results = [] url = URI.parse("http://search.twitter.com") res = Net::HTTP.start(url.host, url.port) do |http| http.get("/search.json?q=#{search_term}&since_id=#{last_id.to_s}") end @results = JSON.parse res.body end ``` I'm tempted to just drop that method into my Rails controller as a private method, but part of me thinks that there is a better, more "Rails" way to do this. Is there a best practice approach or is this really the best way?
2009/04/14
[ "https://Stackoverflow.com/questions/748614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4082/" ]
There is a plugin/gem called HTTParty that I've used for several projects. <http://johnnunemaker.com/httparty/> HTTParty lets you easily consume any web service and parses results into a hash for you. Then you can use the hash itself or instantiate one or more model instances with the results. I've done it both ways. For the twitter example, your code would look like this: ``` class Twitter include HTTParty base_uri 'twitter.com' def initialize(u, p) @auth = {:username => u, :password => p} end # which can be :friends, :user or :public # options[:query] can be things like since, since_id, count, etc. def timeline(which=:friends, options={}) options.merge!({:basic_auth => @auth}) self.class.get("/statuses/#{which}_timeline.json", options) end def post(text) options = { :query => {:status => text}, :basic_auth => @auth } self.class.post('/statuses/update.json', options) end end # usage examples. twitter = Twitter.new('username', 'password') twitter.post("It's an HTTParty and everyone is invited!") twitter.timeline(:friends, :query => {:since_id => 868482746}) twitter.timeline(:friends, :query => 'since_id=868482746') ``` As a last point, you could use your code above also, but definitely include the code in a model as opposed to a controller.
[Restclient](https://github.com/rest-client/rest-client) is a really nice solution to this problem. ``` require 'rest_client' RestClient.get 'http://example.com/resource' RestClient.get 'http://example.com/resource', {:params => {:id => 50, 'foo' => 'bar'}} ``` From the [readme](https://github.com/rest-client/rest-client/blob/master/README.md).
748,614
I would like to write a Ruby on Rails application that consumes a RESTful web service API performs some logic on the result and then displays that data on my view. For example, let's say I wanted to write a program that did a search on search.twitter.com. Using pure ruby I might create the following method: ``` def run(search_term='', last_id=0) @results = [] url = URI.parse("http://search.twitter.com") res = Net::HTTP.start(url.host, url.port) do |http| http.get("/search.json?q=#{search_term}&since_id=#{last_id.to_s}") end @results = JSON.parse res.body end ``` I'm tempted to just drop that method into my Rails controller as a private method, but part of me thinks that there is a better, more "Rails" way to do this. Is there a best practice approach or is this really the best way?
2009/04/14
[ "https://Stackoverflow.com/questions/748614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4082/" ]
There is a plugin/gem called HTTParty that I've used for several projects. <http://johnnunemaker.com/httparty/> HTTParty lets you easily consume any web service and parses results into a hash for you. Then you can use the hash itself or instantiate one or more model instances with the results. I've done it both ways. For the twitter example, your code would look like this: ``` class Twitter include HTTParty base_uri 'twitter.com' def initialize(u, p) @auth = {:username => u, :password => p} end # which can be :friends, :user or :public # options[:query] can be things like since, since_id, count, etc. def timeline(which=:friends, options={}) options.merge!({:basic_auth => @auth}) self.class.get("/statuses/#{which}_timeline.json", options) end def post(text) options = { :query => {:status => text}, :basic_auth => @auth } self.class.post('/statuses/update.json', options) end end # usage examples. twitter = Twitter.new('username', 'password') twitter.post("It's an HTTParty and everyone is invited!") twitter.timeline(:friends, :query => {:since_id => 868482746}) twitter.timeline(:friends, :query => 'since_id=868482746') ``` As a last point, you could use your code above also, but definitely include the code in a model as opposed to a controller.
I think Faraday deserves a mention here. Really nice interface, and powerful concept of middleware. <https://github.com/lostisland/faraday>
748,614
I would like to write a Ruby on Rails application that consumes a RESTful web service API performs some logic on the result and then displays that data on my view. For example, let's say I wanted to write a program that did a search on search.twitter.com. Using pure ruby I might create the following method: ``` def run(search_term='', last_id=0) @results = [] url = URI.parse("http://search.twitter.com") res = Net::HTTP.start(url.host, url.port) do |http| http.get("/search.json?q=#{search_term}&since_id=#{last_id.to_s}") end @results = JSON.parse res.body end ``` I'm tempted to just drop that method into my Rails controller as a private method, but part of me thinks that there is a better, more "Rails" way to do this. Is there a best practice approach or is this really the best way?
2009/04/14
[ "https://Stackoverflow.com/questions/748614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4082/" ]
[Restclient](https://github.com/rest-client/rest-client) is a really nice solution to this problem. ``` require 'rest_client' RestClient.get 'http://example.com/resource' RestClient.get 'http://example.com/resource', {:params => {:id => 50, 'foo' => 'bar'}} ``` From the [readme](https://github.com/rest-client/rest-client/blob/master/README.md).
I think Faraday deserves a mention here. Really nice interface, and powerful concept of middleware. <https://github.com/lostisland/faraday>
2,042,257
I'm looking at the following differential equation: $\frac{dx}{dt} = \frac{\sin^2 x - t^2}{t \cdot \sin(2x)}$ I rewrote it as $(t \cdot \sin(2x))dx = (\sin^2x - t^2)dt$ $\Leftrightarrow (\underbrace{\sin^2 x - t^2}\_{J(x,t)})dt + (\underbrace{-t \cdot \sin(2x)}\_{I(x,t)}) dx = 0$ where I put the minus sign inside the function because I think it is important that a plus stands between the two functions in order to check if a differential equation is exact or not. But then: $\partial\_x J(x,t) = 2 \sin x \cos x = \sin(2x)$ $\partial\_t I(x,t) = -\sin(2x)$ Those functions don't seem to satisfy the condition for a differential equation to be exact. However my teacher wrote in his answer the following: $\frac{-\partial\_x (\sin^2 x - t^2) - \partial\_t (t \cdot \sin (2x))}{t \sin(2x)} = \frac{-2}{t}$ $\implies c' = - \frac{2}{t} c$ $\implies x' = \frac{\frac{\sin^2 x}{t^2} - 1}{\frac{\sin (2x)}{t}}$ and he states that this equation is now exact. What happened there? I've never seen anything like that yet. I understand (more or less) what he is doing after $c' = -\frac{2}{t}c$ (separation of variables and integration), but how he came to the first line I have no idea. Is that a known technic to transform a differential equation that is $\textit{almost}$ exact? Thanks a lot in advance for your answers. Julien.
2016/12/03
[ "https://math.stackexchange.com/questions/2042257", "https://math.stackexchange.com", "https://math.stackexchange.com/users/281357/" ]
The positive real solution to $x^x=2$ is irrational. Proof: Assume $x=\frac{p}{q}$ where $p$ and $q$ have no common factor but $1$ then: $$\left(\frac{p}{q}\right)^{p}=2^{q}$$ We must have $p^p=q^p2^q$ Note $p>q$ because $x>1$ (this can be shown). Then $p$ must be even. So we may set $p=2k$. $$(2k)^{2k}=q^p2^q$$ $$2^{2k}k^{2k}=q^{2k}2^q$$ $$2^{2k-q}k^{2k}=q^{2k}$$ Then $q$ must be even. Contradiction. Note: We have $x^x=2$, then $x \ln x=\ln 2$ and $\ln xe^{\ln x}=2$ so using the lambert W function: $$\ln x=W(\ln 2)$$ $$x=e^{W(\ln 2)}=\frac{\ln (2)}{W(\ln 2)}$$
As $x^x$ is a continous function, $1^1=1$ and $2^2=4$, then there is an $x$ such that $$x^x=2.$$ As the function is monotonic in this range, the solution is unique. This number is irrational, otherwise let $x$ be the irreducible fraction $p/q$: $$\left(\frac pq\right)^{p/q}=2$$ implies $$p^p=2^qq^p.$$ Then $p$ is even, $p=2r$ with $q$ odd, and $$2^{2r}r^{2r}=2^qq^p,$$ so that $q$ is even !
68,903,488
Below are my javascript code, why the preloader doesnt show up when I refresh? The first code i use to append a new preloader inside it when it start running javascript, does anyone know how I can append a things that used to replace another thing at the bottom there, as well as three screw driver is running around the place and here. ``` $('body').append('<div id="loader-background"><div class="load"><div class="gear one"><svg id="blue" viewbox="0 0 100 100" fill="#aeb2b7"><path d="M97.6,55.7V44.3l-13.6-2.9c-0.8-3.3-2.1-6.4-3.9-9.3l7.6-11.7l-8-8L67.9,20c-2.9-1.7-6-3.1-9.3-3.9L55.7,2.4H44.3l-2.9,13.6 c-3.3,0.8-6.4,2.1-9.3,3.9l-11.7-7.6l-8,8L20,32.1c-1.7,2.9-3.1,6-3.9,9.3L2.4,44.3v11.4l13.6,2.9c0.8,3.3,2.1,6.4,3.9,9.3 l-7.6,11.7l8,8L32.1,80c2.9,1.7,6,3.1,9.3,3.9l2.9,13.6h11.4l2.9-13.6c3.3-0.8,6.4-2.1,9.3-3.9l11.7,7.6l8-8L80,67.9 c1.7-2.9,3.1-6,3.9-9.3L97.6,55.7z M50,65.6c-8.7,0-15.6-7-15.6-15.6s7-15.6,15.6-15.6s15.6,7,15.6,15.6S58.7,65.6,50,65.6z"></path></svg></div><div class="gear two"><svg id="pink" viewbox="0 0 100 100" fill="#ff6c60"><path d="M97.6,55.7V44.3l-13.6-2.9c-0.8-3.3-2.1-6.4-3.9-9.3l7.6-11.7l-8-8L67.9,20c-2.9-1.7-6-3.1-9.3-3.9L55.7,2.4H44.3l-2.9,13.6 c-3.3,0.8-6.4,2.1-9.3,3.9l-11.7-7.6l-8,8L20,32.1c-1.7,2.9-3.1,6-3.9,9.3L2.4,44.3v11.4l13.6,2.9c0.8,3.3,2.1,6.4,3.9,9.3 l-7.6,11.7l8,8L32.1,80c2.9,1.7,6,3.1,9.3,3.9l2.9,13.6h11.4l2.9-13.6c3.3-0.8,6.4-2.1,9.3-3.9l11.7,7.6l8-8L80,67.9 c1.7-2.9,3.1-6,3.9-9.3L97.6,55.7z M50,65.6c-8.7,0-15.6-7-15.6-15.6s7-15.6,15.6-15.6s15.6,7,15.6,15.6S58.7,65.6,50,65.6z"></path></svg></div><div class="gear three"><svg id="yellow" viewbox="0 0 100 100" fill="#36404e"><path d="M97.6,55.7V44.3l-13.6-2.9c-0.8-3.3-2.1-6.4-3.9-9.3l7.6-11.7l-8-8L67.9,20c-2.9-1.7-6-3.1-9.3-3.9L55.7,2.4H44.3l-2.9,13.6 c-3.3,0.8-6.4,2.1-9.3,3.9l-11.7-7.6l-8,8L20,32.1c-1.7,2.9-3.1,6-3.9,9.3L2.4,44.3v11.4l13.6,2.9c0.8,3.3,2.1,6.4,3.9,9.3 l-7.6,11.7l8,8L32.1,80c2.9,1.7,6,3.1,9.3,3.9l2.9,13.6h11.4l2.9-13.6c3.3-0.8,6.4-2.1,9.3-3.9l11.7,7.6l8-8L80,67.9 c1.7-2.9,3.1-6,3.9-9.3L97.6,55.7z M50,65.6c-8.7,0-15.6-7-15.6-15.6s7-15.6,15.6-15.6s15.6,7,15.6,15.6S58.7,65.6,50,65.6z"></path></svg></div></div><div class="text">loading</div></div>'); $(window).on('load', function(){ setTimeout(removeLoader, 2000); //wait for page load PLUS two seconds. }); ``` Here is my CSS code which i use to style the preloader for my web page using vannila js. The css below show all the color correctly and other details ``` #loader-background { position:absolute;; top:0; left:0; width:100%; height:100%; background-color: #f1f2f7; z-index: 5; } .load { position: relative; margin: 50px auto; width: 100px; height: 80px; z-index: 10; } .gear { position: absolute; z-index: 15; width: 40px; height: 40px; animation: spin 5s infinite; } .two { left: 40px; width: 80px; height: 80px; animation: spin-reverse 5s infinite; } .three { top: 45px; left: -10px; width: 60px; height: 60px; } @keyframes spin { 50% { transform: rotate(360deg); } } @keyframes spin-reverse { 50% { transform: rotate(-360deg); } } .lil-circle { position: absolute; border-radius: 50%; box-shadow: inset 0 0 10px 2px gray, 0 0 50px white; width: 100px; height: 100px; opacity: .65; } .blur-circle { z-index: 20; position: absolute; top: -19px; left: -19px; } @import url(https://fonts.googleapis.com/css?family=Open+Sans); ```
2021/08/24
[ "https://Stackoverflow.com/questions/68903488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15518305/" ]
You can write a single condition with `Optional`: ``` if (rule.getName() != null) { ruleBean.setName(rule.getName()); } ``` becomes: ``` Optional.ofNullable(rule.getName()).ifPresent(ruleBean::setName); ``` It's harder to chain this to give the "if else" behaviour you have, though. It looks like what you're trying to detect with the "if/else" is whether *some* update was performed. To achieve this, you could have a method like: ``` <T> boolean did(T value, Consumer<? super T> consumer) { if (value == null) return false; consumer.accept(value); return true; } ``` Then you can write your chain as: ``` boolean didSomething = did(rule.getName(), ruleBean::setName) || did(rule.getScript(), ruleBean::setScript) /* etc */; if (!didSomething) { // Return your error response. } ``` Because of the short-circuiting behaviour of `||`, this will stop after the first call to `did` which "did" something, like the if/else if. And if you actually want to apply the update for any non-null value, simply change `||` to `|`. The value of `didSomething` is still false if none of the conditions matched, as before.
* If you have a lot of attributes in `rule` need to check, you can use `reflection` to make it clean a little. * If you just have a few attributes need to check, the `if` solution is a clean and readable way to do it. * Waring: the `reflection` solution may lead to a performance issue. ### example code: ``` test.java public class test{ public static void main(String[] args) { Foo rule = new Foo(); Foo ruleBean = new Foo(); rule.setName("foo"); rule.setTargets(1); # the field you need to check, not necessary to check all attributes. List<String> fields = Arrays.asList("Name", "Script", "Targets"); for (String field : fields) { try { Object temp = rule.getClass().getMethod("get"+field).invoke(rule); if (temp != null) { ruleBean.getClass().getMethod("set"+field,temp.getClass()).invoke(ruleBean,temp); } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } System.out.println(ruleBean.getName()); System.out.println(ruleBean.getScript()); System.out.println(ruleBean.getTargets()); } } Foo.java public class Foo { private String name; private String script; private Integer targets; public void setName(String s) { this.name = s; } public String getName() { return this.name; } public void setScript(String s) { this.script = s; } public String getScript() { return this.script; } public void setTargets(Integer s) { this.targets = s; } public Integer getTargets() { return this.targets; } } ``` ### result: ``` foo null 1 ```
68,903,488
Below are my javascript code, why the preloader doesnt show up when I refresh? The first code i use to append a new preloader inside it when it start running javascript, does anyone know how I can append a things that used to replace another thing at the bottom there, as well as three screw driver is running around the place and here. ``` $('body').append('<div id="loader-background"><div class="load"><div class="gear one"><svg id="blue" viewbox="0 0 100 100" fill="#aeb2b7"><path d="M97.6,55.7V44.3l-13.6-2.9c-0.8-3.3-2.1-6.4-3.9-9.3l7.6-11.7l-8-8L67.9,20c-2.9-1.7-6-3.1-9.3-3.9L55.7,2.4H44.3l-2.9,13.6 c-3.3,0.8-6.4,2.1-9.3,3.9l-11.7-7.6l-8,8L20,32.1c-1.7,2.9-3.1,6-3.9,9.3L2.4,44.3v11.4l13.6,2.9c0.8,3.3,2.1,6.4,3.9,9.3 l-7.6,11.7l8,8L32.1,80c2.9,1.7,6,3.1,9.3,3.9l2.9,13.6h11.4l2.9-13.6c3.3-0.8,6.4-2.1,9.3-3.9l11.7,7.6l8-8L80,67.9 c1.7-2.9,3.1-6,3.9-9.3L97.6,55.7z M50,65.6c-8.7,0-15.6-7-15.6-15.6s7-15.6,15.6-15.6s15.6,7,15.6,15.6S58.7,65.6,50,65.6z"></path></svg></div><div class="gear two"><svg id="pink" viewbox="0 0 100 100" fill="#ff6c60"><path d="M97.6,55.7V44.3l-13.6-2.9c-0.8-3.3-2.1-6.4-3.9-9.3l7.6-11.7l-8-8L67.9,20c-2.9-1.7-6-3.1-9.3-3.9L55.7,2.4H44.3l-2.9,13.6 c-3.3,0.8-6.4,2.1-9.3,3.9l-11.7-7.6l-8,8L20,32.1c-1.7,2.9-3.1,6-3.9,9.3L2.4,44.3v11.4l13.6,2.9c0.8,3.3,2.1,6.4,3.9,9.3 l-7.6,11.7l8,8L32.1,80c2.9,1.7,6,3.1,9.3,3.9l2.9,13.6h11.4l2.9-13.6c3.3-0.8,6.4-2.1,9.3-3.9l11.7,7.6l8-8L80,67.9 c1.7-2.9,3.1-6,3.9-9.3L97.6,55.7z M50,65.6c-8.7,0-15.6-7-15.6-15.6s7-15.6,15.6-15.6s15.6,7,15.6,15.6S58.7,65.6,50,65.6z"></path></svg></div><div class="gear three"><svg id="yellow" viewbox="0 0 100 100" fill="#36404e"><path d="M97.6,55.7V44.3l-13.6-2.9c-0.8-3.3-2.1-6.4-3.9-9.3l7.6-11.7l-8-8L67.9,20c-2.9-1.7-6-3.1-9.3-3.9L55.7,2.4H44.3l-2.9,13.6 c-3.3,0.8-6.4,2.1-9.3,3.9l-11.7-7.6l-8,8L20,32.1c-1.7,2.9-3.1,6-3.9,9.3L2.4,44.3v11.4l13.6,2.9c0.8,3.3,2.1,6.4,3.9,9.3 l-7.6,11.7l8,8L32.1,80c2.9,1.7,6,3.1,9.3,3.9l2.9,13.6h11.4l2.9-13.6c3.3-0.8,6.4-2.1,9.3-3.9l11.7,7.6l8-8L80,67.9 c1.7-2.9,3.1-6,3.9-9.3L97.6,55.7z M50,65.6c-8.7,0-15.6-7-15.6-15.6s7-15.6,15.6-15.6s15.6,7,15.6,15.6S58.7,65.6,50,65.6z"></path></svg></div></div><div class="text">loading</div></div>'); $(window).on('load', function(){ setTimeout(removeLoader, 2000); //wait for page load PLUS two seconds. }); ``` Here is my CSS code which i use to style the preloader for my web page using vannila js. The css below show all the color correctly and other details ``` #loader-background { position:absolute;; top:0; left:0; width:100%; height:100%; background-color: #f1f2f7; z-index: 5; } .load { position: relative; margin: 50px auto; width: 100px; height: 80px; z-index: 10; } .gear { position: absolute; z-index: 15; width: 40px; height: 40px; animation: spin 5s infinite; } .two { left: 40px; width: 80px; height: 80px; animation: spin-reverse 5s infinite; } .three { top: 45px; left: -10px; width: 60px; height: 60px; } @keyframes spin { 50% { transform: rotate(360deg); } } @keyframes spin-reverse { 50% { transform: rotate(-360deg); } } .lil-circle { position: absolute; border-radius: 50%; box-shadow: inset 0 0 10px 2px gray, 0 0 50px white; width: 100px; height: 100px; opacity: .65; } .blur-circle { z-index: 20; position: absolute; top: -19px; left: -19px; } @import url(https://fonts.googleapis.com/css?family=Open+Sans); ```
2021/08/24
[ "https://Stackoverflow.com/questions/68903488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15518305/" ]
[Java validation API](https://beanvalidation.org/2.0/) (JSR-380) can be very handy in this type of problems, if you can afford the dependencies. In this specific case, you can just annotate your bean: ```java import javax.validation.constraints.NotNull; // ... public class Rule { @NotNull private String description; @NotNull private String name; @NotNull private String script; @NotNull private String targets; @NotNull private String trigger; } ``` (there are more [built-in constraint definitions](https://beanvalidation.org/2.0/spec/#builtinconstraints)) And then validate using Hibernate Validator (the reference implementation of the validation API): ```java Rule rule = new Rule(); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Rule>> violations = validator.validate(rule); if (violations.isEmpty()) { //all good! } else { //bean is not valid } ``` In order to use this approach, you need two new dependencies in your pom.xml: Java Validation API: ```xml <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.1.Final</version> </dependency> ``` and Hibernate Validator ```xml <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.13.Final</version> </dependency> ```
* If you have a lot of attributes in `rule` need to check, you can use `reflection` to make it clean a little. * If you just have a few attributes need to check, the `if` solution is a clean and readable way to do it. * Waring: the `reflection` solution may lead to a performance issue. ### example code: ``` test.java public class test{ public static void main(String[] args) { Foo rule = new Foo(); Foo ruleBean = new Foo(); rule.setName("foo"); rule.setTargets(1); # the field you need to check, not necessary to check all attributes. List<String> fields = Arrays.asList("Name", "Script", "Targets"); for (String field : fields) { try { Object temp = rule.getClass().getMethod("get"+field).invoke(rule); if (temp != null) { ruleBean.getClass().getMethod("set"+field,temp.getClass()).invoke(ruleBean,temp); } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } System.out.println(ruleBean.getName()); System.out.println(ruleBean.getScript()); System.out.println(ruleBean.getTargets()); } } Foo.java public class Foo { private String name; private String script; private Integer targets; public void setName(String s) { this.name = s; } public String getName() { return this.name; } public void setScript(String s) { this.script = s; } public String getScript() { return this.script; } public void setTargets(Integer s) { this.targets = s; } public Integer getTargets() { return this.targets; } } ``` ### result: ``` foo null 1 ```
68,903,488
Below are my javascript code, why the preloader doesnt show up when I refresh? The first code i use to append a new preloader inside it when it start running javascript, does anyone know how I can append a things that used to replace another thing at the bottom there, as well as three screw driver is running around the place and here. ``` $('body').append('<div id="loader-background"><div class="load"><div class="gear one"><svg id="blue" viewbox="0 0 100 100" fill="#aeb2b7"><path d="M97.6,55.7V44.3l-13.6-2.9c-0.8-3.3-2.1-6.4-3.9-9.3l7.6-11.7l-8-8L67.9,20c-2.9-1.7-6-3.1-9.3-3.9L55.7,2.4H44.3l-2.9,13.6 c-3.3,0.8-6.4,2.1-9.3,3.9l-11.7-7.6l-8,8L20,32.1c-1.7,2.9-3.1,6-3.9,9.3L2.4,44.3v11.4l13.6,2.9c0.8,3.3,2.1,6.4,3.9,9.3 l-7.6,11.7l8,8L32.1,80c2.9,1.7,6,3.1,9.3,3.9l2.9,13.6h11.4l2.9-13.6c3.3-0.8,6.4-2.1,9.3-3.9l11.7,7.6l8-8L80,67.9 c1.7-2.9,3.1-6,3.9-9.3L97.6,55.7z M50,65.6c-8.7,0-15.6-7-15.6-15.6s7-15.6,15.6-15.6s15.6,7,15.6,15.6S58.7,65.6,50,65.6z"></path></svg></div><div class="gear two"><svg id="pink" viewbox="0 0 100 100" fill="#ff6c60"><path d="M97.6,55.7V44.3l-13.6-2.9c-0.8-3.3-2.1-6.4-3.9-9.3l7.6-11.7l-8-8L67.9,20c-2.9-1.7-6-3.1-9.3-3.9L55.7,2.4H44.3l-2.9,13.6 c-3.3,0.8-6.4,2.1-9.3,3.9l-11.7-7.6l-8,8L20,32.1c-1.7,2.9-3.1,6-3.9,9.3L2.4,44.3v11.4l13.6,2.9c0.8,3.3,2.1,6.4,3.9,9.3 l-7.6,11.7l8,8L32.1,80c2.9,1.7,6,3.1,9.3,3.9l2.9,13.6h11.4l2.9-13.6c3.3-0.8,6.4-2.1,9.3-3.9l11.7,7.6l8-8L80,67.9 c1.7-2.9,3.1-6,3.9-9.3L97.6,55.7z M50,65.6c-8.7,0-15.6-7-15.6-15.6s7-15.6,15.6-15.6s15.6,7,15.6,15.6S58.7,65.6,50,65.6z"></path></svg></div><div class="gear three"><svg id="yellow" viewbox="0 0 100 100" fill="#36404e"><path d="M97.6,55.7V44.3l-13.6-2.9c-0.8-3.3-2.1-6.4-3.9-9.3l7.6-11.7l-8-8L67.9,20c-2.9-1.7-6-3.1-9.3-3.9L55.7,2.4H44.3l-2.9,13.6 c-3.3,0.8-6.4,2.1-9.3,3.9l-11.7-7.6l-8,8L20,32.1c-1.7,2.9-3.1,6-3.9,9.3L2.4,44.3v11.4l13.6,2.9c0.8,3.3,2.1,6.4,3.9,9.3 l-7.6,11.7l8,8L32.1,80c2.9,1.7,6,3.1,9.3,3.9l2.9,13.6h11.4l2.9-13.6c3.3-0.8,6.4-2.1,9.3-3.9l11.7,7.6l8-8L80,67.9 c1.7-2.9,3.1-6,3.9-9.3L97.6,55.7z M50,65.6c-8.7,0-15.6-7-15.6-15.6s7-15.6,15.6-15.6s15.6,7,15.6,15.6S58.7,65.6,50,65.6z"></path></svg></div></div><div class="text">loading</div></div>'); $(window).on('load', function(){ setTimeout(removeLoader, 2000); //wait for page load PLUS two seconds. }); ``` Here is my CSS code which i use to style the preloader for my web page using vannila js. The css below show all the color correctly and other details ``` #loader-background { position:absolute;; top:0; left:0; width:100%; height:100%; background-color: #f1f2f7; z-index: 5; } .load { position: relative; margin: 50px auto; width: 100px; height: 80px; z-index: 10; } .gear { position: absolute; z-index: 15; width: 40px; height: 40px; animation: spin 5s infinite; } .two { left: 40px; width: 80px; height: 80px; animation: spin-reverse 5s infinite; } .three { top: 45px; left: -10px; width: 60px; height: 60px; } @keyframes spin { 50% { transform: rotate(360deg); } } @keyframes spin-reverse { 50% { transform: rotate(-360deg); } } .lil-circle { position: absolute; border-radius: 50%; box-shadow: inset 0 0 10px 2px gray, 0 0 50px white; width: 100px; height: 100px; opacity: .65; } .blur-circle { z-index: 20; position: absolute; top: -19px; left: -19px; } @import url(https://fonts.googleapis.com/css?family=Open+Sans); ```
2021/08/24
[ "https://Stackoverflow.com/questions/68903488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15518305/" ]
You can write a single condition with `Optional`: ``` if (rule.getName() != null) { ruleBean.setName(rule.getName()); } ``` becomes: ``` Optional.ofNullable(rule.getName()).ifPresent(ruleBean::setName); ``` It's harder to chain this to give the "if else" behaviour you have, though. It looks like what you're trying to detect with the "if/else" is whether *some* update was performed. To achieve this, you could have a method like: ``` <T> boolean did(T value, Consumer<? super T> consumer) { if (value == null) return false; consumer.accept(value); return true; } ``` Then you can write your chain as: ``` boolean didSomething = did(rule.getName(), ruleBean::setName) || did(rule.getScript(), ruleBean::setScript) /* etc */; if (!didSomething) { // Return your error response. } ``` Because of the short-circuiting behaviour of `||`, this will stop after the first call to `did` which "did" something, like the if/else if. And if you actually want to apply the update for any non-null value, simply change `||` to `|`. The value of `didSomething` is still false if none of the conditions matched, as before.
[Java validation API](https://beanvalidation.org/2.0/) (JSR-380) can be very handy in this type of problems, if you can afford the dependencies. In this specific case, you can just annotate your bean: ```java import javax.validation.constraints.NotNull; // ... public class Rule { @NotNull private String description; @NotNull private String name; @NotNull private String script; @NotNull private String targets; @NotNull private String trigger; } ``` (there are more [built-in constraint definitions](https://beanvalidation.org/2.0/spec/#builtinconstraints)) And then validate using Hibernate Validator (the reference implementation of the validation API): ```java Rule rule = new Rule(); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Rule>> violations = validator.validate(rule); if (violations.isEmpty()) { //all good! } else { //bean is not valid } ``` In order to use this approach, you need two new dependencies in your pom.xml: Java Validation API: ```xml <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.1.Final</version> </dependency> ``` and Hibernate Validator ```xml <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.13.Final</version> </dependency> ```
2,942,983
`<div id="id" class="div-style"><img id="id" class="img-style"></div>` I would like to use the id attribute as a way for jQuery to select the element, and the class attribute for CSS to style it. My guess for jQuery selector ran thusly: `$("#id .div-class")` and `$("#id .img-class")` This returns the error "Selector expected"
2010/05/31
[ "https://Stackoverflow.com/questions/2942983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/341121/" ]
I am not 100% sure and I didn't test it but according to Hibernate's documentation: > > [16.2.2. Using stored procedures for querying](http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querysql.html#sp_query) > --------------------------------------------------------------------------------------------------------------------------------- > > > Hibernate3 provides support for > queries via stored procedures and > functions. Most of the following > documentation is equivalent for both. > **The stored procedure/function must return a resultset as the first > out-parameter to be able to work with > Hibernate**. An example of such a > stored function in Oracle 9 and higher > is as follows: > > > > ``` > CREATE OR REPLACE FUNCTION selectAllEmployments > RETURN SYS_REFCURSOR > AS > st_cursor SYS_REFCURSOR; > BEGIN > OPEN st_cursor FOR > SELECT EMPLOYEE, EMPLOYER, > STARTDATE, ENDDATE, > REGIONCODE, EID, VALUE, CURRENCY > FROM EMPLOYMENT; > RETURN st_cursor; > END; > > ``` > > To use this query in Hibernate you > need to map it via a named query. > > > > ``` > <sql-query name="selectAllEmployees_SP" callable="true"> > <return alias="emp" class="Employment"> > <return-property name="employee" column="EMPLOYEE"/> > <return-property name="employer" column="EMPLOYER"/> > <return-property name="startDate" column="STARTDATE"/> > <return-property name="endDate" column="ENDDATE"/> > <return-property name="regionCode" column="REGIONCODE"/> > <return-property name="id" column="EID"/> > <return-property name="salary"> > <return-column name="VALUE"/> > <return-column name="CURRENCY"/> > </return-property> > </return> > { ? = call selectAllEmployments() } > </sql-query> > > ``` > > Stored procedures currently only > return scalars and entities. > `<return-join>` and > `<load-collection>` are not supported. > > > ### [16.2.2.1. Rules/limitations for using stored procedures](http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querysql.html#querysql-limits-storedprocedures) > > > You cannot use stored procedures with > Hibernate unless you follow some > procedure/function rules. **If they do > not follow those rules they are not > usable with Hibernate. If you still > want to use these procedures you have > to execute them via > `session.connection()`**. The rules are > different for each database, since > database vendors have different stored > procedure semantics/syntax. > > > Stored procedure queries cannot be > paged with > `setFirstResult()/setMaxResults()`. > > > The recommended call form is standard > SQL92: `{ ? = call > functionName(<parameters>) }` or `{ ? > = call procedureName(<parameters>}`. Native call syntax is not supported. > > > For Oracle the following rules apply: > > > * **A function must return a result set. The first parameter of a > procedure must be an OUT that returns > a result set. This is done by using a > SYS\_REFCURSOR type in Oracle 9 or > 10.** In Oracle you need to define a REF CURSOR type. See Oracle literature > for further information. > > > ... > > > As I said, I'm not sure but my understanding is that you'll have to use `session.getConnection()` here.
`callable = true` is for calling stored procedures with `{? = call ...()}` syntax. Oracle's `select ... from dual` syntax is a normal query, so you don't need `callable = true`: ``` <sql-query name="TransferLocationFix"> <return-scalar column="retVal" type="string"/> select Transferlocation_Fix(:mnemonic) as retVal from dual </sql-query> ```
2,942,983
`<div id="id" class="div-style"><img id="id" class="img-style"></div>` I would like to use the id attribute as a way for jQuery to select the element, and the class attribute for CSS to style it. My guess for jQuery selector ran thusly: `$("#id .div-class")` and `$("#id .img-class")` This returns the error "Selector expected"
2010/05/31
[ "https://Stackoverflow.com/questions/2942983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/341121/" ]
For further reference, here is my final solution: ``` CallableStatement statement = session.connection().prepareCall( "{ ? = call Transferlocation_Fix(?) }"); statement.registerOutParameter(1, Types.VARCHAR); statement.setString(2, "FC3"); statement.execute(); String result = statement.getString(1); ```
`callable = true` is for calling stored procedures with `{? = call ...()}` syntax. Oracle's `select ... from dual` syntax is a normal query, so you don't need `callable = true`: ``` <sql-query name="TransferLocationFix"> <return-scalar column="retVal" type="string"/> select Transferlocation_Fix(:mnemonic) as retVal from dual </sql-query> ```
2,942,983
`<div id="id" class="div-style"><img id="id" class="img-style"></div>` I would like to use the id attribute as a way for jQuery to select the element, and the class attribute for CSS to style it. My guess for jQuery selector ran thusly: `$("#id .div-class")` and `$("#id .img-class")` This returns the error "Selector expected"
2010/05/31
[ "https://Stackoverflow.com/questions/2942983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/341121/" ]
For further reference, here is my final solution: ``` CallableStatement statement = session.connection().prepareCall( "{ ? = call Transferlocation_Fix(?) }"); statement.registerOutParameter(1, Types.VARCHAR); statement.setString(2, "FC3"); statement.execute(); String result = statement.getString(1); ```
I am not 100% sure and I didn't test it but according to Hibernate's documentation: > > [16.2.2. Using stored procedures for querying](http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querysql.html#sp_query) > --------------------------------------------------------------------------------------------------------------------------------- > > > Hibernate3 provides support for > queries via stored procedures and > functions. Most of the following > documentation is equivalent for both. > **The stored procedure/function must return a resultset as the first > out-parameter to be able to work with > Hibernate**. An example of such a > stored function in Oracle 9 and higher > is as follows: > > > > ``` > CREATE OR REPLACE FUNCTION selectAllEmployments > RETURN SYS_REFCURSOR > AS > st_cursor SYS_REFCURSOR; > BEGIN > OPEN st_cursor FOR > SELECT EMPLOYEE, EMPLOYER, > STARTDATE, ENDDATE, > REGIONCODE, EID, VALUE, CURRENCY > FROM EMPLOYMENT; > RETURN st_cursor; > END; > > ``` > > To use this query in Hibernate you > need to map it via a named query. > > > > ``` > <sql-query name="selectAllEmployees_SP" callable="true"> > <return alias="emp" class="Employment"> > <return-property name="employee" column="EMPLOYEE"/> > <return-property name="employer" column="EMPLOYER"/> > <return-property name="startDate" column="STARTDATE"/> > <return-property name="endDate" column="ENDDATE"/> > <return-property name="regionCode" column="REGIONCODE"/> > <return-property name="id" column="EID"/> > <return-property name="salary"> > <return-column name="VALUE"/> > <return-column name="CURRENCY"/> > </return-property> > </return> > { ? = call selectAllEmployments() } > </sql-query> > > ``` > > Stored procedures currently only > return scalars and entities. > `<return-join>` and > `<load-collection>` are not supported. > > > ### [16.2.2.1. Rules/limitations for using stored procedures](http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querysql.html#querysql-limits-storedprocedures) > > > You cannot use stored procedures with > Hibernate unless you follow some > procedure/function rules. **If they do > not follow those rules they are not > usable with Hibernate. If you still > want to use these procedures you have > to execute them via > `session.connection()`**. The rules are > different for each database, since > database vendors have different stored > procedure semantics/syntax. > > > Stored procedure queries cannot be > paged with > `setFirstResult()/setMaxResults()`. > > > The recommended call form is standard > SQL92: `{ ? = call > functionName(<parameters>) }` or `{ ? > = call procedureName(<parameters>}`. Native call syntax is not supported. > > > For Oracle the following rules apply: > > > * **A function must return a result set. The first parameter of a > procedure must be an OUT that returns > a result set. This is done by using a > SYS\_REFCURSOR type in Oracle 9 or > 10.** In Oracle you need to define a REF CURSOR type. See Oracle literature > for further information. > > > ... > > > As I said, I'm not sure but my understanding is that you'll have to use `session.getConnection()` here.
2,942,983
`<div id="id" class="div-style"><img id="id" class="img-style"></div>` I would like to use the id attribute as a way for jQuery to select the element, and the class attribute for CSS to style it. My guess for jQuery selector ran thusly: `$("#id .div-class")` and `$("#id .img-class")` This returns the error "Selector expected"
2010/05/31
[ "https://Stackoverflow.com/questions/2942983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/341121/" ]
I am not 100% sure and I didn't test it but according to Hibernate's documentation: > > [16.2.2. Using stored procedures for querying](http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querysql.html#sp_query) > --------------------------------------------------------------------------------------------------------------------------------- > > > Hibernate3 provides support for > queries via stored procedures and > functions. Most of the following > documentation is equivalent for both. > **The stored procedure/function must return a resultset as the first > out-parameter to be able to work with > Hibernate**. An example of such a > stored function in Oracle 9 and higher > is as follows: > > > > ``` > CREATE OR REPLACE FUNCTION selectAllEmployments > RETURN SYS_REFCURSOR > AS > st_cursor SYS_REFCURSOR; > BEGIN > OPEN st_cursor FOR > SELECT EMPLOYEE, EMPLOYER, > STARTDATE, ENDDATE, > REGIONCODE, EID, VALUE, CURRENCY > FROM EMPLOYMENT; > RETURN st_cursor; > END; > > ``` > > To use this query in Hibernate you > need to map it via a named query. > > > > ``` > <sql-query name="selectAllEmployees_SP" callable="true"> > <return alias="emp" class="Employment"> > <return-property name="employee" column="EMPLOYEE"/> > <return-property name="employer" column="EMPLOYER"/> > <return-property name="startDate" column="STARTDATE"/> > <return-property name="endDate" column="ENDDATE"/> > <return-property name="regionCode" column="REGIONCODE"/> > <return-property name="id" column="EID"/> > <return-property name="salary"> > <return-column name="VALUE"/> > <return-column name="CURRENCY"/> > </return-property> > </return> > { ? = call selectAllEmployments() } > </sql-query> > > ``` > > Stored procedures currently only > return scalars and entities. > `<return-join>` and > `<load-collection>` are not supported. > > > ### [16.2.2.1. Rules/limitations for using stored procedures](http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querysql.html#querysql-limits-storedprocedures) > > > You cannot use stored procedures with > Hibernate unless you follow some > procedure/function rules. **If they do > not follow those rules they are not > usable with Hibernate. If you still > want to use these procedures you have > to execute them via > `session.connection()`**. The rules are > different for each database, since > database vendors have different stored > procedure semantics/syntax. > > > Stored procedure queries cannot be > paged with > `setFirstResult()/setMaxResults()`. > > > The recommended call form is standard > SQL92: `{ ? = call > functionName(<parameters>) }` or `{ ? > = call procedureName(<parameters>}`. Native call syntax is not supported. > > > For Oracle the following rules apply: > > > * **A function must return a result set. The first parameter of a > procedure must be an OUT that returns > a result set. This is done by using a > SYS\_REFCURSOR type in Oracle 9 or > 10.** In Oracle you need to define a REF CURSOR type. See Oracle literature > for further information. > > > ... > > > As I said, I'm not sure but my understanding is that you'll have to use `session.getConnection()` here.
I've run into a similar question/problem and I've come to realize the changes should be done on the sql part as hibernate works only with cursor returns. I've described everything here: <http://www.len.ro/2011/10/call-oracle-procedure-from-hibernate/>
2,942,983
`<div id="id" class="div-style"><img id="id" class="img-style"></div>` I would like to use the id attribute as a way for jQuery to select the element, and the class attribute for CSS to style it. My guess for jQuery selector ran thusly: `$("#id .div-class")` and `$("#id .img-class")` This returns the error "Selector expected"
2010/05/31
[ "https://Stackoverflow.com/questions/2942983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/341121/" ]
For further reference, here is my final solution: ``` CallableStatement statement = session.connection().prepareCall( "{ ? = call Transferlocation_Fix(?) }"); statement.registerOutParameter(1, Types.VARCHAR); statement.setString(2, "FC3"); statement.execute(); String result = statement.getString(1); ```
I've run into a similar question/problem and I've come to realize the changes should be done on the sql part as hibernate works only with cursor returns. I've described everything here: <http://www.len.ro/2011/10/call-oracle-procedure-from-hibernate/>
70,518,403
Considering a file with string on each lines, I want to create an array with each line of the file as an element of the array. I know I can do it like so: ```scala import scala.io.Source val path: String = "path/to/text/file.txt" var array: Array[String] = new Array[String](0) for (line <- Source.fromFile(path).getLines) { array :+= line } ``` But it's quite long and maybe not very optimal. I look on the web and didn't find any better way of doing it. Do you have a better way of creating such array using Array built-in methods I may have missed or using `map` or anything else ? Thanks.
2021/12/29
[ "https://Stackoverflow.com/questions/70518403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12873652/" ]
Using getLines returns an Iteration, from which you can use toArray ``` val path: String = "path/to/text/file.txt" val array: Array[String] = Source.fromFile(path).getLines.toArray ```
On top of the answer by @TheFourthBird: In your code you don't close the file. This might be ok for short programs, but in a long-lived process you should close it explicitly. This can be accomplished by: ```scala import scala.io.Source import scala.util.{Try, Using} val path: String = "path/to/text/file.txt" val tryLines: Try[Array[String]] = Using(Source.fromFile(path))(_.getLines.toArray) ``` See [What's the right way to use scala.io.Source?](https://stackoverflow.com/questions/4458864/whats-the-right-way-to-use-scala-io-source)
19,062,294
This is the part of the code that I'm using to display content from rss.php feed. ``` for($x=0;$x<$limit;$x++) { $title = str_replace(' & ', ' &amp; ', $feed[$x]['title']); $link = $feed[$x]['link']; $description = $feed[$x]['desc']; $date = date('l F d, Y', strtotime($feed[$x]['date'])); echo '<p><strong><a href="'.$link.'" title="'.$title.'">'.$title.'</a></strong><br />'; echo '<small><em>Posted on '.$date.'</em></small></p>'; echo '<p><a style="color:#000;text-decoration:none;" href="'.$link.'" title="'.$title.'"></>'.$description.'</p>'; ``` The problem is that `.$description.` contains image + text and I'm ending with wording next to images. Is there any way I can add `<br>` tag on all images that are displayed on the page? I don't have access to rss.php.
2013/09/28
[ "https://Stackoverflow.com/questions/19062294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2643234/" ]
This is probably not the cause of your immediate problem, but code like this: ``` } catch (MalformedURLException ex) { } catch (IOException ioe) { } ``` is an accident waiting to happen. If any of those exceptions happens, you've told the application to *silently ignore them*. Just don't do it! If you don't know the correct thing to do with a checked exception, declare is as `thrown` in the method signature. Don't just throw it away.
``` package org.assume.StackOverflow; import java.io.File; public class Progress implements Runnable { private File file; private long totalSize; private int currentProgress; public Progress(String filePath, long totalSize) { this(new File(filePath), totalSize); } public Progress(File file, long totalSize) { this.file = file; this.totalSize = totalSize; new Thread(this).start(); } public int getProgress() { return currentProgress; } @Override public void run() { while (file.length() < (totalSize - 100)) { currentProgress = (int) (file.length() / totalSize); } } } ``` How to use it: ``` new Thread(new Progress(file, totalSize)).start(); ```
19,062,294
This is the part of the code that I'm using to display content from rss.php feed. ``` for($x=0;$x<$limit;$x++) { $title = str_replace(' & ', ' &amp; ', $feed[$x]['title']); $link = $feed[$x]['link']; $description = $feed[$x]['desc']; $date = date('l F d, Y', strtotime($feed[$x]['date'])); echo '<p><strong><a href="'.$link.'" title="'.$title.'">'.$title.'</a></strong><br />'; echo '<small><em>Posted on '.$date.'</em></small></p>'; echo '<p><a style="color:#000;text-decoration:none;" href="'.$link.'" title="'.$title.'"></>'.$description.'</p>'; ``` The problem is that `.$description.` contains image + text and I'm ending with wording next to images. Is there any way I can add `<br>` tag on all images that are displayed on the page? I don't have access to rss.php.
2013/09/28
[ "https://Stackoverflow.com/questions/19062294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2643234/" ]
This is probably not the cause of your immediate problem, but code like this: ``` } catch (MalformedURLException ex) { } catch (IOException ioe) { } ``` is an accident waiting to happen. If any of those exceptions happens, you've told the application to *silently ignore them*. Just don't do it! If you don't know the correct thing to do with a checked exception, declare is as `thrown` in the method signature. Don't just throw it away.
these lines are actually perfoming the downloading and writing ``` while (b != -1) { b = in.read(); if (b != -1) { out.write(b); } } ``` to add progress add something : ``` while (b != -1) { b = in.read(); if (b != -1) { downloaded += b; out.write(b); } } ``` and progress is ``` downloaded / conn.getContentLength() * 100 ```
12,580,269
Not sure if this question has been asked elsewhere... For a website project that I'm working on, I created an ASPX web form that will send an email containing the contents of the form on button click. I tried it and it worked when I'm using the Yahoo SMTP server and testing using my personal Yahoo email address (+ specifying the username and password). However, it wouldn't work when I'm using the SMTP server for mail messages for the website (after I've created a new admin email account in the website). The website is up and running and I'm able to send an email to the website's admin email account (through Yahoo) but just not when sending through the ASPX web form. Here is the code for using the Yahoo SMTP server and it works fine: ``` SmtpServer.Credentials = New Net.NetworkCredential("username@yahoo.com", "password") SmtpServer.Port = "25" SmtpServer.Host = "smtp.mail.yahoo.com" mail.From = New MailAddress("username@yahoo.com") mail.To.Add("username@yahoo.com") mail.Subject = "RE: Message Subject" mail.Body = "Message goes here." SmtpServer.Send(mail) ``` Now, here is the code for using my website's SMTP server which doesn't work: ``` SmtpServer.Port = "25" SmtpServer.Host = "127.0.0.1" mail.From = New MailAddress("admin@awesomewebsite.org.au") mail.To.Add("admin@awesomewebsite.org.au") mail.Subject = "RE: Message Subject" mail.Body = "Message goes here." SmtpServer.Send(mail) ``` These are the correct port and host numbers given by the web hosting company that hosts the website. They also said that username and password are not needed. I also tried appending this to the beginning of the code but it still wouldn't work: ``` SmtpServer.Credentials = New Net.NetworkCredential() ``` or even ``` SmtpServer.Credentials = New Net.NetworkCredential("", "") ``` I really don't know what to do. Please help this newbie out. Any response is appreciated. By the way, the error message that I get when I test this out appears in a message box: "Failure sending mail."
2012/09/25
[ "https://Stackoverflow.com/questions/12580269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You need to create an email account in your web site and use those credentials to send the mail just as you did with yahoo (This can be done in your admin portal of the website but some hosting providers will charge you separately for the email service). Further more the correct smtp server is also should be given, that depends on your hosting provider. You can get that information from your hosting provider. 127.0.0.1 will not work here anyway.
Don't import 'System.Net.Mail'. Completed code is shown below: ``` Dim SmtpServer As New Net.Mail.SmtpClient Dim mail As New Net.Mail.MailMessage SmtpServer.Host = "198.154.99.8" SmtpServer.UseDefaultCredentials = False SmtpServer.Credentials = New System.Net.NetworkCredential("admin@awesomewebsite.org.au", "password") mail.From = New Net.Mail.MailAddress("admin@awesomewebsite.org.au") mail.To.Add("admin@awesomewebsite.org.au") mail.Subject = "RE: Message Subject" mail.Body = "Message goes here." SmtpServer.Send(mail) ```
47,369,143
I have implemented the waypoint mission in android using DJI mobile sdk. Now I want the drone to hover around each waypoint when it reaches there, like a hotpoint mission, with the waypoint as the hot point, after hovering it should go to the next waypoint and do the same. Is it possible to pause the waypoint mission when it reaches the waypoint and start the hot point mission? Or this can be done using timeline? Can anyone shed some light on this? Cannot find proper solution in Internet.
2017/11/18
[ "https://Stackoverflow.com/questions/47369143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5689605/" ]
No you don't need to use the same IDE. But be careful, different ide's have different files that should not go to git. IntelliJ produces `.iml` files and Eclipse produce `.project` files. Some other files might also exist and you may not want them to go git. So, you need to define your `.gitignore` files carefully and you are good to go.
You do not need to use same IDE. The two you mentioned has property of connecting git so you can just go as you want. Just import your projects from git.
47,369,143
I have implemented the waypoint mission in android using DJI mobile sdk. Now I want the drone to hover around each waypoint when it reaches there, like a hotpoint mission, with the waypoint as the hot point, after hovering it should go to the next waypoint and do the same. Is it possible to pause the waypoint mission when it reaches the waypoint and start the hot point mission? Or this can be done using timeline? Can anyone shed some light on this? Cannot find proper solution in Internet.
2017/11/18
[ "https://Stackoverflow.com/questions/47369143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5689605/" ]
Unless you decide to upload IDE specific configurations into your source control, or if you don't use something like Maven or Gradle to manage your source dependencies, it won't matter.
You do not need to use same IDE. The two you mentioned has property of connecting git so you can just go as you want. Just import your projects from git.
47,369,143
I have implemented the waypoint mission in android using DJI mobile sdk. Now I want the drone to hover around each waypoint when it reaches there, like a hotpoint mission, with the waypoint as the hot point, after hovering it should go to the next waypoint and do the same. Is it possible to pause the waypoint mission when it reaches the waypoint and start the hot point mission? Or this can be done using timeline? Can anyone shed some light on this? Cannot find proper solution in Internet.
2017/11/18
[ "https://Stackoverflow.com/questions/47369143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5689605/" ]
IDE has nothing to do with your code or the machine you use, there are many IDEs you can choose from based on your personal preferences like visual-studio, Atom, sublime, notepad++ e.t.c. sure few people associate an IDE with particular language/framework, then again there is no standard for this, everyone has there own preference.
You do not need to use same IDE. The two you mentioned has property of connecting git so you can just go as you want. Just import your projects from git.
47,369,143
I have implemented the waypoint mission in android using DJI mobile sdk. Now I want the drone to hover around each waypoint when it reaches there, like a hotpoint mission, with the waypoint as the hot point, after hovering it should go to the next waypoint and do the same. Is it possible to pause the waypoint mission when it reaches the waypoint and start the hot point mission? Or this can be done using timeline? Can anyone shed some light on this? Cannot find proper solution in Internet.
2017/11/18
[ "https://Stackoverflow.com/questions/47369143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5689605/" ]
No you don't need to use the same IDE. But be careful, different ide's have different files that should not go to git. IntelliJ produces `.iml` files and Eclipse produce `.project` files. Some other files might also exist and you may not want them to go git. So, you need to define your `.gitignore` files carefully and you are good to go.
Unless you decide to upload IDE specific configurations into your source control, or if you don't use something like Maven or Gradle to manage your source dependencies, it won't matter.
47,369,143
I have implemented the waypoint mission in android using DJI mobile sdk. Now I want the drone to hover around each waypoint when it reaches there, like a hotpoint mission, with the waypoint as the hot point, after hovering it should go to the next waypoint and do the same. Is it possible to pause the waypoint mission when it reaches the waypoint and start the hot point mission? Or this can be done using timeline? Can anyone shed some light on this? Cannot find proper solution in Internet.
2017/11/18
[ "https://Stackoverflow.com/questions/47369143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5689605/" ]
No you don't need to use the same IDE. But be careful, different ide's have different files that should not go to git. IntelliJ produces `.iml` files and Eclipse produce `.project` files. Some other files might also exist and you may not want them to go git. So, you need to define your `.gitignore` files carefully and you are good to go.
IDE has nothing to do with your code or the machine you use, there are many IDEs you can choose from based on your personal preferences like visual-studio, Atom, sublime, notepad++ e.t.c. sure few people associate an IDE with particular language/framework, then again there is no standard for this, everyone has there own preference.
47,369,143
I have implemented the waypoint mission in android using DJI mobile sdk. Now I want the drone to hover around each waypoint when it reaches there, like a hotpoint mission, with the waypoint as the hot point, after hovering it should go to the next waypoint and do the same. Is it possible to pause the waypoint mission when it reaches the waypoint and start the hot point mission? Or this can be done using timeline? Can anyone shed some light on this? Cannot find proper solution in Internet.
2017/11/18
[ "https://Stackoverflow.com/questions/47369143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5689605/" ]
Unless you decide to upload IDE specific configurations into your source control, or if you don't use something like Maven or Gradle to manage your source dependencies, it won't matter.
IDE has nothing to do with your code or the machine you use, there are many IDEs you can choose from based on your personal preferences like visual-studio, Atom, sublime, notepad++ e.t.c. sure few people associate an IDE with particular language/framework, then again there is no standard for this, everyone has there own preference.
37,734,849
I have a Application in Asp.net MVC running perfectly in Visual Studio 2015, with IIS EXPRESS (local computer). I try execute this application in other computer (Windows Server 2008 R2 w/ IIS 7.5). I did a Deploy and i put in folder "C:\inetpub\wwwroot\testsite". On execute localhost/testsite, the index page showying normaly, but, on submit the form (it's a login page), my IIS presents the "401.0 ERROR". I am using "authentication mode forms": ``` <system.web> <compilation debug="true" targetFramework="4.5.2" /> <httpRuntime targetFramework="4.5.2" /> <authentication mode="Forms"> <forms loginUrl="~/User/Login" timeout="2880" /> </authentication> </system.web> ``` Pool application is "DefaultAppPool". The Authentication: "Anonymous = ON", "Forms = ON", others options = OFF. I tried various tips from other posts here from StackOverflow, But I could not solve my problem =( Thanks!
2016/06/09
[ "https://Stackoverflow.com/questions/37734849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5941828/" ]
Select the web application returning `401 - Unauthorized,` and double-click the Authentication feature. Right-click the "Anonymous Authentication" provider and select edit. Switch the default anonymous user account ("IUSR") to ApplicationPoolIdentity. Now, right-click the web application in the left pane, select **Edit Permissions**..., select the **Security** tab, click Edit -> Add and add `IIS APPPOOL\NameOfAppPool`. Make sure the Application Pool Identity has read and execute permissions of the folder. If you want to enable logging, check out this TechNet article: <http://technet.microsoft.com/en-us/library/cc754631(WS.10).aspx> There is a setting for the `anonymous user` to use the credentials of the `application pool identity` or a *specific user*. Sometimes, it is defaulted to a *specific user* and not `anonymous user` If this is the issue in your case, following settings will hopefully fix it: 1. IIS Manager → Sites → Website 2. Double click "Authentication" 3. Select Anonymous Authentication 4. From the Actions panel, select Edit 5. Select Application pool Identity and click ok
Solution: It is not the way you would like to solve ... But the way it worked was creating a new subdomain for my application.
24,845,969
I am trying to create a "find the odd word" application (given a list of words like cat, dog, bird and car, the latter is the odd one because it's not an animal). Firstly, I retrieve and shuffle randomly five words from the DB. They are called: odd (which is the odd one), one, two, three, four (which are the other four). Then, I produce a form (radio button) with the five words, so that users can select one of their choice: ``` $words = array ( $odd, $one, $two, $three, $four, ); shuffle($words); foreach ($words as $word) { $string = $word; echo '<html><input type="radio" name="odd" value="'.$string.'">'.$string.'<br><br></html>'; } ``` In the next PHP page, I want to check if the selected word is the odd one. I can't figure out how to do it. Any suggestions? Thanks!
2014/07/19
[ "https://Stackoverflow.com/questions/24845969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1726369/" ]
You need to carry the odd word to the next page somehow. There are many different ways of doing this, arguably the easiest one is by saving the odd word in a variable in your form ```html <input type="hidden" name="realodd" value="<?php print $odd; ?>" /> ``` On the next page, you can then check whether the chosen word is right by comparing it to the hidden word. ``` if ($_POST['realodd'] == $_POST['odd']) { print "You found the odd word."; } ``` This could easily be broken by just looking at the source code. A better solution could be saving the odd word in a session cookie: ``` session_start(); $_SESSION['realodd'] = $odd; ``` And then verify on the next page almost like before ``` if ($_SESSION['realodd'] == $_POST['odd']) { print "You found the odd word."; } ```
``` session_start(); if(isset($_POST['odd'])&& isset($_SESSION['odd'])&& $_POST['odd']==$_SESSION['odd']){ exit ("You're a genius, you got the right word"); }else{ if (isset($_POST['odd'])){ echo "Sorry, try again";} } //sql query goes here $words = array ( $odd, $one, $two, $three, $four, ); $_SESSION['odd'] = $odd; shuffle($words); echo '<form method="POST">'; foreach ($words as $word) { echo '<input type="radio" name="odd" value="$word"/>$word<br><br>'; } echo '<input type="submit" value="Submit"/>'; echo '</form>'; ```
24,845,969
I am trying to create a "find the odd word" application (given a list of words like cat, dog, bird and car, the latter is the odd one because it's not an animal). Firstly, I retrieve and shuffle randomly five words from the DB. They are called: odd (which is the odd one), one, two, three, four (which are the other four). Then, I produce a form (radio button) with the five words, so that users can select one of their choice: ``` $words = array ( $odd, $one, $two, $three, $four, ); shuffle($words); foreach ($words as $word) { $string = $word; echo '<html><input type="radio" name="odd" value="'.$string.'">'.$string.'<br><br></html>'; } ``` In the next PHP page, I want to check if the selected word is the odd one. I can't figure out how to do it. Any suggestions? Thanks!
2014/07/19
[ "https://Stackoverflow.com/questions/24845969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1726369/" ]
Use the $\_SESSION variable to handle this to find out if the odd was selected or not Say the following code is from your Odd.php that displays the radio buttons (assuming you would handle the form element and submit button) ``` <?php session_start(); $_SESSION['odd'] = $odd; $words = array ( $odd, $one, $two, $three, $four, ); shuffle($words); echo '<form method="POST" action="Next.php">'; foreach ($words as $word) { $string = $word; echo '<input type="radio" name="odd" value="'.$string.'">'.$string.'<br><br>'; } echo '<input type="submit" /></form>'; ?> ``` On your Next.php file use the code below to validate if the odd was selected or not ``` <?php session_start(); $odd = $_SESSION['odd']; if ($_REQUEST['odd'] == $odd) { // $_REQUEST handles both $_POST and $_GET echo "Odd was selected"; } else { echo "Odd was not selected"; } ?> ``` Hope this helps!
You need to carry the odd word to the next page somehow. There are many different ways of doing this, arguably the easiest one is by saving the odd word in a variable in your form ```html <input type="hidden" name="realodd" value="<?php print $odd; ?>" /> ``` On the next page, you can then check whether the chosen word is right by comparing it to the hidden word. ``` if ($_POST['realodd'] == $_POST['odd']) { print "You found the odd word."; } ``` This could easily be broken by just looking at the source code. A better solution could be saving the odd word in a session cookie: ``` session_start(); $_SESSION['realodd'] = $odd; ``` And then verify on the next page almost like before ``` if ($_SESSION['realodd'] == $_POST['odd']) { print "You found the odd word."; } ```
24,845,969
I am trying to create a "find the odd word" application (given a list of words like cat, dog, bird and car, the latter is the odd one because it's not an animal). Firstly, I retrieve and shuffle randomly five words from the DB. They are called: odd (which is the odd one), one, two, three, four (which are the other four). Then, I produce a form (radio button) with the five words, so that users can select one of their choice: ``` $words = array ( $odd, $one, $two, $three, $four, ); shuffle($words); foreach ($words as $word) { $string = $word; echo '<html><input type="radio" name="odd" value="'.$string.'">'.$string.'<br><br></html>'; } ``` In the next PHP page, I want to check if the selected word is the odd one. I can't figure out how to do it. Any suggestions? Thanks!
2014/07/19
[ "https://Stackoverflow.com/questions/24845969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1726369/" ]
Use the $\_SESSION variable to handle this to find out if the odd was selected or not Say the following code is from your Odd.php that displays the radio buttons (assuming you would handle the form element and submit button) ``` <?php session_start(); $_SESSION['odd'] = $odd; $words = array ( $odd, $one, $two, $three, $four, ); shuffle($words); echo '<form method="POST" action="Next.php">'; foreach ($words as $word) { $string = $word; echo '<input type="radio" name="odd" value="'.$string.'">'.$string.'<br><br>'; } echo '<input type="submit" /></form>'; ?> ``` On your Next.php file use the code below to validate if the odd was selected or not ``` <?php session_start(); $odd = $_SESSION['odd']; if ($_REQUEST['odd'] == $odd) { // $_REQUEST handles both $_POST and $_GET echo "Odd was selected"; } else { echo "Odd was not selected"; } ?> ``` Hope this helps!
``` session_start(); if(isset($_POST['odd'])&& isset($_SESSION['odd'])&& $_POST['odd']==$_SESSION['odd']){ exit ("You're a genius, you got the right word"); }else{ if (isset($_POST['odd'])){ echo "Sorry, try again";} } //sql query goes here $words = array ( $odd, $one, $two, $three, $four, ); $_SESSION['odd'] = $odd; shuffle($words); echo '<form method="POST">'; foreach ($words as $word) { echo '<input type="radio" name="odd" value="$word"/>$word<br><br>'; } echo '<input type="submit" value="Submit"/>'; echo '</form>'; ```
3,354,887
I just upgraded from Dojo 1.4.3 to 1.5.0 and noticed that my legend is now missing. Anyone else have this problem?? I keep receiving the following error: o is undefined in dojo.js line 73 This error occurs when chart1.render(); //Graph shows but error causes the rest of the code in that javascript function to not execute (So, not legend because it's created after chart1.render(); line. executes. Works perfect in release 1.4.3.
2010/07/28
[ "https://Stackoverflow.com/questions/3354887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/158787/" ]
If you're looking for flash-like interactivity in a web application, matplotlib probably isn't what you're looking for. It's fine for rendering a static image to serve out in a web app, though. (and is amazingly flexible) However, there's been a lot of recent development on making matplotlib more oriented toward web interactivity. Take a look at the new HTML5/Canvas backend. <http://code.google.com/p/mplh5canvas/> It's not quite finished yet, but it's worth playing around with, anyway.
I have never used `matplotlib`, but how about using **Google's Chart API** <http://code.google.com/intl/pl-PL/apis/chart/> for charts?
3,354,887
I just upgraded from Dojo 1.4.3 to 1.5.0 and noticed that my legend is now missing. Anyone else have this problem?? I keep receiving the following error: o is undefined in dojo.js line 73 This error occurs when chart1.render(); //Graph shows but error causes the rest of the code in that javascript function to not execute (So, not legend because it's created after chart1.render(); line. executes. Works perfect in release 1.4.3.
2010/07/28
[ "https://Stackoverflow.com/questions/3354887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/158787/" ]
I have never used `matplotlib`, but how about using **Google's Chart API** <http://code.google.com/intl/pl-PL/apis/chart/> for charts?
This tool is nice, but it would awesome if it worked with matplotlib. <http://www.highcharts.com/>
3,354,887
I just upgraded from Dojo 1.4.3 to 1.5.0 and noticed that my legend is now missing. Anyone else have this problem?? I keep receiving the following error: o is undefined in dojo.js line 73 This error occurs when chart1.render(); //Graph shows but error causes the rest of the code in that javascript function to not execute (So, not legend because it's created after chart1.render(); line. executes. Works perfect in release 1.4.3.
2010/07/28
[ "https://Stackoverflow.com/questions/3354887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/158787/" ]
You can use [MPLD3](https://mpld3.github.io/) to export your existing matplotlib stuff to browser. Matplotlib itself is very powerful, albeit, I agree the documentation is not very extensive. I've learned it just by trying stuff out and finding examples on the net. 'matplotlib example X' where X is somewhat about what you are trying to plot find suprising amount of code on the net.
I have never used `matplotlib`, but how about using **Google's Chart API** <http://code.google.com/intl/pl-PL/apis/chart/> for charts?
3,354,887
I just upgraded from Dojo 1.4.3 to 1.5.0 and noticed that my legend is now missing. Anyone else have this problem?? I keep receiving the following error: o is undefined in dojo.js line 73 This error occurs when chart1.render(); //Graph shows but error causes the rest of the code in that javascript function to not execute (So, not legend because it's created after chart1.render(); line. executes. Works perfect in release 1.4.3.
2010/07/28
[ "https://Stackoverflow.com/questions/3354887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/158787/" ]
If you're looking for flash-like interactivity in a web application, matplotlib probably isn't what you're looking for. It's fine for rendering a static image to serve out in a web app, though. (and is amazingly flexible) However, there's been a lot of recent development on making matplotlib more oriented toward web interactivity. Take a look at the new HTML5/Canvas backend. <http://code.google.com/p/mplh5canvas/> It's not quite finished yet, but it's worth playing around with, anyway.
This tool is nice, but it would awesome if it worked with matplotlib. <http://www.highcharts.com/>
3,354,887
I just upgraded from Dojo 1.4.3 to 1.5.0 and noticed that my legend is now missing. Anyone else have this problem?? I keep receiving the following error: o is undefined in dojo.js line 73 This error occurs when chart1.render(); //Graph shows but error causes the rest of the code in that javascript function to not execute (So, not legend because it's created after chart1.render(); line. executes. Works perfect in release 1.4.3.
2010/07/28
[ "https://Stackoverflow.com/questions/3354887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/158787/" ]
If you're looking for flash-like interactivity in a web application, matplotlib probably isn't what you're looking for. It's fine for rendering a static image to serve out in a web app, though. (and is amazingly flexible) However, there's been a lot of recent development on making matplotlib more oriented toward web interactivity. Take a look at the new HTML5/Canvas backend. <http://code.google.com/p/mplh5canvas/> It's not quite finished yet, but it's worth playing around with, anyway.
You can use [MPLD3](https://mpld3.github.io/) to export your existing matplotlib stuff to browser. Matplotlib itself is very powerful, albeit, I agree the documentation is not very extensive. I've learned it just by trying stuff out and finding examples on the net. 'matplotlib example X' where X is somewhat about what you are trying to plot find suprising amount of code on the net.
3,354,887
I just upgraded from Dojo 1.4.3 to 1.5.0 and noticed that my legend is now missing. Anyone else have this problem?? I keep receiving the following error: o is undefined in dojo.js line 73 This error occurs when chart1.render(); //Graph shows but error causes the rest of the code in that javascript function to not execute (So, not legend because it's created after chart1.render(); line. executes. Works perfect in release 1.4.3.
2010/07/28
[ "https://Stackoverflow.com/questions/3354887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/158787/" ]
If you're looking for flash-like interactivity in a web application, matplotlib probably isn't what you're looking for. It's fine for rendering a static image to serve out in a web app, though. (and is amazingly flexible) However, there's been a lot of recent development on making matplotlib more oriented toward web interactivity. Take a look at the new HTML5/Canvas backend. <http://code.google.com/p/mplh5canvas/> It's not quite finished yet, but it's worth playing around with, anyway.
Resurrecting an old question with the current state of affairs. As of Fall 2013, there's now an example of embedding matplotlib's WebAgg backend in a Tornado-based webserver: <https://github.com/matplotlib/matplotlib/blob/master/examples/user_interfaces/embedding_webagg.py> This makes use of websockets to send the figure updates to the browser, which allows for really nice interactive plots that get rendered client-side. This means that no images are being generated on the server!
3,354,887
I just upgraded from Dojo 1.4.3 to 1.5.0 and noticed that my legend is now missing. Anyone else have this problem?? I keep receiving the following error: o is undefined in dojo.js line 73 This error occurs when chart1.render(); //Graph shows but error causes the rest of the code in that javascript function to not execute (So, not legend because it's created after chart1.render(); line. executes. Works perfect in release 1.4.3.
2010/07/28
[ "https://Stackoverflow.com/questions/3354887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/158787/" ]
You can use [MPLD3](https://mpld3.github.io/) to export your existing matplotlib stuff to browser. Matplotlib itself is very powerful, albeit, I agree the documentation is not very extensive. I've learned it just by trying stuff out and finding examples on the net. 'matplotlib example X' where X is somewhat about what you are trying to plot find suprising amount of code on the net.
This tool is nice, but it would awesome if it worked with matplotlib. <http://www.highcharts.com/>
3,354,887
I just upgraded from Dojo 1.4.3 to 1.5.0 and noticed that my legend is now missing. Anyone else have this problem?? I keep receiving the following error: o is undefined in dojo.js line 73 This error occurs when chart1.render(); //Graph shows but error causes the rest of the code in that javascript function to not execute (So, not legend because it's created after chart1.render(); line. executes. Works perfect in release 1.4.3.
2010/07/28
[ "https://Stackoverflow.com/questions/3354887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/158787/" ]
Resurrecting an old question with the current state of affairs. As of Fall 2013, there's now an example of embedding matplotlib's WebAgg backend in a Tornado-based webserver: <https://github.com/matplotlib/matplotlib/blob/master/examples/user_interfaces/embedding_webagg.py> This makes use of websockets to send the figure updates to the browser, which allows for really nice interactive plots that get rendered client-side. This means that no images are being generated on the server!
This tool is nice, but it would awesome if it worked with matplotlib. <http://www.highcharts.com/>
3,354,887
I just upgraded from Dojo 1.4.3 to 1.5.0 and noticed that my legend is now missing. Anyone else have this problem?? I keep receiving the following error: o is undefined in dojo.js line 73 This error occurs when chart1.render(); //Graph shows but error causes the rest of the code in that javascript function to not execute (So, not legend because it's created after chart1.render(); line. executes. Works perfect in release 1.4.3.
2010/07/28
[ "https://Stackoverflow.com/questions/3354887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/158787/" ]
You can use [MPLD3](https://mpld3.github.io/) to export your existing matplotlib stuff to browser. Matplotlib itself is very powerful, albeit, I agree the documentation is not very extensive. I've learned it just by trying stuff out and finding examples on the net. 'matplotlib example X' where X is somewhat about what you are trying to plot find suprising amount of code on the net.
Resurrecting an old question with the current state of affairs. As of Fall 2013, there's now an example of embedding matplotlib's WebAgg backend in a Tornado-based webserver: <https://github.com/matplotlib/matplotlib/blob/master/examples/user_interfaces/embedding_webagg.py> This makes use of websockets to send the figure updates to the browser, which allows for really nice interactive plots that get rendered client-side. This means that no images are being generated on the server!
46,236
Apologies for the uninformative title, this is a relatively specific question so it was hard to title. I'm solving the following recurrence relation: > > $a\_{n} + a\_{n-1} - 6a\_{n-2} = 0$ > > With initial conditions $a\_{0} = 3$ > and $a\_{1} = 1$ > > > And I have it mostly figured out except for the very last part. My working: We have characteristic equation $s^2 + s - 6 = 0$ This factorises to $(s+3)(s-2)$ Hence we have roots $s=-3$ and $s=2$ and hence the **solution has the form $a\_{n} = -x3^n + y2^n$** We sub in the initial conditions: $a\_{0} = x + y = 3$ $a\_{1} = -3x+2y = 1$ And solving this system we have solutions: $x = 1$ and $y = 2$ Hence subbing this back to what we work out to be the general form of the solution: $a\_{n} = (-1)3^n + (2)2^n$ $a\_{n} = (-3)^n + (4)^n$ Correct? But it is incorrect, the correct solution is: $a\_{n} = (-3)^n + 2^{n+1}$ I don't understand where the $2^{n+1}$ came from. What am I missing here?
2011/06/19
[ "https://math.stackexchange.com/questions/46236", "https://math.stackexchange.com", "https://math.stackexchange.com/users/9046/" ]
You can't multiply expressions with exponents like that. $2\times (2^n)$ is equal to $2^{n+1}$, not $$4^n=\underbrace{4\times\cdots\times 4}\_{n\text{ times}}=\underbrace{(2\times 2)\times\cdots\times (2\times 2)}\_{n\text{ times}}=\underbrace{2\times\cdots\times 2}\_{2n\text{ times}}=2^{2n}.$$ Also, the general solution is $$a\_n=x(-3)^n+y2^n,$$ which is **not** the same as $-x3^n+y2^n$, which is what you wrote in the question. It so happens that since $x$ is 1, this discrepancy did not cause a problem, but you should be aware of the issue in general.
$(2)2^n$ is equal to $2^{n+1}$, not to $4^n$.
244,952
I have multiple java-based applications which produce statistics on how long method calls take. Right now the information is being written into a log file and I analyse performance that way. However with multiple apps and more monitoring requirements this is being becoming a bit overwhelming. I am looking for an application which will collect stats and graph them so I can analyse performance and be aware of performance degradation. I have looked at Solarwinds Application Performance Monitoring, however this polls periodically to gather information. My applications are totally event based and we would like to graph and track this accordingly. I almost started hacking together some scripts to produce Google Charts but surely there are applications which do this already. Suggestions?
2011/03/08
[ "https://serverfault.com/questions/244952", "https://serverfault.com", "https://serverfault.com/users/32417/" ]
For something simple, and since you're already collecting stats yourself, check out Perf4J. It might fit the bill perfectly. If you anticipate needing something more involved, consider publishing stats through JMX and monitoring with just JConsole or something like OpenNMS (I haven't tried this myself). See more here: <http://www.ibm.com/developerworks/java/library/j-jtp09196/index.html> If your monitoring needs extend outside a single server, for example if your apps are talking with DBs or web services, then an application-aware network performance monitor like ExtraHop is something to consider: <http://www.extrahop.com/products/>
I haven't seen a solution that does exactly that. However, if you have a look at up.time, from uptime software, you'll find that it has a number of deep application events monitors that might do the trick. Additionally, you can push data into up.time and leverage it's graphing functionality. There is a free 30-day trial, so it might be worth checking out if it sounds like a fit - <http://www.uptimesoftware.com>
244,952
I have multiple java-based applications which produce statistics on how long method calls take. Right now the information is being written into a log file and I analyse performance that way. However with multiple apps and more monitoring requirements this is being becoming a bit overwhelming. I am looking for an application which will collect stats and graph them so I can analyse performance and be aware of performance degradation. I have looked at Solarwinds Application Performance Monitoring, however this polls periodically to gather information. My applications are totally event based and we would like to graph and track this accordingly. I almost started hacking together some scripts to produce Google Charts but surely there are applications which do this already. Suggestions?
2011/03/08
[ "https://serverfault.com/questions/244952", "https://serverfault.com", "https://serverfault.com/users/32417/" ]
For something simple, and since you're already collecting stats yourself, check out Perf4J. It might fit the bill perfectly. If you anticipate needing something more involved, consider publishing stats through JMX and monitoring with just JConsole or something like OpenNMS (I haven't tried this myself). See more here: <http://www.ibm.com/developerworks/java/library/j-jtp09196/index.html> If your monitoring needs extend outside a single server, for example if your apps are talking with DBs or web services, then an application-aware network performance monitor like ExtraHop is something to consider: <http://www.extrahop.com/products/>
There's expensive tools like [DynaTrace](http://www.dynatrace.com)
244,952
I have multiple java-based applications which produce statistics on how long method calls take. Right now the information is being written into a log file and I analyse performance that way. However with multiple apps and more monitoring requirements this is being becoming a bit overwhelming. I am looking for an application which will collect stats and graph them so I can analyse performance and be aware of performance degradation. I have looked at Solarwinds Application Performance Monitoring, however this polls periodically to gather information. My applications are totally event based and we would like to graph and track this accordingly. I almost started hacking together some scripts to produce Google Charts but surely there are applications which do this already. Suggestions?
2011/03/08
[ "https://serverfault.com/questions/244952", "https://serverfault.com", "https://serverfault.com/users/32417/" ]
For something simple, and since you're already collecting stats yourself, check out Perf4J. It might fit the bill perfectly. If you anticipate needing something more involved, consider publishing stats through JMX and monitoring with just JConsole or something like OpenNMS (I haven't tried this myself). See more here: <http://www.ibm.com/developerworks/java/library/j-jtp09196/index.html> If your monitoring needs extend outside a single server, for example if your apps are talking with DBs or web services, then an application-aware network performance monitor like ExtraHop is something to consider: <http://www.extrahop.com/products/>
There is a free java performance troubleshooting product available for download at www.appdynamics.com/free It is designed to be installed and working in 15 minutes...to provide exactly what you are looking for. Give it a try. In 15 minutes, you'll know whether or not you found the right tool.
244,952
I have multiple java-based applications which produce statistics on how long method calls take. Right now the information is being written into a log file and I analyse performance that way. However with multiple apps and more monitoring requirements this is being becoming a bit overwhelming. I am looking for an application which will collect stats and graph them so I can analyse performance and be aware of performance degradation. I have looked at Solarwinds Application Performance Monitoring, however this polls periodically to gather information. My applications are totally event based and we would like to graph and track this accordingly. I almost started hacking together some scripts to produce Google Charts but surely there are applications which do this already. Suggestions?
2011/03/08
[ "https://serverfault.com/questions/244952", "https://serverfault.com", "https://serverfault.com/users/32417/" ]
For something simple, and since you're already collecting stats yourself, check out Perf4J. It might fit the bill perfectly. If you anticipate needing something more involved, consider publishing stats through JMX and monitoring with just JConsole or something like OpenNMS (I haven't tried this myself). See more here: <http://www.ibm.com/developerworks/java/library/j-jtp09196/index.html> If your monitoring needs extend outside a single server, for example if your apps are talking with DBs or web services, then an application-aware network performance monitor like ExtraHop is something to consider: <http://www.extrahop.com/products/>
Take a look at this option, <http://www.rtiperformance.com>. It can be used in both production and test. I was so impressed by the product I allowed my name and feedback to be used to promote the product.
49,649,046
I would like to unhide or not in `list3` the letter behind "\*" in `list2`, depending on whether or not the letter chosen is in `list1`. However, my list comprehension does not work. My code in Python 3: ``` list1 = [ "h", "e", "l", "l", "o"] list2 = ["h", "*", "*", "*", "o"] letter_chosen = input("Choose a letter: ") list3 = [letter_chosen for letter in list1 if letter_chosen == letter else letter2 for letter2 in list2] ``` In the Python interpreter if I enter "l" as `letter_chosen`, I would like to have: ``` list3 = ["h", "*", "l", "l", "o"] ``` Thank you for your help.
2018/04/04
[ "https://Stackoverflow.com/questions/49649046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9575916/" ]
It'll be easier if you started with writing out a normal loop. You want to do this: ``` for letter in list1: if letter_choosen == letter: letter # picked letter, so add it to the output else: # not the picked letter, use the value from letter2 at the same position ``` The easiest way to do get the values from list2 is to use `zip()`; this pairs up the values from the two lists: ``` for letter, letter2 in zip(list1, list2): if letter_choosen == letter: letter # picked letter, so add it to the output else: letter2 # not the picked letter, copy over the one from list2 ``` Note that the `if` tests what value to add, so it is part of the *expression*. You could use a conditional expression instead: ``` for letter, letter2 in zip(list1, list2): letter if letter_choosen == letter else letter2 ``` This then can be turned into a list comprehension: ``` [letter if letter_choosen == letter else letter2 for letter, letter2 in zip(list1, list2)] ``` or using more compact and comprehensible variable names: ``` goal = ["h", "e", "l", "l", "o"] display = ["h", "*", "*", "*", "o"] guess = input ("Choose a letter: ") new_display = [g if guess == g else d for g, d in zip(goal, display)] ```
Your syntax is invalid; you cannot loop on two lists at one time. Try using the [`zip`](https://docs.python.org/3/library/functions.html#zip) command: ``` >>> list(zip(list1, list2)) [('h', 'h'), ('e', '*'), ('l', '*'), ('l', '*'), ('o', 'o')] ``` It will pair together items from both lists. So, your expression becomes: ``` >>> list3 = [letter_choosen if letter_choosen == letter1 else letter2 for (letter1, letter2) in zip(list1, list2)] >>> list3 ['h', '*', 'l', 'l', 'o'] ```
49,649,046
I would like to unhide or not in `list3` the letter behind "\*" in `list2`, depending on whether or not the letter chosen is in `list1`. However, my list comprehension does not work. My code in Python 3: ``` list1 = [ "h", "e", "l", "l", "o"] list2 = ["h", "*", "*", "*", "o"] letter_chosen = input("Choose a letter: ") list3 = [letter_chosen for letter in list1 if letter_chosen == letter else letter2 for letter2 in list2] ``` In the Python interpreter if I enter "l" as `letter_chosen`, I would like to have: ``` list3 = ["h", "*", "l", "l", "o"] ``` Thank you for your help.
2018/04/04
[ "https://Stackoverflow.com/questions/49649046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9575916/" ]
Your syntax is invalid; you cannot loop on two lists at one time. Try using the [`zip`](https://docs.python.org/3/library/functions.html#zip) command: ``` >>> list(zip(list1, list2)) [('h', 'h'), ('e', '*'), ('l', '*'), ('l', '*'), ('o', 'o')] ``` It will pair together items from both lists. So, your expression becomes: ``` >>> list3 = [letter_choosen if letter_choosen == letter1 else letter2 for (letter1, letter2) in zip(list1, list2)] >>> list3 ['h', '*', 'l', 'l', 'o'] ```
You can do something like this: ``` [letter if letter_choosen != letter else '*' for letter in list1] ```
49,649,046
I would like to unhide or not in `list3` the letter behind "\*" in `list2`, depending on whether or not the letter chosen is in `list1`. However, my list comprehension does not work. My code in Python 3: ``` list1 = [ "h", "e", "l", "l", "o"] list2 = ["h", "*", "*", "*", "o"] letter_chosen = input("Choose a letter: ") list3 = [letter_chosen for letter in list1 if letter_chosen == letter else letter2 for letter2 in list2] ``` In the Python interpreter if I enter "l" as `letter_chosen`, I would like to have: ``` list3 = ["h", "*", "l", "l", "o"] ``` Thank you for your help.
2018/04/04
[ "https://Stackoverflow.com/questions/49649046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9575916/" ]
It'll be easier if you started with writing out a normal loop. You want to do this: ``` for letter in list1: if letter_choosen == letter: letter # picked letter, so add it to the output else: # not the picked letter, use the value from letter2 at the same position ``` The easiest way to do get the values from list2 is to use `zip()`; this pairs up the values from the two lists: ``` for letter, letter2 in zip(list1, list2): if letter_choosen == letter: letter # picked letter, so add it to the output else: letter2 # not the picked letter, copy over the one from list2 ``` Note that the `if` tests what value to add, so it is part of the *expression*. You could use a conditional expression instead: ``` for letter, letter2 in zip(list1, list2): letter if letter_choosen == letter else letter2 ``` This then can be turned into a list comprehension: ``` [letter if letter_choosen == letter else letter2 for letter, letter2 in zip(list1, list2)] ``` or using more compact and comprehensible variable names: ``` goal = ["h", "e", "l", "l", "o"] display = ["h", "*", "*", "*", "o"] guess = input ("Choose a letter: ") new_display = [g if guess == g else d for g, d in zip(goal, display)] ```
You can do something like this: ``` [letter if letter_choosen != letter else '*' for letter in list1] ```
55,098
My question relates to the lubrication of cylinder walls and piston rings. It is my understanding that pistons in cars consists of 3 rings; two compression rings and the oil/scraper ring. [![enter image description here](https://i.stack.imgur.com/uaKei.jpg)](https://i.stack.imgur.com/uaKei.jpg) As far as I've read, the cylinder walls are only lubricated by the jet of oil coming out of the connecting rod holes, and any excess oil is primarily scraped off the walls by the oil ring (consisting of 2 small rings and a center bent shape ring - correct?) If I'm correct on this, it seems intuitive to me that oil would never reach the compression rings as it is scraped by the oil ring sitting beneath it. How is the compression ring then lubricated and kept from scoring the walls?
2018/06/11
[ "https://mechanics.stackexchange.com/questions/55098", "https://mechanics.stackexchange.com", "https://mechanics.stackexchange.com/users/19769/" ]
manufactures of carburetor gas engines such as honda, brigs and straton ,preditor do not recomend using alchol gas in any of their products as it will void the warranty also kawasaki and other carbed engines do the same..unless your fuel system is setup to use straight alcohol...most all older carbs and many new carbs wont tollerate it...ive seen it many times
I run 100% alcohol and it does not gel or change colors, looks to me like bad/cheap gas. I would clean the system and try a different source for your fuel.
53,252,347
I have found that the [graphql-js](https://github.com/graphql/graphql-js) library does not allow dependencies to also use graphql. You would get the following error `Duplicate "graphql" modules cannot be used at the same time since different versions may have different capabilities and behavior. The data from one version used in the function from another could produce confusing and spurious results.` from the following code ``` const express = require('express'); const graphqlHTTP = require('express-graphql'); const { GraphQLSchema } = require('graphql'); // the module graphql-test-mod-obj-type' has // graphql as a depenedency const myType = require('graphql-test-mod-obj-type'); const app = express(); const schema = new GraphQLSchema({ query: myType }) app.use('/graphql', graphqlHTTP({ schema, graphiql: true })); app.listen(4000); ``` I created a small repo and a small public npm package to demonstrate this [repo-with-npm-dependency-on-graphql](https://github.com/ghinks/graphql-test-consume-graphql-obj-type.git) . This can be quite easily worked around by not having the graphql module as a dependency in the module. But surely this is an issue? Or is this a well known thing?
2018/11/11
[ "https://Stackoverflow.com/questions/53252347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4891711/" ]
it does appear that this is a longstanding and known issue and is covered [here](https://github.com/graphql/graphql-js/issues/491)
If you are using Yarn instead of NPM, first thing I would advise trying is switching to NPM since there is apparently a specific issue between the GraphQL package and how Yarn resolves dependencies. See the Github issues: - [162](https://github.com/prisma-labs/graphql-yoga/issues/162) - [1928](https://github.com/prisma/prisma/issues/1928#issuecomment-366480975)
53,252,347
I have found that the [graphql-js](https://github.com/graphql/graphql-js) library does not allow dependencies to also use graphql. You would get the following error `Duplicate "graphql" modules cannot be used at the same time since different versions may have different capabilities and behavior. The data from one version used in the function from another could produce confusing and spurious results.` from the following code ``` const express = require('express'); const graphqlHTTP = require('express-graphql'); const { GraphQLSchema } = require('graphql'); // the module graphql-test-mod-obj-type' has // graphql as a depenedency const myType = require('graphql-test-mod-obj-type'); const app = express(); const schema = new GraphQLSchema({ query: myType }) app.use('/graphql', graphqlHTTP({ schema, graphiql: true })); app.listen(4000); ``` I created a small repo and a small public npm package to demonstrate this [repo-with-npm-dependency-on-graphql](https://github.com/ghinks/graphql-test-consume-graphql-obj-type.git) . This can be quite easily worked around by not having the graphql module as a dependency in the module. But surely this is an issue? Or is this a well known thing?
2018/11/11
[ "https://Stackoverflow.com/questions/53252347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4891711/" ]
I had this error in a Strapi project and could solve it with the following commands: ``` yarn cache clean rm -rf node_modules ``` added in package.json the "resolutions" section. See below: ``` { "name": "lighthouse-strapi", "private": true, "version": "0.1.0", "description": "A Strapi application", "scripts": { "develop": "strapi develop", "start": "strapi start", "build": "strapi build", "strapi": "strapi", "generate-api-doc": "node docs/MD_TOC.js README.md README_toc.md" }, "devDependencies": {}, "dependencies": { "@sendgrid/mail": "^7.5.0", "graphql": "^15.6.1", "highlight.js": "^10.7.3", "knex": "0.21.18", "kuzzle-sdk": "^7.7.6", "md-to-pdf": "^5.0.0", "mysql": "2.18.1", "pg": "^8.7.1", "pg-connection-string": "^2.5.0", "strapi": "3.6.8", "strapi-admin": "3.6.8", "strapi-connector-bookshelf": "3.6.8", "strapi-plugin-content-manager": "3.6.8", "strapi-plugin-content-type-builder": "3.6.8", "strapi-plugin-email": "3.6.8", "strapi-plugin-graphql": "3.6.8", "strapi-plugin-i18n": "3.6.8", "strapi-plugin-upload": "3.6.8", "strapi-plugin-users-permissions": "3.6.8", "strapi-provider-upload-cloudinary": "^3.6.8", "strapi-utils": "3.6.8" }, "resolutions": { "graphql": "^15.6.1", "**/graphql": "^15.6.1" }, "author": { "name": "A Strapi developer" }, "strapi": { "uuid": "c192f5ec-e7d1-4747-80d2-24b725ff9b0e" }, "engines": { "node": ">=10.16.0 <=14.x.x", "npm": "^6.0.0" }, "license": "MIT" } ``` And finally: ``` yarn install ```
If you are using Yarn instead of NPM, first thing I would advise trying is switching to NPM since there is apparently a specific issue between the GraphQL package and how Yarn resolves dependencies. See the Github issues: - [162](https://github.com/prisma-labs/graphql-yoga/issues/162) - [1928](https://github.com/prisma/prisma/issues/1928#issuecomment-366480975)
53,252,347
I have found that the [graphql-js](https://github.com/graphql/graphql-js) library does not allow dependencies to also use graphql. You would get the following error `Duplicate "graphql" modules cannot be used at the same time since different versions may have different capabilities and behavior. The data from one version used in the function from another could produce confusing and spurious results.` from the following code ``` const express = require('express'); const graphqlHTTP = require('express-graphql'); const { GraphQLSchema } = require('graphql'); // the module graphql-test-mod-obj-type' has // graphql as a depenedency const myType = require('graphql-test-mod-obj-type'); const app = express(); const schema = new GraphQLSchema({ query: myType }) app.use('/graphql', graphqlHTTP({ schema, graphiql: true })); app.listen(4000); ``` I created a small repo and a small public npm package to demonstrate this [repo-with-npm-dependency-on-graphql](https://github.com/ghinks/graphql-test-consume-graphql-obj-type.git) . This can be quite easily worked around by not having the graphql module as a dependency in the module. But surely this is an issue? Or is this a well known thing?
2018/11/11
[ "https://Stackoverflow.com/questions/53252347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4891711/" ]
I encountered this error and resolved it using the following steps: 1. list all available instances of graphql package to check for dependences npm ls graphql 2. remove node\_modules directory rm -rf node\_modules 3. delete package-lock.json file 4. add "resolutions" object to package.json "resolutions": { "graphql": "15.5.0", "\*\*/graphql": "15.5.0" } 5. Add preinstall script to enforce resolutions options to scripts object in package.json file "preinstall": "npx npm-force-resolutions" 6. install packages again npm install \*\* NOTE\*\*\* In my case I also had to change the node version from v18.0 to v17.0 because of some other the apollo/federation package I was using so may be also look at the node dependencies
If you are using Yarn instead of NPM, first thing I would advise trying is switching to NPM since there is apparently a specific issue between the GraphQL package and how Yarn resolves dependencies. See the Github issues: - [162](https://github.com/prisma-labs/graphql-yoga/issues/162) - [1928](https://github.com/prisma/prisma/issues/1928#issuecomment-366480975)
286
Matthew 8:21-23 says > > And another of his disciples said unto him, Lord, suffer me first to go and bury my father. But Jesus said unto him, **"Follow me; and let the dead bury their dead."** > And when he was entered into a ship, his disciples followed him. (KJV) > > > What is the meaning of the dead burying their dead?
2011/08/24
[ "https://christianity.stackexchange.com/questions/286", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/140/" ]
To me, this is a very offensive direction that Jesus gives. And that isn't a bad thing -- frequently the Bible gives directions that are offensive to what we are accustomed to believing. We should always take them seriously. In this case, I think the message is that we must put following Christ above everything, even our most important worldly concerns. In Hebrew culture, it is a son's duty to bury his father -- an important duty -- but Jesus is telling him to forget about that, to put following him first. The options are "bury your father, and get around to following me in a bit" or "follow me". As far as Jesus is concerned, there's only one choice. It's quite similar to [Matthew 19:29](http://bible.oremus.org/?ql=181187275): > > And everyone who has left houses or brothers or sisters or father or mother or children or fields, for my name’s sake, will receive a hundredfold, and will inherit eternal life. > > > As to the specific wording, I would suggest that "follow me" is contrasted to death. So following Jesus is life, tarrying about with worldly duties is death. So the dead in spirit are left to bury the dead in body: the living are following Jesus along the way.
The purpose of His response may have been two fold. The first purpose was to encourage the disciples to faithfully follow Him. The second purpose and perhaps more importantly, was to teach correct theology. **First-Century Jewish Burial Practices** After a body was placed in a burial cave, it was left to decompose. The family mourned for seven days. This initial mourning period was followed by a less intense 30-day period of mourning, called shloshim. However, the entire mourning period was not fully over until the flesh of the deceased had decomposed, usually about a year later. The Jerusalem Talmud states: When the flesh had wasted away, the bones were collected and placed in chests (ossuaries). On that day (the son) mourned, but the following day he was glad, because his forebears rested from judgment. The final act of mourning, the gathering of the bones into a bone box called an ossuary, was called ossilegium, or secondary burial. According to the Rabbinic sources, the decomposition of the flesh atoned for the sins of the dead person (a kind of purgatory) and the final stage of this process was gathering the bones and placing them in an ossuary (Meyers 1971: 80-85). Jesus confronts this contrary theology. Only faith in Christ's redemptive work on the cross can atone for sin, not rotting flesh or any other work or merit of our own (Heb. 9:22, 26; Acts 4:12; Eph. 2:8, 9). Jesus may have rebuked the disciple rather harshly because they were following the corrupted practice of secondary burial. **The setting of the saying:** The Gospels record two incidents where disciples approached the Lord to request a leave of absence from following Him. The first request is recorded in Matthew 8. Jesus was about to take the Twelve across the Sea of Galilee to the Decapolis city of Gadara. Chronologically, this trip is the first recorded journey of Jesus to minister in Gentile territory. Maybe the disciple hesitated, probably because he did not want to go to those Gentiles so he made an excuse: Let me first go and bury my father. He most likely appealed to the Jewish burial practice of ossilegium, or secondary burial, which would remove him from following the Lord for up to eleven months. Jesus saw this as an excuse not to minister to the Gentiles. As a result He rebuked him with a statement of irony and challenged the disciple to follow Him. I got most of the information from [LET THE DEAD BURY THEIR OWN DEAD.](http://www.ldolphin.org/deaddead.html)
286
Matthew 8:21-23 says > > And another of his disciples said unto him, Lord, suffer me first to go and bury my father. But Jesus said unto him, **"Follow me; and let the dead bury their dead."** > And when he was entered into a ship, his disciples followed him. (KJV) > > > What is the meaning of the dead burying their dead?
2011/08/24
[ "https://christianity.stackexchange.com/questions/286", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/140/" ]
To me, this is a very offensive direction that Jesus gives. And that isn't a bad thing -- frequently the Bible gives directions that are offensive to what we are accustomed to believing. We should always take them seriously. In this case, I think the message is that we must put following Christ above everything, even our most important worldly concerns. In Hebrew culture, it is a son's duty to bury his father -- an important duty -- but Jesus is telling him to forget about that, to put following him first. The options are "bury your father, and get around to following me in a bit" or "follow me". As far as Jesus is concerned, there's only one choice. It's quite similar to [Matthew 19:29](http://bible.oremus.org/?ql=181187275): > > And everyone who has left houses or brothers or sisters or father or mother or children or fields, for my name’s sake, will receive a hundredfold, and will inherit eternal life. > > > As to the specific wording, I would suggest that "follow me" is contrasted to death. So following Jesus is life, tarrying about with worldly duties is death. So the dead in spirit are left to bury the dead in body: the living are following Jesus along the way.
I think Jesus' answer can be taken on two levels. On the first level he was helping the individual who asked him to let him bury his dead. Jesus' response to him was that he could have little impact on the person that was already dead and should rather focus his efforts on helping to spread the Gospel that would impact the living before their death and subsequent judgement. Paul clarified the reason for focusing on the living when he said to the Hebrews in Hebrews 9:27 "And as it is appointed unto men once to die, but after this the judgment". The second level comes in a prophetic form. Jesus did not waste opportunity to teach us and I think he knew that in future times there would come those who would teach false doctrines spending endless hours doing meaningless ordinances such as baptism for the dead as if the dead could change their outcome by repentance after death. How much more clearly could it be said since baptism represents burial. Therefore baptism or burial with Christ was a decision for this life only and would have as little effect on the salvation of the soul of that person as the burial of their bones would ultimately affect their Eternal outcome.
286
Matthew 8:21-23 says > > And another of his disciples said unto him, Lord, suffer me first to go and bury my father. But Jesus said unto him, **"Follow me; and let the dead bury their dead."** > And when he was entered into a ship, his disciples followed him. (KJV) > > > What is the meaning of the dead burying their dead?
2011/08/24
[ "https://christianity.stackexchange.com/questions/286", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/140/" ]
To me, this is a very offensive direction that Jesus gives. And that isn't a bad thing -- frequently the Bible gives directions that are offensive to what we are accustomed to believing. We should always take them seriously. In this case, I think the message is that we must put following Christ above everything, even our most important worldly concerns. In Hebrew culture, it is a son's duty to bury his father -- an important duty -- but Jesus is telling him to forget about that, to put following him first. The options are "bury your father, and get around to following me in a bit" or "follow me". As far as Jesus is concerned, there's only one choice. It's quite similar to [Matthew 19:29](http://bible.oremus.org/?ql=181187275): > > And everyone who has left houses or brothers or sisters or father or mother or children or fields, for my name’s sake, will receive a hundredfold, and will inherit eternal life. > > > As to the specific wording, I would suggest that "follow me" is contrasted to death. So following Jesus is life, tarrying about with worldly duties is death. So the dead in spirit are left to bury the dead in body: the living are following Jesus along the way.
It is an Aramaic colloquialism, and means that the son would take care of his aging father until he dies(or other relative), which might take many years. So the would-be disciple could not follow Jesus. see: *Idioms in the Bible Explained and A Key to the Original Gospels* by George M. Lamsa HarperSanFrancisco (1985) As an example from the book: *21 And another of his disciples said unto him, Lord, suffer me first to go and bury my father.* meant“take care of my father until he dies.” Jesus suggested that those not believing in Christ (the spiritually dead) should take care of the aging parent. For more examples of Aramaic Idiom download my PDF <http://www.waeshael.com/Christianity/Waking_Jesus/Entries/2007/1/21_Aramaic_Idiom_in_the_NT_files/AramaicIdiomNT.pdf>
286
Matthew 8:21-23 says > > And another of his disciples said unto him, Lord, suffer me first to go and bury my father. But Jesus said unto him, **"Follow me; and let the dead bury their dead."** > And when he was entered into a ship, his disciples followed him. (KJV) > > > What is the meaning of the dead burying their dead?
2011/08/24
[ "https://christianity.stackexchange.com/questions/286", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/140/" ]
The purpose of His response may have been two fold. The first purpose was to encourage the disciples to faithfully follow Him. The second purpose and perhaps more importantly, was to teach correct theology. **First-Century Jewish Burial Practices** After a body was placed in a burial cave, it was left to decompose. The family mourned for seven days. This initial mourning period was followed by a less intense 30-day period of mourning, called shloshim. However, the entire mourning period was not fully over until the flesh of the deceased had decomposed, usually about a year later. The Jerusalem Talmud states: When the flesh had wasted away, the bones were collected and placed in chests (ossuaries). On that day (the son) mourned, but the following day he was glad, because his forebears rested from judgment. The final act of mourning, the gathering of the bones into a bone box called an ossuary, was called ossilegium, or secondary burial. According to the Rabbinic sources, the decomposition of the flesh atoned for the sins of the dead person (a kind of purgatory) and the final stage of this process was gathering the bones and placing them in an ossuary (Meyers 1971: 80-85). Jesus confronts this contrary theology. Only faith in Christ's redemptive work on the cross can atone for sin, not rotting flesh or any other work or merit of our own (Heb. 9:22, 26; Acts 4:12; Eph. 2:8, 9). Jesus may have rebuked the disciple rather harshly because they were following the corrupted practice of secondary burial. **The setting of the saying:** The Gospels record two incidents where disciples approached the Lord to request a leave of absence from following Him. The first request is recorded in Matthew 8. Jesus was about to take the Twelve across the Sea of Galilee to the Decapolis city of Gadara. Chronologically, this trip is the first recorded journey of Jesus to minister in Gentile territory. Maybe the disciple hesitated, probably because he did not want to go to those Gentiles so he made an excuse: Let me first go and bury my father. He most likely appealed to the Jewish burial practice of ossilegium, or secondary burial, which would remove him from following the Lord for up to eleven months. Jesus saw this as an excuse not to minister to the Gentiles. As a result He rebuked him with a statement of irony and challenged the disciple to follow Him. I got most of the information from [LET THE DEAD BURY THEIR OWN DEAD.](http://www.ldolphin.org/deaddead.html)
It is an Aramaic colloquialism, and means that the son would take care of his aging father until he dies(or other relative), which might take many years. So the would-be disciple could not follow Jesus. see: *Idioms in the Bible Explained and A Key to the Original Gospels* by George M. Lamsa HarperSanFrancisco (1985) As an example from the book: *21 And another of his disciples said unto him, Lord, suffer me first to go and bury my father.* meant“take care of my father until he dies.” Jesus suggested that those not believing in Christ (the spiritually dead) should take care of the aging parent. For more examples of Aramaic Idiom download my PDF <http://www.waeshael.com/Christianity/Waking_Jesus/Entries/2007/1/21_Aramaic_Idiom_in_the_NT_files/AramaicIdiomNT.pdf>
286
Matthew 8:21-23 says > > And another of his disciples said unto him, Lord, suffer me first to go and bury my father. But Jesus said unto him, **"Follow me; and let the dead bury their dead."** > And when he was entered into a ship, his disciples followed him. (KJV) > > > What is the meaning of the dead burying their dead?
2011/08/24
[ "https://christianity.stackexchange.com/questions/286", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/140/" ]
I think Jesus' answer can be taken on two levels. On the first level he was helping the individual who asked him to let him bury his dead. Jesus' response to him was that he could have little impact on the person that was already dead and should rather focus his efforts on helping to spread the Gospel that would impact the living before their death and subsequent judgement. Paul clarified the reason for focusing on the living when he said to the Hebrews in Hebrews 9:27 "And as it is appointed unto men once to die, but after this the judgment". The second level comes in a prophetic form. Jesus did not waste opportunity to teach us and I think he knew that in future times there would come those who would teach false doctrines spending endless hours doing meaningless ordinances such as baptism for the dead as if the dead could change their outcome by repentance after death. How much more clearly could it be said since baptism represents burial. Therefore baptism or burial with Christ was a decision for this life only and would have as little effect on the salvation of the soul of that person as the burial of their bones would ultimately affect their Eternal outcome.
It is an Aramaic colloquialism, and means that the son would take care of his aging father until he dies(or other relative), which might take many years. So the would-be disciple could not follow Jesus. see: *Idioms in the Bible Explained and A Key to the Original Gospels* by George M. Lamsa HarperSanFrancisco (1985) As an example from the book: *21 And another of his disciples said unto him, Lord, suffer me first to go and bury my father.* meant“take care of my father until he dies.” Jesus suggested that those not believing in Christ (the spiritually dead) should take care of the aging parent. For more examples of Aramaic Idiom download my PDF <http://www.waeshael.com/Christianity/Waking_Jesus/Entries/2007/1/21_Aramaic_Idiom_in_the_NT_files/AramaicIdiomNT.pdf>
51,274,370
``` import React from "react"; import styles from "../articles.css"; const TeamInfo = props => ( <div className={styles.articleTeamHeader}> <div className={styles.left}> style={{ background: `url('/images/teams/${props.team.logo}')` }} </div> <div className={styles.right}> <div> <span> {props.team.city} {props.team.name} </span> </div> <div> <strong> W{props.team.stats[0].wins}-L{props.team.stats[0].defeats} </strong> </div> </div> </div> ); export default TeamInfo; ``` the code that render this ``` import React from 'react'; import TeamInfo from '../../Elements/TeamInfo'; const header = (props) => { const teaminfofunc = (team) => { return team ? ( <TeamInfo team={team}/> ) : null } return ( <div> {teaminfofunc(props.teamdata)} </div> ) } export default header; ``` and I am getting error TypeError: props is undefined in line 8 why is that ? Line 8 is > > background: `url('/images/teams/${props.team.logo}')` > > > **Update**: I found that in index.js the `componentWillMount` bring the data correctly but in the `render()` those data (article and team) was not passed to render, any idea why ? ``` import React, {Component} from 'react'; import axios from 'axios'; import {URL} from "../../../../config"; import styles from '../../articles.css'; import Header from './header'; import Body from './body'; class NewsArticles extends Component { state = { article:[], team: [] } componentWillMount() { axios.get(`${URL}/articles?id=${this.props.match.params.id}`) .then(response => { let article = response.data[0]; axios.get(`${URL}/teams?id=${article.team}`) .then(response => { this.props.setState({ article, team:response.data }) }) }) } render() { const article = this.state.article; const team = this.state.team; return ( <div className={styles.articleWrapper}> <Header teamdata={team[0]} date={article.date} author={article.author} /> <Body /> </div> ) } } export default NewsArticles; ```
2018/07/10
[ "https://Stackoverflow.com/questions/51274370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/283322/" ]
You should always gate any object traversal in case the component renders without the data. ``` {props && props.team && props.team.logo ? <div className={styles.left}> style={{ background: `url('/images/teams/${props.team.logo}')` }} </div> : null} ``` This may not be you exact issue, but without knowing how the prop is rendered that is all we can do from this side of the code. --- Update based on your edit. You can't be sure that props.teamdata exists, and therefore your component will be rendered without this data. You'll need to gate this side also, and you don't need to seperate it as a function, also. Here is an example of what it could look like: ``` import React from 'react'; import TeamInfo from '../../Elements/TeamInfo'; const header = (props) => ( <div> {props.teamdata ? <TeamInfo team={props.teamdata}/> : null} </div> ) export default header; ```
First -- while this is stylistic -- it's not good practice to pass `props` directly to your functional component. Do this instead. ``` const TeamInfo = ({team}) => ( <div className={styles.articleTeamHeader}> <div className={styles.left}> style={{ background: `url('/images/teams/${team.logo}')` }} </div> <div className={styles.right}> <div> <span> {team.city} {team.name} </span> </div> <div> <strong> W{team.stats[0].wins}-L{team.stats[0].defeats} </strong> </div> </div> </div> ); ``` Second, you might just want to do some kind of `null` check. If `team` is `undefined` the first time the component tries to render, you might just want to render `null` so you're not wasting cycles. In case this isn't the issue, you'd learn a lot by `console.log`-ing your props so you know what everything is each time your component tries to render. It's okay if data is `undefined` if you're in a state that will soon resolve.