text
stringlengths
64
89.7k
meta
dict
Q: Intellij does not recognize Scala List operator Here is the intellij warning : When overing "::" Intellij display this message : Cannot resolve symbol :: I have scala + sbt plugins correctly installed. How can i fix this error ? A: Your code is incorrect : :: is a method on List, not on Integer. Your last element must be an instance of List. Either of those will work : val otherList = 3::2::List(3) or val otherList = 3::2::3::Nil Note that :: is called on List and not the Integer because it is right-associative. From the Scala Specification (Infix Operations, 6.12.3) : The associativity of an operator is determined by the operator’s last character. Operators ending in a colon ‘:’ are right-associative. All other operators are left-associative.
{ "pile_set_name": "StackExchange" }
Q: Manually Advancing Orbit Slider I'm using the Zurb 'Orbit' Javascript slider, http://www.zurb.com/playground/orbit-jquery-image-slider, and I'd like to fire my own javascript at it to manually advance the slider left or right. Basically, I'd like to fill it with my content, then have that content 'slide' in an out of view depending on a user interactions with the page as a whole, not only on a timer function or clicking a navigational image as already provided by the library. So if I have a link named 'myLink', then something like this... $('#myLink').click(function() { ... code to advance javascript slider... $('#content').orbit(?????); }); Failing that, my 'content' is going to be an html form and other similar stuff, anyone know a good free library that already does what I want? A: Get a reference to the orbit object using "afterLoadComplete": var myOrbit; $(".orbitSlides").orbit({ afterLoadComplete: function() { myOrbit = this; } }); Then use the 'shift' function to change slides: myOrbit.shift(1); or myOrbit.shift('prev'); or myOrbit.shift('next'); A: The easiest way would be $(".slider-nav .right").click(); to simulate the arrow being clicked. Change if necessary to account for using the bullet-navigation option. I don't think you're going to get anything more elegant than that, because the plugin doesn't expose an API of any sort - it's all privately closured up in the plugin.
{ "pile_set_name": "StackExchange" }
Q: ITextSharp: parse html with cyrillic/international words I try to parse html file and to generate pdf. I use code document.Open(); HtmlPipelineContext htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true); IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer))); XMLWorker worker = new XMLWorker(pipeline, true); XMLParser p = new XMLParser(true, worker, Encoding.Unicode); p.Parse((TextReader)File.OpenText(@"Template.html")); document.Close(); How can I define base font, If i'd like use cyrillic/international words? A: You should register font string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF"); FontFactory.Register(arialuniTff); and modifed page's body <body face='Arial' encoding='koi8-r' > ... </body > For somebody, who can read in russian, this article can be useful
{ "pile_set_name": "StackExchange" }
Q: Exclude items from a model - MVC/ASP.Net This is a follow up question to this post I have two models: CarType.cs // // Holds types of car - this has a one to many relationship with Car class // [Table("tType")] public class CarType { [Key] public int type_id { get; set; } public int dealer_id { get; set; } public string type_name { get; set; } public string type_desc { get; set; } public virtual ICollection<Car> Cars { get; set; } } Car.cs // // Holds actual Cars // [Table("tCar")] public class Car { [Key] public int car_id { get; set; } public int dealer_id { get; set; } public int type_id { get; set; } public int car_order { get; set; } public string car_name { get; set; } public virtual ICollection<Rental> Rentals { get; set; } public virtual CarType CarType { get; set; } } I want to have a view model, where I can view car types, and how many of each car type I have within each Car Type class, so I've created a ViewModel: public class SearchViewModel { [Required] public DateTime From { get; set; } public int Nights { get; set; } public int dealer_id { get; set; } public IQueryable<CarType> CarTypes { get; set; } // CarTypes as above, has a one to many relationship with the class Car } Given a predeterminded list of actual cars (say preBookedCars), I want to remove the list of cars from the ViewObject so for example, if the model of CarType (including the one 2 many Cars) looked like this: Mercedes (count = 3) ....Car 1 ....Car 2 ....Car 3 Ford (count = 3) ....Car 4 ....Car 5 ....Car 6 Citroen (count = 3) ....Car 7 ....Car 8 ....Car 9 Given a list of CARS, how would I EXCLUDE the list of cars from the CarType model - eg. I have a list of: Car 1, Car 4, Car 8, Car 9 - so I would like the above model to show: Mercedes (count = 2) ....Car 2 ....Car 3 Ford (count = 2) ....Car 5 ....Car 6 Citroen (count = 1) ....Car 7 I know it's something along the lines of (pseudo LINQ): var freeCars = (db context).CarTypes .Cars .Except(preBookedCars) Thank you for any help, Mark A: I'm not sure if this is what you're looking for, but if you're just trying to filter against the Cars collection in the CarType object, you can use something like this: var preBookedCars = new List<int> { 1, 5, 9 }; var myCarType = new CarType(); var filteredCars = myCarType.Cars.Where(c => !preBookedCars.Contains(c.car_id)); This code can be adapted to be used where ever you need.
{ "pile_set_name": "StackExchange" }
Q: How to mapp an array to a complex type using Dozer I am using Dozer to map some beans, and I have a mapping that I can't figure out. Here are my classes: class A{ private ComplexeType type; //Constructors & getters } class B{ private String[] type; //Constructors & getters } class ComplexteType{ private List<String> list; //Getter for the list, no constructor } How do I map class A to class B? I want to map the field type of class A to the field type of the class B using xml. here is the xml file: <mapping> <class-a>A</class-a> <class-b>B</class-b> <field custom-converter="AToBCustomConverter"> <a>type</a> <b>type</b> </field> </mapping> And here is a sippet from my CustomConverter if (source == null) { return null; } B dest = null; if (source instanceof java.lang.String) { // check to see if the object already exists if (destination == null) { dest = new A(); } else { dest = (A) destination; } dest.getTypes().add((String) source); return dest; } else if (source instanceof B) { String[] sourceObj = ((B) destination) .getType() .toArray( new String[((B) destination) .getType().size()]); return sourceObj; } else { throw new MappingException( "Converter StatResultCustomConverter used incorrectly. Arguments passed in were:" + destination + " and " + source); } } A: Here is the mapping I used to solve the problem. <mapping> <class-a>Q</class-a> <class-b>B</class-b> <field> <a is-accessible="true">type<list</a> <b is-accessible="true">type</b> </field> </mapping>
{ "pile_set_name": "StackExchange" }
Q: Web page moves horizonatally in the Iphone 7 I see that the website home page horizontally moves when a user scrolls the page. Below is the URL: https://tandcity.dk/da/ I have tried the below CSS body{ overflow: hidden; } html{ overflow: hidden; } I added some meta tags. You can check on view source. Can someone please help me to fix this. A: Remove this from body tag: body { /* overflow: hidden; */ /* width: 100vw; */ /* height: 100vh; */ } For Mobile: On this class .vc_grid.vc_row.vc_grid-gutter-15px .vc_pageable-slide-wrapper remove margin-right: -15px replace with margin-right: 0px if you want to. Afrter that replace .vc_grid.vc_row.vc_grid-gutter-15px .vc_grid-item , padding-right: 15px; with padding-right: 0px; Remember for this mobile chages to take affect you have to add it within an @media query. Example: Where you add the custom css, add this before the closing tag @media (max-width: 480px) { .vc_grid.vc_row.vc_grid-gutter-15px .vc_pageable-slide-wrapper { margin-right: 0px; } .vc_grid.vc_row.vc_grid-gutter-15px .vc_grid-item { padding-right: 0px; } } For iphone 7 : /* Portrait and Landscape */ @media only screen and (min-device-width: 414px) and (max-device-width: 736px) and (-webkit-min-device-pixel-ratio: 3) { .vc_grid.vc_row.vc_grid-gutter-15px .vc_pageable-slide-wrapper { margin-right: 0px; } .vc_grid.vc_row.vc_grid-gutter-15px .vc_grid-item { padding-right: 0px; } }
{ "pile_set_name": "StackExchange" }
Q: I use the following code to capture image from camera. But I cant record the video by this CameraCaptureUI capture = new CameraCaptureUI(); capture.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg; capture.PhotoSettings.CroppedAspectRatio = new Size(1, 2); capture.PhotoSettings.MaxResolution=CameraCaptureUIMaxPhotoResolution.HighestAvailable StorageFile storeFile=await capture.CaptureFileAsync(CameraCaptureUIMode.Photo); if (storeFile != null) { var stream = await storeFile.OpenAsync(FileAccessMode.Read); BitmapImage bimage = new BitmapImage(); bimage.SetSource(stream); Image imageitem = new Image(); imageitem.Source = bimage; my_canvas.Children.Add(imageitem); A: Just use standard sample for recording video from Capture photos and video with CameraCaptureUI CameraCaptureUI captureUI = new CameraCaptureUI(); captureUI.VideoSettings.Format = CameraCaptureUIVideoFormat.Mp4; StorageFile videoFile = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Video); if (videoFile == null) { // User cancelled photo capture return; }
{ "pile_set_name": "StackExchange" }
Q: DatePicker configuration swift sorry for my english and question! I´m using xCode 6 with swift I´m trying to develop my own app, and i don´t know how to ask the user to set a date, so i can use that value on other side :S i don´t care if it uses a DatePicker with scroll or other way, just need that the user can set any date. I can´t guess how the datePicker works :S I found this code inside a course that develops "Tinder", when it asks for your date of birth in the login, i adapt it to my app, but it doesnt work, and i dont know why :S import UIKit class SignUpController: UIViewController, UITextFieldDelegate { var pickerContainer = UIView() var picker = UIDatePicker() @IBOutlet weak var selectedDate: UIButton! override func viewDidLoad() { super.viewDidLoad() self.selectedDate.setTitle("", forState: UIControlState.Normal) configurePicker() } func configurePicker() { pickerContainer.frame = CGRectMake(0.0, 600.0, 320.0, 300.0) pickerContainer.backgroundColor = UIColor.whiteColor() picker.frame = CGRectMake(0.0, 20.0, 320.0, 300.0) picker.setDate(NSDate(), animated: true) picker.maximumDate = NSDate() picker.datePickerMode = UIDatePickerMode.Date pickerContainer.addSubview(picker) var doneButton = UIButton() doneButton.setTitle("Done", forState: UIControlState.Normal) doneButton.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal) doneButton.addTarget(self, action: Selector("dismissPicker"), forControlEvents: UIControlEvents.TouchUpInside) doneButton.frame = CGRectMake(250.0, 5.0, 70.0, 37.0) pickerContainer.addSubview(doneButton) self.view.addSubview(pickerContainer) } @IBAction func selectDate(sender: AnyObject) { UIView.animateWithDuration(0.4, animations: { var frame:CGRect = self.pickerContainer.frame frame.origin.y = self.view.frame.size.height - 300.0 + 84 self.pickerContainer.frame = frame }) } func dismissPicker () { UIView.animateWithDuration(0.4, animations: { self.pickerContainer.frame = CGRectMake(0.0, 600.0, 320.0, 300.0) let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd/MM/yyyy" self.selectedDate.setTitle(dateFormatter.stringFromDate(self.picker.date), forState: UIControlState.Normal) }) } A: I made some changes for you. In addition to adding one right bracket at the end of the code, I modified the CGRectMake coordinates in two places. Things were off the screen. When I implemented the code I added the button for the date display in the upper left corner of the view and connected it to the IBOutlet. This should give you a good start. import UIKit class SignUpController: UIViewController, UITextFieldDelegate { var pickerContainer = UIView() var picker = UIDatePicker() @IBOutlet weak var selectedDate: UIButton! override func viewDidLoad() { super.viewDidLoad() self.selectedDate.setTitle("", forState: UIControlState.Normal) configurePicker() } func configurePicker() { pickerContainer.frame = CGRectMake(0.0, 50, 320.0, 300.0) pickerContainer.backgroundColor = UIColor.whiteColor() picker.frame = CGRectMake(0.0, 20.0, 320.0, 300.0) picker.setDate(NSDate(), animated: true) picker.maximumDate = NSDate() picker.datePickerMode = UIDatePickerMode.Date pickerContainer.addSubview(picker) var doneButton = UIButton() doneButton.setTitle("Done", forState: UIControlState.Normal) doneButton.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal) doneButton.addTarget(self, action: Selector("dismissPicker"), forControlEvents: UIControlEvents.TouchUpInside) doneButton.frame = CGRectMake(250.0, 5.0, 70.0, 37.0) pickerContainer.addSubview(doneButton) self.view.addSubview(pickerContainer) } @IBAction func selectDate(sender: AnyObject) { UIView.animateWithDuration(0.4, animations: { var frame:CGRect = self.pickerContainer.frame frame.origin.y = self.view.frame.size.height - 300.0 + 84 self.pickerContainer.frame = frame }) } func dismissPicker () { UIView.animateWithDuration(0.4, animations: { self.pickerContainer.frame = CGRectMake(0.0, 50, 320.0, 300.0) let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd/MM/yyyy" self.selectedDate.setTitle(dateFormatter.stringFromDate(self.picker.date), forState: UIControlState.Normal) }) } }
{ "pile_set_name": "StackExchange" }
Q: How to write query in 1 to many relation, to get random 1 record from 2nd table in sql query I have 3 tables tblAlbum ------------------------ AlbumID Int Name nvarchar(255) tblPhotos ------------------------- PhotoID int FileName nvarchar(255) tblAlbumPhotos ------------------------ AlbumPhotoID (P) int AlbumID int PhotoID int This is the query to get the result from Album and 1 photo with Album(RankNo,AlbumID, Name, FileName, PhotoID) as ( select rank() over(partition by GA.AlbumID order by GP.photoid) as RankNo , GA.AlbumID,GA.Name, GP.FileName, GP.PhotoID, GP.CreatedDate from tblAlbum GA inner join tblAlbumPhotos GAP on GAP.AlbumID=GA.AlbumID inner join tblPhotos GP on GP.PhotoID=GAP.PhotoID ) select RankNo,AlbumID, Name, FileName, PhotoID from Album where RankNo=1 BUT, I Want a result from tblAlbum table and FileName any 1 (Random) from tblPhotos A: Try this (I've only changed your order by clause): ;with Album(RankNo,AlbumID, Name, FileName, PhotoID) as ( select rank() over(partition by GA.AlbumID order by newId()) as RankNo , GA.AlbumID,GA.Name, GP.FileName, GP.PhotoID, GP.CreatedDate from tblAlbum GA inner join tblAlbumPhotos GAP on GAP.AlbumID=GA.AlbumID inner join tblPhotos GP on GP.PhotoID=GAP.PhotoID ) select RankNo,AlbumID, Name, FileName, PhotoID from Album where RankNo=1
{ "pile_set_name": "StackExchange" }
Q: Looking for a good name for this "Quantisation Regime" This is an attempt to salvage the wreckage of my hope to motivate (finite) quantum groups a lá this question. Let $\{S_i\}_{i=0}^n$ be a family of finite sets and let $\varphi$ be a map $$\varphi:S_1\times S_2\times \cdots \times S_n\rightarrow S_0.$$ This map may be extended to a multilinear map $$\varphi_1:\mathbb{C}S_1\times \cdots\times \mathbb{C}S_n\rightarrow \mathbb{C}S_0.$$ Here $\mathbb{C}S_i$ is the complex vector space with basis $\{\delta^s:s\in S_i\}$. This map may be further extended to a linear map: $$\tilde{\varphi_1}:\mathbb{C}S_1\otimes \cdots\otimes \mathbb{C}S_n\rightarrow \mathbb{C}S_0.$$ Finally we can take the transpose of this map to get a map: $$\tilde{\varphi_1}^*:\mathbb{C}S_0^*\rightarrow \mathbb{C}S_1^*\otimes \cdots\otimes \mathbb{C}S_n^*.$$ I am looking for a word to describe this quantisation where a map on cartesian copies of $S_i$ is turned into a map into tensor copies of $\mathbb{C}S_i^*$. The answer should be "$\underline{\qquad}$ Quantisation". I had hoped to call it categorical or functorial quantisation but I know now this isn't appropriate. I might be happy enough to just call it "Tensoring Quantisation" but would love a better word. Context: One way to generalise classical finite group concepts to the quantum setting is to use the above regime. For example, applying this regime to multiplication, inclusion of the unit and inverses yields comultiplication, the counit and the antipode. Translating the axioms of associativity, identity and inverses gives coassociativity, the counitary property and the antipodal property. Similarly, applying this regime to group actions $X\times G\rightarrow X$ yields corepresentations $V\rightarrow V\otimes F(G)$. The translations of the axioms of actions gives the axioms of corepresentations. A: With help of Matthias's comments (both on this question and on the previous one), I have come to see that my problems emanate from the way I am doing the category theory. The below answers both this question and the previous. Rather than talking about the category of finite groups (and group homomorphisms), we are better off starting in the category of finite sets where the morphisms are functions. A finite group $G$ is an object in this category together with three morphisms $m:G\times G\rightarrow G$, $^{-1}:G\rightarrow G$ and $e:\{0\}\rightarrow G$ that satisfy three commutative diagrams expressing associativity, identity and inverses. There is a functor from the category of finite sets to the category of finite dimensional vector spaces that sends the object $G$ to the object $\mathbb{C}G$ --- the complex vector space with basis $\{\delta^g:g\in G\}$. For this to be a morphism, the images of $m$, $^{-1}$ and $e$ under this $\mathbb{C}$ functor must be morphisms in the category of finite dimensional vector spaces i.e. they must be linear maps. If we define: $$\begin{align} \varphi:\mathbb{C}G\times\mathbb{C}G\rightarrow \mathbb{C}G,\qquad(\delta^g,\delta^h)\mapsto \delta^{gh}, \end{align}$$ and extend bilinearly we get a bilinear map rather than a linear map. However we know there is a linear map $\nabla:\mathbb{C}G\otimes \mathbb{C}G\rightarrow \mathbb{C}G$, namely $\delta^g\otimes \delta^h\mapsto \delta^{gh}$ and we send the morphism $m$ to the morphism $\nabla$ using the $\mathbb{C}$ functor so that $\mathbb{C}m=\nabla$. In a similar way any morphisms on cartesian copies of objects are sent to morphisms on tensor products; e.g. $$I_G\times m:G\times G\times G\rightarrow G\times G$$ is sent to $$\mathbb{C}(I_G\times m)=I_{\mathbb{C}G}\otimes \nabla:\mathbb{C}G\otimes\mathbb{C}G\otimes \mathbb{C}G\rightarrow \mathbb{C}G\otimes\mathbb{C}G.$$ The finite set morphism $^{-1}$ is defined in the obvious way and we write $\mathbb{C}(^{-1})=\operatorname{inv}$. Also $\mathbb{C}e:\mathbb{C}\{0\}\cong\mathbb{C}\rightarrow \mathbb{C}G$, $1\mapsto \delta^e$ is denoted by $\eta$. Now the image of a commutative diagram under a functor is another commutative diagram and what we have if we look at the three commutative diagrams expressing the group axioms is: \begin{eqnarray} \nabla\circ(\nabla\otimes I_{\mathbb{C} G})=\nabla\circ(I_{\mathbb{C} G}\otimes\nabla) \\ \nabla\circ(\eta\otimes I_{\mathbb{C} G})\cong I_{\mathbb{C} G}\cong \nabla\circ(I_{\mathbb{C} G}\otimes\eta) \\ \nabla\circ(\operatorname{inv}\otimes I_{\mathbb{C} G})\circ \Delta_{\mathbb{C} G}=\eta\circ\varepsilon_{\mathbb{C} G}=\nabla\circ(I_{\mathbb{C} G}\otimes\operatorname{inv})\circ\Delta_{\mathbb{C} G}. \end{eqnarray} Here $\Delta_{\mathbb{C}G}:\mathbb{C}G\rightarrow \mathbb{C}G\otimes \mathbb{C}G$, $\delta^g\mapsto \delta^g\otimes \delta^g$ is the diagonal map and $\varepsilon_{\mathbb{C}G}:\mathbb{C}G\rightarrow \mathbb{C}$, $\delta^g\mapsto 1$. Now apply the dual map $\mathcal{D}$ to $\mathbb{C}G$. The dual map is an contravariant endofunctor of the category of finite dimensional vector spaces and sends a vector space to it's dual and a linear map $T:U\rightarrow V$ to its transpose ($\varphi\in V^*$): $$\mathcal{D}(T):V^*\rightarrow U^*,\qquad \varphi\mapsto \varphi\circ T.$$ Once again this map sends linear maps to linear maps and so is a functor and the image of the commutative diagrams expressing $\mathbb{C}(\text{group axioms})$ is a commutative diagram expressing the three Hopf algebra axioms. Call the composition of these two functors by the quantisation functor: $$\mathcal{Q}:\textbf{FinSet}\rightarrow \textbf{FinVec},\qquad \mathcal{Q}=\mathcal{D}\circ\mathbb{C}.$$ Note $$\mathcal{Q}(G)=F(G),\,\mathcal{Q}(m)=\Delta, \mathcal{Q}(^{-1})=S\text{ and }\mathcal{Q}(e)=\varepsilon.$$ Also the image of a commutative diagram under a functor is a commutative diagram so we have: $$\begin{align} \mathcal{Q}(\text{associativity})&=\text{coassociativity} \\ \mathcal{Q}(\text{identity})&=\text{counitary property} \\ \mathcal{Q}(\text{inverses})&=\text{antipodal property} \end{align}$$ Now the take an object $H$ in the category of finite vector spaces with maps that satisfy these "quantised" axioms. Such an object is a finite Hopf-algebra and if it is non-commutative: $$\Delta^*_{H}(a\otimes b)=\Delta^*_H(b\otimes a),$$ then it can be considered (if we make a few extra assumptions) the algebra of functions on a quantum group and I am simply going to call this regime by Quantisation via Category Theory.
{ "pile_set_name": "StackExchange" }
Q: Unable to execute Unix command through Java code case "BVT Tool": System.out.println("Inside BVT Tool"); try { String[] command1 = new String[] {"mv $FileName /bgw/feeds/ibs/incoming/"}; Runtime.getRuntime().exec(command1); } catch(IOException e) { System.out.println("execption is :"+ e); e.printStackTrace(); } break; I'm unable to execute the Unix command. It's showing the following exception: java.io.IOException: Cannot run program mv $FileName /bgw/feeds/ibs/incoming/": CreateProcess error=2, The system cannot find the file specified. A: I agree with @Reimeus on most points, but I want to point out that there reason you're getting this particular error message is a crosscontamination between 2 of the overloaded versions of exec: String command1 = "mv $FileName /bgw/feeds/ibs/incoming/"; Runtime.getRuntime().exec(command1); Would work - it's allowed to specify the command and its parameters in one String if you use the overloaded version that expects a String String[] command1 = new String[] {"mv", "$FileName", "/bgw/feeds/ibs/incoming/"}; Runtime.getRuntime().exec(command1); would work too, because it uses the the exec version expecting a String array. That version expects the command and its parameters in separate Strings Please note that I here assume that $Filename is actually the name of the file, so no shell-based substitution will take place. EDIT: if FileName is a variable name as you seem to suggest elsewhere in the comments, try String[] command1 = new String[] {"mv", FileName, "/bgw/feeds/ibs/incoming/"}; But : with Commons IO you could just do FileUtils.moveFileToDirectory(new File(FileName), new File("/bgw/feeds/ibs/incoming/") , true); JavaDoc which is totally portable between Mac, Windows and Linux (your version won't work on Windows) is faster because it doesn't need to spawn an external process gives you more information when something goes wrong.
{ "pile_set_name": "StackExchange" }
Q: Updating a listbox from worker thread? I have found an article on this subject but I can't quite get my head around how to implement the answer proposed. What I am getting is a cross-thread exception and I realise that the GUI is in one thread and the worker is in another thread. The exception: System.InvalidOperationException was unhandled by user code HResult=-2146233079 Message=Cross-thread operation not valid: Control 'listBoxCodes' accessed from a thread other than the thread it was created on. Source=System.Windows.Forms StackTrace: at System.Windows.Forms.Control.get_Handle() at System.Windows.Forms.Control.SendMessage(Int32 msg, Int32 wparam, String lparam) at System.Windows.Forms.ListBox.NativeInsert(Int32 index, Object item) at System.Windows.Forms.ListBox.ObjectCollection.AddInternal(Object item) at System.Windows.Forms.ListBox.ObjectCollection.Add(Object item) at Find_Duplicate_MX_codes.MyThread.backgroundWorker_DoWork(Object sender, DoWorkEventArgs e) in D:\My Programs\Find Duplicate MX codes\Find Duplicate MX codes\MyThread.cs:line 69 at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e) at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument) InnerException: Now, I was trying to initially to deal with this by writing my code as follows: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Find_Duplicate_MX_codes { public struct ThreadSettings { public Find_Duplicate_MX_codes.Form1 pMainForm { get; set; } public ProgressBar progressBar { get; set; } public TextBox progressLabel { get; set; } public String strFile { get; set; } public ListBox lbCodes { get; set; } public ListBox lbCodesDuplicate { get; set; } } class MyThread { private BackgroundWorker m_backgroundWorker; ThreadSettings m_sThreadSettings; public MyThread(ThreadSettings sThreadSettings) { m_sThreadSettings = sThreadSettings; m_backgroundWorker = new BackgroundWorker(); m_backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork); m_backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged); m_backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted); m_backgroundWorker.WorkerReportsProgress = true; } public void start() { if(m_sThreadSettings.pMainForm != null) m_sThreadSettings.pMainForm.Enabled = false; // Stop user interacting with the form m_backgroundWorker.RunWorkerAsync(); } public void stop() { m_backgroundWorker.CancelAsync(); } public void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { m_backgroundWorker.ReportProgress(0, "Extracting MX codes {0}%)"); using (var reader = new StreamReader(m_sThreadSettings.strFile)) { Stream baseStream = reader.BaseStream; long length = baseStream.Length; string line; while ((line = reader.ReadLine()) != null) { if (line.Length > 8 && line.Substring(0, 4) == "080,") { string strCode = line.Substring(4, 4); if (m_sThreadSettings.lbCodes.FindStringExact(strCode) == -1) { m_sThreadSettings.lbCodes.Items.Add(strCode); } else m_sThreadSettings.lbCodesDuplicate.Items.Add(strCode); } m_backgroundWorker.ReportProgress(Convert.ToInt32(baseStream.Position / length * 100), "Extracting MX codes {0}%)"); } } } private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { if(m_sThreadSettings.progressBar != null) m_sThreadSettings.progressBar.Value = e.ProgressPercentage; if(m_sThreadSettings.progressLabel != null) m_sThreadSettings.progressLabel.Text = String.Format((string)e.UserState, e.ProgressPercentage); } private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { int iResult = Convert.ToInt32(e.Result); if (m_sThreadSettings.pMainForm != null) m_sThreadSettings.pMainForm.Enabled = true; // User can interact with form again } } } If I comment out the line of code that tries to add an item to the list box is works. Progress bar/label are updating. It is when I try to update the listbox that it fails. In the answer on the other post it suggests: UserContrl1_LOadDataMethod() { if(textbox1.text=="MyName") //<<======Now it wont give exception** { //Load data correspondin to "MyName" //Populate a globale variable List<string> which will be //bound to grid at some later stage if(InvokeRequired) { // after we've done all the processing, this.Invoke(new MethodInvoker(delegate { // load the control with the appropriate data })); return; } } } But I am struggling to understand how to make use of that answer for my lines of code: m_sThreadSettings.lbCodes.Items.Add(strCode); How do I change it so that I can get the list boxes populated and: a) Not get the cross-thread exception b) Not choke the GUI due to the updating of the list boxes Thank you! Update: I have tried this code: Invoke(new MethodInvoker(delegate { m_sThreadSettings.lbCodes.Items.Add(strCode); })); But I get warnings that I don't fully understand: Update 2: I now realise that Invoke is part of the Form object. So I changed my code to: if (m_sThreadSettings.lbCodes.FindStringExact(strCode) == -1) m_sThreadSettings.pMainForm.Invoke(new MethodInvoker(delegate { m_sThreadSettings.lbCodes.Items.Add(strCode); })); else m_sThreadSettings.pMainForm.Invoke(new MethodInvoker(delegate { m_sThreadSettings.lbCodesDuplicate.Items.Add(strCode); })); That now seems to work. But watch this animation: https://www.dropbox.com/s/mznoqhqll8m28x7/Results0001.mp4?dl=0 It just doesn't all process quite as I expect. It seems to still be doing all the processing of the GUI once the reading has finished. Confused. Update 3: I used Console.Beep() to establish when my progress change handler was being fired. In addition, I confirmed when the progress actually changes. And it does 0 for all apart from towards the end when it does 100. So this BaseSteam.Position might be the fault. A: There turned out to be unrelated issues with my code. ISSUE 1 This is how to update the list box from a worker thread: public void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { m_backgroundWorker.ReportProgress(0, "Extracting MX codes {0}%"); using (var reader = new StreamReader(m_sThreadSettings.strFile)) { Stream baseStream = reader.BaseStream; long length = baseStream.Length; string line; while ((line = reader.ReadLine()) != null) { if (line.Length > 8 && line.Substring(0, 4) == "080,") { string strCode = line.Substring(4, 4); if (m_sThreadSettings.lbCodes.FindStringExact(strCode) == -1) m_sThreadSettings.pMainForm.Invoke(new MethodInvoker(delegate { m_sThreadSettings.lbCodes.Items.Add(strCode); })); else m_sThreadSettings.pMainForm.Invoke(new MethodInvoker(delegate { m_sThreadSettings.lbCodesDuplicate.Items.Add(strCode); })); } m_backgroundWorker.ReportProgress(Convert.ToInt32((100 / (double)length) * baseStream.Position), "Extracting MX codes {0}%"); } } } You have to use the Form's Invoke method. ISSUE 2 The logic for calculating the progress needed to be adjusted because in this context the result was always 0 due to the way the calculation worked. So I now use: m_backgroundWorker.ReportProgress( Convert.ToInt32((100 / (double)length) * baseStream.Position), "Extracting MX codes {0}%"); Voila! My form list b ox content is getting update and the progress bar is being updated when expected ... :)
{ "pile_set_name": "StackExchange" }
Q: How to build and run Maven projects after importing into Eclipse IDE I am learning building a Java project in Eclipse using Maven. I created a Java project HelloWorld from “maven-archetype-quickstart” template in a folder D:/maven_projects. Then to convert the Maven project to support Eclipse IDE, I navigated into the project folder and issued the commands: mvn eclipse:eclipse and mvn package . Then I imported the project in Eclipse and did the necessary Eclipse configurations like setting the Maven local repository in Eclipse classpath. Now the project in D:/EclipseWorkspace folder. I ran the project successfully in Eclipse printing "helloworld". Now if I want to go on develop the project and for that reason want to add new dependencies in pom.xml in Eclipse, then the new jars are not added in classpath when I run the project. So my question is after importing a Maven project into Eclipse how can I add more and more dependencies in pom.xml, then build and run the project? What is the recommended and efficient way to do this? A: I would recommend you don't use the m2eclipse command line tools (i.e. mvn eclipse:eclipse) and instead use the built-in Maven support, known as m2e. Delete your project from Eclipse, then run mvn eclipse:clean on your project to remove the m2eclipse project data. Finally, with a modern version of Eclipse, just do "Import > Maven > Existing project into workspace..." and select your pom.xml. M2e will automatically manage your dependencies and download them as required. It also supports Maven builds through a new "Run as Maven build..." interface. It's rather nifty. A: Dependencies can be updated by using "Maven --> Update Project.." in Eclipse using m2e plugin, after pom.xml file modification. A: 1.Update project Right Click on your project maven > update project 2.Build project Right Click on your project again. run as > Maven build If you have not created a “Run configuration” yet, it will open a new configuration with some auto filled values. You can change the name. "Base directory" will be a auto filled value for you. Keep it as it is. Give maven command to ”Goals” fields. i.e, “clean install” for building purpose Click apply Click run. 3.Run project on tomcat Right Click on your project again. run as > Run-Configuration. It will open Run-Configuration window for you. Right Click on “Maven Build” from the right side column and Select “New”. It will open a blank configuration for you. Change the name as you want. For the base directory field you can choose values using 3 buttons(workspace,FileSystem,Variables). You can also copy and paste the auto generated value from previously created Run-configuration. Give the Goals as “tomcat:run”. Click apply. Click run. If you want to get more clear idea with snapshots use the following link. Build and Run Maven project in Eclipse (I hope this answer will help someone come after the topic of the question)
{ "pile_set_name": "StackExchange" }
Q: How to remove textbox using dynamic id in javascript? I have lots of dynamic textboxes with different ids. I am trying to remove them on click i have a function <script> function removing(id){ alert(id); id.remove(); } </script> and my html textbox <input type="text" id="a" name="name" onclick="removing(this.id)" /> when i click on it. it gives alert box but not removing textbox any help? A: You need the element itself, so just pass this <input type="text" id="a" name="name" onclick="removing(this)" /> And then the function can be function removing(elm){ alert(elm.id); elm.parentNode.removeChild(elm); } You need to use removeChild from parentNode of element to remove it from DOM.
{ "pile_set_name": "StackExchange" }
Q: Using the system's time zone settings in PHP So I have a web app written in PHP that will run on different Ubuntu servers around the world. Some of the servers will be configured to run on local time, some will run on UTC, it depends on the customer. While I can edit the php.ini-file and set date.timezone, manually enter such data is bound to get wrong one day. How can I get PHP to use the time zone already defined in the system (tzdata)? Or, in other words: How can I extract (the long) time zone name from the system in PHP to use in date_default_timezone_set()? A: With the help that Andrey Knupp gave in his answer, I was able to solve this one. echo "Time: " . date("Y-m-d H:i:s") . "<br>\n"; $shortName = exec('date +%Z'); echo "Short timezone:" . $shortName . "<br>"; $longName = timezone_name_from_abbr($shortName); echo "Long timezone:" . $longName . "<br>"; date_default_timezone_set($longName); echo "Time: " . date("Y-m-d H:i:s") . "<br>\n"; Gives output: Time: 2011-12-23 23:29:45 Short timezone:MYT Long timezone:Asia/Kuala_Lumpur Time: 2011-12-24 06:29:45 Update: The short name for the time zones are not unique. For instance, in both America and Australia there is an "EST", leading timezone_name_from_abbr to sometimes pick the one I don't want to... You can ask date how big the offset is, and that can be used to further match the correct time zone: $offset = exec('date +%::z'); $off = explode (":", $offset); $offsetSeconds = $off[0][0] . abs($off[0])*3600 + $off[1]*60 + $off[2]; $longName = @timezone_name_from_abbr($shortName, $offsetSeconds); A: If you have timezone set you could use: http://php.net/manual/en/function.date-default-timezone-get.php Or http://php.net/manual/en/function.timezone-name-from-abbr.php
{ "pile_set_name": "StackExchange" }
Q: How can I keep content from re-sizing it's wrapper div? I'm a css noob, and though I want this DIV to resize when the window is resized, I don't want inner content to change the size of it. A: Use the overflow statement. e.g. overflow: hidden; /* all content hidden as it spills over */ overflow: auto; /* Scroll bars appear on div when required to allow moving around */ overflow: scroll; /* Scroll bars will be present at all times */
{ "pile_set_name": "StackExchange" }
Q: Android banner ribbon using shape I am trying to figure out how I would stack shapes so I can create the following ribbon(Pink/White/Pink/White/Pink part). I will then be using this as a background for my textview. A: I figured it out using a layer-list <?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#FFe5887c" /> <size android:width="2dp" android:height="2dp"/> </shape> </item> <item android:top="2dp"> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#FFFFFFFF" /> <size android:width="1dp" android:height="1dp"/> </shape> </item> <item android:top="3dp"> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#FFe5887c" /> <size android:width="20dp" android:height="20dp"/> </shape> </item> <item android:top="23dp"> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#FFFFFFFF" /> <size android:width="1dp" android:height="1dp"/> </shape> </item> <item android:top="24dp"> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#FFe5887c" /> <size android:width="2dp" android:height="2dp"/> </shape> </item> </layer-list>
{ "pile_set_name": "StackExchange" }
Q: Order products by sales within 30 days followed by those without sales I'm trying to fetch a list of products ordered by the sold quantity within the last 30 days. How would I make the following query also order by the sold quantity in the last 30 days and having them followed by the products that have not sold anything in those 30 days? I need those with a sale within the last 30 days first and then the products without any sales after. The field with the sale date is a datetime field called orders.sold_time This is my current query: SELECT pd.products_id AS id, pd.products_name AS name FROM products_description pd LEFT JOIN products ON pd.products_id = products.products_id LEFT JOIN orders_products ON pd.products_id = orders_products.products_id LEFT JOIN orders ON orders_products.orders_id = orders.orders_id WHERE pd.c5_dataset = 'DAT' AND products.products_status =1 AND pd.language_id =4 AND NOT EXISTS ( SELECT 1 FROM products_description WHERE products_id = pd.products_id AND language_id = 10 ) AND orders_total.class = 'ot_total' GROUP BY pd.products_id ORDER BY count( orders_products.products_quantity ) DESC A: You can use a case when expression for that. The expression that gives you the sold quantity in the last 30 days is: sum(case when orders.sold_time >= date_add(curdate(), interval -30 day) then orders_products.products_quantity end) You can put this in the order by clause, and then you should decide what to order the articles by that have no sales in the last 30 days. This could for instance be the all-time sold quantity. I would also use aliases for all your tables (like you did for the first one). So o for orders, op for orders_products. So then your order by would look like: order by sum(case when o.sold_time >= date_add(curdate(), interval -30 day) then op.products_quantity end), sum(op.products_quantity) To check the results, it would be good to also add those two expressions to the select list. Some notes about the SQL: As you have a non-null condition on products.products_status (=1) there is no good reason to use LEFT JOIN products. Instead use the more efficient INNER JOIN. You would probably gain on efficiency if you would replace the NOT EXISTS condition with an INNER JOIN clause: INNER JOIN products_description p2 ON p2.products_id = pd.products_id AND p2.language_id = 10 provided there can be at most one description per product and language.
{ "pile_set_name": "StackExchange" }
Q: Java map with lists of objects to list Here is my code: public class CarShop { private final HashMap<Brand, List<CarPrototype>> catalog; public List<CarPrototype> allPrototypes() { List<CarPrototype> prototypes = catalog.values().stream().collect(Collectors.toList()) return prototypes ; } What I want to do in this method is I want to get a list of all different car prototypes given in car shop catalog. I should not use for loop, so stream comes into play. My solution is adds only lists of prototypes, and I struggle finding how to change it so it add specific prototypes themselves. A: If you have a Stream<List<Foo>> and want to convert it to List<Foo> you can use flatMap: Stream<List<Foo>> stream = ...; Stream<Foo> flatStream = stream.flatMap(List::stream); List<Foo> list = flatStream.collect(Collectors.toList()); For your specific example: public List<CarPrototype> allPrototypes() { List<CarPrototype> prototypes = catalog.values().stream() .flatMap(List::stream) .collect(Collectors.toList()); return prototypes; }
{ "pile_set_name": "StackExchange" }
Q: Fields re-initialized in PageLoad c# I am perplexed, and maybe I am just familiar with the properties of pageLoad, IsPostBack, or IsCallback. I created a Boolean variable called "first" and set it to True. First time through PageLoad, there is a line of code if first = False, if so, write = true. Then I have a Run_write routine attached to a button, when it runs, if the user response Yes, to the initial question, I make another group of radio buttons visible and set first to false. (i ran this in debug, and I know it hits this line of code) ... so the write to sql is ignored because write == false and the window reappears with the new set of Buttons... Great! Furthermore, I go through the PageLoad routine again, and it hits the line if (!first), set write to TRUE. my issue is first has been re-set to true? What am I missing? Note, I was able to work around this by utilizing whether the new set of buttons is checked, but I may not want to go this route, and I do want to understand what is going on. code is below. namespace MEAU.Web.Components.SupportCenter { public partial class feedback : System.Web.UI.Page { String login; String myurl; String response; String s_call; String p_ship; String wrnty; Boolean write; Boolean first = true; protected void Page_Load(object sender, EventArgs e) { login = Sitecore.Security.Accounts.User.Current.Profile.Email; myurl = Request.QueryString["value"]; s_call = "No"; p_ship = "No"; wrnty = "No"; // Hide the question Buttons scall.Visible = false; parts.Visible = false; wrnt.Visible = false; lit.Visible = false; write = false; if (!first) write = true; } protected void Run_Write(object sender, EventArgs e) { // Get Reponse if (yes.Checked) { response = "Yes"; // Display the quesiton buttons, and Hide the NO button scall.Visible = true; parts.Visible = true; wrnt.Visible = true; lit.Visible = true; no.Visible = false; first = false; // Did this Prevent a Service call? if (scall.Checked) { s_call = "Yes"; write = true; } // Did this Prevent a parts shipment? if (parts.Checked) { p_ship = "Yes"; write = true; } // Is this under warranty? if (wrnt.Checked) { wrnty = "Yes"; write = true; } // write = true; } if (no.Checked) { response = "No"; write = true; } if (write == true) { SqlConnection conn = new SqlConnection(Sitecore.Configuration.Settings.GetConnectionString("feedback")); SqlCommand cmd = new SqlCommand("Insert_fb", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@login", login); cmd.Parameters.AddWithValue("@url", myurl); cmd.Parameters.AddWithValue("@response", response); cmd.Parameters.AddWithValue("@dateTime", DateTime.Now); cmd.Parameters.AddWithValue("@serviceCall", s_call); cmd.Parameters.AddWithValue("@partsShipment", p_ship); cmd.Parameters.AddWithValue("@warranty", wrnty); try { conn.Open(); cmd.ExecuteNonQuery(); Response.Write("<script type='text/javascript'>parent.$.fancybox.close();</script>"); Response.Write("<script type='text/javascript'>return false;</script>"); } catch (Exception ex) { throw new Exception("Error on file update" + ex.Message); } finally { conn.Close(); } } } } } A: Every HTTP request to your site creates a new instance of your page class. Instance state is not preserved. Instead, you need to store the state in session or ViewState, depending on what you want to apply to.
{ "pile_set_name": "StackExchange" }
Q: How to run a command via elisp, completely ignoring its output and status? (fire and forget) Currently I'm using shell command - which makes a buffer, showing the output, sometimes locking emacs. What is a good way to run a process that: Doesn't make a buffer. Doesn't lock emacs. Ignores the stdout/stderr. A: call-process, despite normally being used for synchronous process calls: call-process is a built-in function in `C source code'. (call-process PROGRAM &optional INFILE DESTINATION DISPLAY &rest ARGS) [...] Insert output in DESTINATION before point[...]0 means discard and don't wait [...] If DESTINATION is 0, `call-process' returns immediately with value nil. [...]
{ "pile_set_name": "StackExchange" }
Q: Catmull-Rom blending functions I have a non-uniform Catmull-Rom spline (so the $t_i$ parameter values are not uniformly distributed). Is there a simple way to calculate the blending functions of the control points? So the spline can be expressed as $f(t)=\sum_{i=0}^nw_i(t)p_i$ (where $p_i$ is the control point itself, and $w_i(t)$ is the blending function) The spline between the $p_i$ and $p_{i+1}$ is: $f_i(t) = a_3(t-t_i)^3+a_2(t-t_i)^2+a_1(t-t_i)+a_0$ Where $a_0=p_i$ $a_1=v_1$ $a_2=\frac{3(p_{i+1}-p_i)}{(t_{i+1}-t_i)^2}-\frac{v_{i+1}+2v_i}{t_{i+1}-t_i}$ $a_3=\frac{2(p_i-p_{i+1})}{(t_{i+1}-t_i)^3}-\frac{v_{i+1}+v_i}{(t_{i+1}-t_i)^2}$ (And of course, $v_i = \frac{\frac{p_{i+1}-p_i}{t_{i+1}-t_i}+\frac{p_i-p_{i-1}}{t_i-t_{i-1}}}{2}$) I can express $f_i(t)$ only in terms of $p$-s: $f_i(t)=\left( 2\frac{(p_i-p_{i+1})}{(t_{i+1}-t_i)^3}+\frac{\frac{\frac{p_{i+2}-p_{i+1}}{t_{i+2}-t_{i+1}}+\frac{p_{i+1}-p_i}{t_{i+1}-t_i}}{2}+\frac{\frac{p_{i+1}-p_i}{t_{i+1}-t_i}+\frac{p_i-p_{i-1}}{t_i-t_{i-1}}}{2}}{(t_{i+1}-t_i)^2} \right )(t-t_i)^3+\left(\frac{3(p_{i+1}-p_i)}{(t_{i+1}-t_i)^2}-\frac{\frac{\frac{p_{i+2}-p_{i+1}}{t_{i+2}-t_{i+1}}+\frac{p_{i+1}-p_i}{t_{i+1}-t_i}}{2}+2\frac{\frac{p_{i+1}-p_i}{t_{i+1}-t_i}+\frac{p_i-p_{i-1}}{t_i-t_{i-1}}}{2}}{t_{i+1}-t_i} \right )(t-t_i)^2+\frac{\frac{p_{i+1}-p_i}{t_{i+1}-t{i}}+\frac{p_i-p_{i-1}}{t_i-t_{i-1}}}{2}(t-t_i)+p_i$ I can do Collect using Mathematica, but it looks like a "brute-force" approach to me, I'm sure there is a much simpler way. A: A Catmull-Rom spline can be expressed as a b-spline, of course (every spline can be). So, the first step is to figure out the b-spline representation. The knots of our b-spline are going to be the $2n+6$ values: $$ t_0, t_0, t_0, t_0, t_1, t_1, t_2, t_2, \;\ldots\; t_{n-1}, t_{n-1}, t_n, t_n, t_n, t_n $$ Let $\phi_0, \ldots \phi_{2n+1}$ be the cubic b-spline basis functions constructed from this knot sequence. Define $2n+2$ points $Q_i$ by $$ \;\;\;\;\;\;Q_0 = P_0 \quad ; \quad Q_1 = P_0 + V_0 \\ Q_2 = P_1 - V_1 \quad ; \quad Q_3 = P_1 + V_1 \\ Q_4 = P_2 - V_2 \quad ; \quad Q_5 = P_2 + V_2 \\ \vdots \\ Q_{2i} = P_i - V_i \quad ; \quad Q_{2i+1} = P_i + V_i \\ \vdots \\ Q_{2n-2} = P_{n-1} - V_{n-1} \quad ; \quad Q_{2n-1} = P_{n-1} + V_{n-1} \\ Q_{2n} = P_{n} - V_{n} \quad ; \quad Q_{2n+1} = P_n $$ where $V_i$ is the derivative vector of the Catmull-Rom spline at point $P_i$. Typically $$ V_i = \frac12\left({\frac{P_{i+1}-P_i}{t_{i+1}-t_i}+\frac{P_i-P_{i-1}}{t_i-t_{i-1}}}\right) $$ Then the Catmull-Rom spline is $$ f(t) = \sum_{i=0}^{2n+1}\phi_i(t)Q_i $$ You can eliminate the $Q_i$ and $V_i$ using the equations above, and you'll end up with something that's in the form that you want. I think it's still going to be a huge mess, but this approach requires less algebra than the one you were using, I think. The key idea is to use a b-spline or Bezier representation of the spline, rather than the algebraic one you used. In the b-spline or Bezier forms, the relationship with the interpolated points and derivatives is more direct, so there's less algebra.
{ "pile_set_name": "StackExchange" }
Q: Azure API gateway and app service, concurrency limitation? Have an odata api endpoint hosted in App Service behind API Management Gateway, but getting concurrency call issues, trying to identify where the problem occurs. We use a standard tier of API gateway. Is there a concurrent call limit? Sorry trying to scan through documentation didn't find one straight answer. One more question, what is the simplest way to track the request and response the API gateway generates? Thanks A: Adding the header Ocp-Apim-Trace: true to a request will return a link to a complete trace of the request and respond. This only works if you are using a subscription key for an administrator user.
{ "pile_set_name": "StackExchange" }
Q: MySQL, possible to prevent two fields to be NULL or NOT NULL? a simple table: ID, NAME, POST_ID, GROUP_ID either POST_ID or GROUP_ID must be set, but never both of them, NEITHER none of them. So, there are valid cases: ID, NAME, POST_ID, GROUP_ID x, y, 1, NULL x, y, NULL, 4 and NOT VALID cases: ID, NAME, POST_ID, GROUP_ID x, y, NULL, NULL x, y, 4, 4 is it possible to set such complicated restriction rule? A: You have to use TRIGGERS on CREATE and UPDATE events and throw an exception when the condition (COALESCE(POST_ID, GROUP_ID) IS NULL OR (POST_ID IS NOT NULL AND GROUP_ID IS NOT NULL)) occurs Here the answer to your question: Either OR non-null constraints in MySQL This is the procedure, slightly change the syntax depending on the version of MySql.
{ "pile_set_name": "StackExchange" }
Q: setTimeout и цикл for - каков порядок выполнения? var count = 0; for ( var i = 0; i < 4; i++ ) { setTimeout( function(){ assert( i == count++, "Check the value of i." ); }, i * 200); } Объясните, пожалуйста, как работает этот код. Почему цикл бегает четыре раза со значением 4? A: Проблема с обработчиками в цикле A: демо Сам setTimeOut работает асинхронно, то есть вне запускается 4 раза на выполнение функция assert i у Вас глобальная переменная и во время выполнения функции assert она уже равна 4 ем. Цикл пробегает быстрее. явная демонстрация сего факта сначало цикл прошел потом сработали assert ы
{ "pile_set_name": "StackExchange" }
Q: Best practice loading entity with related entities I am trying to figure what the best practice with loading data from web apis is. Assume you have a model structure as per below: class School { private string name; private List<Classroom> Rooms; } class Classroom { private string Type; private School school; private List<Student> Students; } class Student { private string Name; private int Age; private Classroom Room; } Is it better practice to load a single school entity and include all the related data (School + classrooms + students), then use the entity set at client side or is it better practice to just load the individual entities depending on what you need i.e. get School when school info needed, get Classroom when classroom needed so forth. I can see pros and cons to both but keen to know if there is best practice. A: Eager or Lazy Loading If you know exactly how the data is used, you can easily decide, if eager loading (load everything at once) or lazy loading (do a second request if needed) gives better average performance. Let the Consumer Decide If your platform is more generic, so you don't have the information to optimize the data retrieval / transport, you should leave the decision to the API consumer. Request Parameters You could allow request parameters that specify, which related data is transmitted: api/school/:name?with=rooms,rooms.students GraphQL Another way is GraphQL, which allows you to specify the requested data in the request body. api/school/:name and the body to retrieve everything { school { name rooms { type students { name age } } } }
{ "pile_set_name": "StackExchange" }
Q: need to read excel sheet C# and import into mySQL only 3 columns I am trying to read 3 columns from an excel sheet and import them into a mySQL database. I am very new at C# and need as much detailed help as possible. The MySQL_DB_Management in my using block is a friend's class that basically serves to create my connection string. The code I have thus far is below: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Excel = Microsoft.Office.Interop.Excel; using MySQL_DB_Management; using System.Data.SqlClient; using System.Data.OleDb; namespace Class_Code_Discrepancy { public partial class CC_Disc_Fixer : Form { MySqlDB mysql; SqlConnection sql; public CC_Disc_Fixer() { InitializeComponent(); //create connection strings sql = new SqlConnection(@"server=1.1.1.1;" + @"Trusted_Connection=false;" + @"uid=RO_agent;" + @"password=mypass;" + @"database=Depot;"); mysql = new MySqlDB("1.1.1.1", "platform", "root", "password"); } private void Upload_Click(object sender, EventArgs e) { string excelconn = @"Provider=Microsoft.Ace.OLEDB.12.0;" + @"Data Source=c:\Notebook Classcode Master 20121024.xlsx;" + @"Extended Properties=Excel 12.0;HDR=NO;FirstRowHasNames=NO"; OleDbConnection xlconn = new OleDbConnection(excelconn); //DataSet xldataset = new DataSet(); //OleDbDataAdapter xladaptor = new OleDbDataAdapter(); xlconn.Open(); OleDbCommand sel = new OleDbCommand(); sel.Connection = xlconn; DataTable dtsheet = xlconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); } Any help on what I need to do next would be greatly appreciated. A: Try looking into a ExcelDataReader library, with that, you can read Excel file into a DataSet just as shown at their page. FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read); //1. Reading from a binary Excel file ('97-2003 format; *.xls) IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream); //... //2. Reading from a OpenXml Excel file (2007 format; *.xlsx) IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); //... //3. DataSet - The result of each spreadsheet will be created in the result.Tables DataSet result = excelReader.AsDataSet(); //... //4. DataSet - Create column names from first row excelReader.IsFirstRowAsColumnNames = true; DataSet result = excelReader.AsDataSet(); Then you can iterate through it with foreach loop foreach (DataTable dt in result.Tables) { foreach (DataRow dr in dt.Rows) { foreach (DataColumn dc in dt.Columns) { // do something } } } And if you want to acces only first three columns, you can do it like result.Tables[0].Rows[0][0]; result.Tables[0].Rows[0][1]; result.Tables[0].Rows[0][2];
{ "pile_set_name": "StackExchange" }
Q: How do I customize the way Emacs prints out certain keys and key sequences? For example, I want Control key to be displayed not as C but as ⎈ (U+2388 HELM SYMBOL) in the minibuffer. Trying to personalize my Emacs and display all function keys as ISO symbols. And sequences to be displayed as something like ⎈ + x, ⎈ + f. Is there a way to do it? A: Yes. There is a function key-description that takes a list or vector of keys and returns a string that describes them. This is used by the built-in help facilities such as describe-key and describe-function to display information about key bindings. It calls single-key-description on each element of the input list. Both of these are written in C rather than Lisp, but you could in principle override both of these to do what you want by adding advice to them. key-description is even called by the Info system to render the correct key bindings in the documentation, even once the user starts customizing them.
{ "pile_set_name": "StackExchange" }
Q: Inserting calculated element to list of list This is in python 3.x: I have one list of lists [['name1', 1, 2, 3] ['name2', 4, 5, 6] ['name3', 7, 8, 9]] Above is just a representation of the type of list of lists I have. I have tried making a small program with only the same type of problem, so I've eliminated the chance that theres a space or anything in it. Now I've been trying to insert one calculated integer to the end of each list inside the big list. for i in range(0,1): listoflists.insert([i][3],((products/listoflists[i][1])*100)) I keep getting the error "IndexError: list index out of range". I've tried switching around the indices in the code and I doubt it has anything to do with the index. It's probably something wrong with my code. I've tried a "for" and "while" loop instead and that doesn't work either. I'm not trying to do this with "i in range(0,1)" specifically, the end result with probably be with len(products). A: [i][3] This is trying to access the element at index 3 of the list [i], which is what causes the error. You might want to try listoflists[i].insert(3, ...) or just listoflists[i].append(...) to add an item directly to the end of the inner lists.
{ "pile_set_name": "StackExchange" }
Q: gridview within itemtemplate getting overwrite once bind in main grid view rowdatabind method getting struckked in one of the situation. created grid with multiple grids within it. code as follows <asp:GridView CssClass="table-responsive" ID="gridReport" runat="server" AutoGenerateColumns="false" DataKeyNames="sales_id" OnRowDataBound="gridReport_RowDataBound"> <Columns> <asp:BoundField DataField="Partno" HeaderText="PART No."> <ItemStyle /> </asp:BoundField> <asp:BoundField DataField="Partname" HeaderText="PART NAME"> <ItemStyle /> </asp:BoundField> <asp:TemplateField HeaderText="ANNUAL QTY (in Nos.)"> <ItemTemplate> <asp:GridView ID="Grid_YEAR" runat="server" AutoGenerateColumns="true"> </asp:GridView> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Raw Material"> <ItemTemplate> <asp:GridView ID="Grid_RM" runat="server" AutoGenerateColumns="true"> </asp:GridView> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> and in code behind protected void gridReport_RowDataBound(object sender, GridViewRowEventArgs e) { string id = ""; try { if (e.Row.RowType == DataControlRowType.DataRow) { id = gridReport.DataKeys[e.Row.RowIndex].Value.ToString(); GridView gvGauges = e.Row.FindControl("Grid_YEAR") as GridView; DataTable dt_years = getdata(string.Format("SELECT * FROM tbl_sales_parts where sales_id={0} and sale_part_id='{1}'", id, id + "_" + e.Row.RowIndex)); if (dt_years.Rows.Count > 0) { gvGauges.DataSource = dt_years; gvGauges.DataBind(); } GridView Grid_RM = e.Row.FindControl("Grid_YEAR") as GridView; DataTable dt_RM = getdata(string.Format("SELECT * FROM tbl_RM where sale_id={0} and sale_part_id='{1}'", id, id + "_" + e.Row.RowIndex)); if (dt_RM.Rows.Count > 0) { Grid_RM.DataSource = dt_RM; Grid_RM.DataBind(); } } } catch (Exception ex) { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "message", "$.prompt('" + ex.Message + "ïd - " + id + "')", true); } } but I am getting only 2nd child grid i.e "Grid_RM" is getting bind and its overwriting first child i.e "grid_year" grid columns. and as some of column names need to generate dynamically I created grids with coloumnautogenerate set true. UPDATED previously was initializing same grid to times so it getting Overwriting. by the help of @Tim Schmelter get the solution. updated code as follows - protected void gridReport_RowDataBound(object sender, GridViewRowEventArgs e) { string id = ""; try { if (e.Row.RowType == DataControlRowType.DataRow) { id = gridReport.DataKeys[e.Row.RowIndex].Value.ToString(); GridView gvGauges = e.Row.FindControl("Grid_YEAR") as GridView; DataTable dt_years = getdata(string.Format("SELECT * FROM tbl_sales_parts where sales_id={0} and sale_part_id='{1}'", id, id + "_" + e.Row.RowIndex)); if (dt_years.Rows.Count > 0) { gvGauges.DataSource = dt_years; gvGauges.DataBind(); } GridView Grid_RM = e.Row.FindControl("Grid_RM") as GridView; DataTable dt_RM = getdata(string.Format("SELECT * FROM tbl_RM where sale_id={0} and sale_part_id='{1}'", id, id + "_" + e.Row.RowIndex)); if (dt_RM.Rows.Count > 0) { Grid_RM.DataSource = dt_RM; Grid_RM.DataBind(); } } } catch (Exception ex) { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "message", "$.prompt('" + ex.Message + "ïd - " + id + "')", true); } } A: You are initializing different gridviews(gvGauges and Grid_RM) from the same reference e.Row.FindControl("Grid_YEAR"). Instead you want: GridView gvGauges = e.Row.FindControl("Grid_YEAR") as GridView; // ... GridView Grid_RM = e.Row.FindControl("Grid_RM") as GridView;
{ "pile_set_name": "StackExchange" }
Q: Javascript Regex or Jquery to parse html strings? I have some texts returned by Google Maps, I would like to remove the div tags, (replacing them by <br /> would be the perfect deal 'Turn <b>right</b> onto <b>Route de Sospel/D2566</b> <div style="font-size:0.9em">Continue to follow D2566</div> <div style="font-size:0.9em">Go through 6 roundabouts</div>' => 'Turn <b>right</b> onto <b>Route de Sospel/D2566</b><br /> Continue to follow D2566<br />Go through 6 roundabouts' I don't know which solution would be better either find the appropriate regex, might be hard, but more performant than evaluating this string with $() Jquery and them find('div').text() inside ... thanks for your advices (or sample code) A: Assume your content was like this: <div id="content"> Turn <b>right</b> onto <b>Route de Sospel/D2566</b> <div style="font-size:0.9em">Continue to follow D2566</div> <div style="font-size:0.9em">Go through 6 roundabouts</div> <div>​ This should work, just replace the #content selector according to how you get your data: ​$("#content​​​​​​​​​ div").each(//get all div's inside #content function(i,el) {//i is an index el refers to each element. $(el).replaceWith("<br/>" + $(el).text()); }//replace the element with the text of each element );​​​​​​​​ //alert($("#content").html()); ​See working demo: http://jsfiddle.net/rYeUH/
{ "pile_set_name": "StackExchange" }
Q: timeout method can't break executing in Completable.fromAction() I discovered an error with method .timeout() in Completable, created by method .fromAction(): Completable.fromAction(() -> { System.out.println("start time: " + timeString()); Thread.sleep(10_000); }) .timeout(3, TimeUnit.SECONDS) .onErrorComplete() .blockingAwait(); System.out.println("after time: " + timeString()); Code inside the brackets executes 10 seconds, timeout set on 3 seconds. However, executing finishes only after 10 seconds. This is output of program: start time: 14:55 after time: 15:05 Process finished with exit code 0 Question: why executing breaks not after 3 seconds and how to fix it? A: Try subscribeOn(Schedulers.io()) after fromAction. timeout can't interrupt the main thread but it can interrupt tasks running on a Scheduler.
{ "pile_set_name": "StackExchange" }
Q: Recycler View not showing jason data in kotlin here is my main class where i'm adding json data in ArrayList using volley. Toast show the json data but array does not show any data. i'm trying to solve my error from last 3 days i also read many questions on stack but i have no solution for this please help me var item = ArrayList<dumy_item_list>() var url = "https://apps.faizeqamar.website/charity/api/organizations" var rq: RequestQueue = Volley.newRequestQueue(this) var sr = StringRequest(Request.Method.GET, url, Response.Listener { response -> var jsonResponse = JSONObject(response) var jsonArray: JSONArray = jsonResponse.getJSONArray("data") for (i in 0..jsonArray.length() - 1) { var jsonObject: JSONObject = jsonArray.getJSONObject(i) var name = jsonObject.getString("name") val data = dumy_item_list() data.setName(jsonObject.getString(name)) item.add(data) Toast.makeText(applicationContext, "NGO Name is : $name", Toast.LENGTH_LONG).show() } }, Response.ErrorListener { error -> Toast.makeText(applicationContext, error.message, Toast.LENGTH_LONG).show() }) rq.add(sr) var away_recycler = findViewById<RecyclerView>(R.id.away_recycler) var adaptor = custom_adopter(item, applicationContext) away_recycler.layoutManager = GridLayoutManager(applicationContext, 1) away_recycler.adapter = adaptor } here is my adapter class wher i'm using getName() function class custom_adopter(data: ArrayList<dumy_item_list>, var context: Context) : RecyclerView.Adapter<custom_adopter.viewHolder>() { var data: List<dumy_item_list> init { this.data = data } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): custom_adopter.viewHolder { var layout = LayoutInflater.from(context).inflate(R.layout.dumy_item, parent, false) return viewHolder(layout) } override fun onBindViewHolder(holder: custom_adopter.viewHolder, position: Int) { holder.tv_dummy_name_donnor.text = data[position].getName() holder.card.setOnClickListener { var intent = Intent(context, ngosProfile::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK startActivity(context, intent, null) } } override fun getItemCount(): Int { return data.size } class viewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { internal var tv_dummy_name_donnor: TextView internal var card: CardView init { tv_dummy_name_donnor = itemView.findViewById(R.id.tv_dummy_name_donnor) card = itemView.findViewById(R.id.card) } } } A: follow this code this work for me. (var adaptor = custom_adopter(item, applicationContext) away_recycler.adapter = adaptor progressBar2?.visibility = View.INVISIBLE ) singe the value to adaptor after the loop. class MainActivity : AppCompatActivity() { var progressBar2:ProgressBar?=null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) var item = ArrayList<dumy_item_list>() var progressBar2 = findViewById<ProgressBar>(R.id.progressBar2) var away_recycler = findViewById<RecyclerView>(R.id.away_recycler) away_recycler.layoutManager = GridLayoutManager(applicationContext, 1) var url = "https://apps.faizeqamar.website/charity/api/organizations" var rq: RequestQueue = Volley.newRequestQueue(this) var sr = StringRequest(Request.Method.GET, url, Response.Listener { response -> var jsonResponse = JSONObject(response) var jsonArray: JSONArray = jsonResponse.getJSONArray("data") for (i in 0..jsonArray.length() - 1) { var jsonObject: JSONObject = jsonArray.getJSONObject(i) var name = jsonObject.getString("ngo_name") var about = jsonObject.getString("ngo_desc") item.add(dumy_item_list(name,about)) } var adaptor = custom_adopter(item, applicationContext) away_recycler.adapter = adaptor progressBar2?.visibility = View.INVISIBLE }, Response.ErrorListener { error -> }) rq.add(sr) }
{ "pile_set_name": "StackExchange" }
Q: How can I extend the life of steel wool used for cleaning? How can I prevent or reduce the rate of rusting for a piece of steel wool used for cleaning things like greasy pots and pans? If I use it once and then put it away somewhere, it is usually beginning to have rust the next time I take it out to use. A: One way of extending the lifespan of steel wool is to put it in a ziplock bag and then put it inside the freezer. The ziplock bag reduces the oxygen it is exposed and prevents it from touching anything else in the freezer, while the freezer's low temperature reduces the rate at which it oxidizes further. Whenever you need to use it, just take it out of the freezer and the bag, clean it a bit after using it, and then put it back in the bag and in the freezer. A: I've never tried this, but you could dry it thoroughly with a blow dryer before you put it again. That should remove all the water from it and limit or prevent rusting.
{ "pile_set_name": "StackExchange" }
Q: Looking for a specific Harry Potter fanfiction: Voldemort as ghost, then Harry's "twin" Hope that you folks can help. The title and the author completely elude me but it's about how Lord Voldemort became a ghost after the events of Halloween 1981 and stalked Harry eventually regaining his body due to the blood wards on the Dursley's house. He then sets up a whole persona as Harry's twin (which included going to America) and eventually manipulates his way to the top of the wizarding world. It's a great story and I hope you can help me find it. A: Welcome to Stack exchange. I know of a couple of similar fanfictions, but I think the one that describes it best is "Yes, I am Harry's brother" by Ynyr. It fits your mould perfectly, including Voldemort (calling himself Vito) going to America and him sitting as the Supreme Mugwump of the ICW as well as the Head of DMLE.
{ "pile_set_name": "StackExchange" }
Q: Does it make sense to map a VLAN to each LAN? I saw a picture of a network-structure with VLANs in it: Why would somebody structure their network like this? Does this even make sense? I mean, they are in a different LAN, why then mapping a VLAN to each one? A: Using VLANs is like breaking a switch into multiple unconnected switches. On a single switch, no hosts on a VLAN will ever see any traffic for a different VLAN. Traffic must pass through a router, where it can be controlled, to get from one VLAN to a different VLAN. There are many reasons to use VLANs. One is that switches will flood unknown unicast traffic, and broadcast and multicast traffic is sent to all the other interfaces. Someone with bad intentions could be snooping on that traffic for other networks if the switch wasn't broken into VLANs. With VLANs, that type of traffic is restricted to interfaces configured for the VLAN.
{ "pile_set_name": "StackExchange" }
Q: Java roman to integer : null pointer Anyone knows what is wrong with my pointer (value)? Exception in thread "main" java.lang.NullPointerException My program: import java.util.LinkedHashMap; public class Solution { private static LinkedHashMap<String, Integer> romanToNum = new LinkedHashMap<String, Integer>(); static{ romanToNum.put("M", 1000); romanToNum.put("D", 500); romanToNum.put("C", 100); romanToNum.put("L", 50); romanToNum.put("X", 10); romanToNum.put("V", 5); romanToNum.put("I", 1); } public int romanToInt(String s) { int sum = 0; char prev = '#'; for(int i = s.length()-1; i >= 0; i--){ char ch = s.charAt(i); ***int value = romanToNum.get(ch);*** if(value < sum && ch != prev){ sum -= value; }else{ sum += value; } prev = ch; } return sum; } } A: Your map is of type <String, Integer>, but you are using char primitives as the keys (for lookup): char ch = s.charAt(i); ***int value = romanToNum.get(ch);*** These get autoboxed to Character objects, which are not compatible with Strings. Thus, as others have noted, your map returns a null Integer, which gets auto-unboxed to a primitive int, and it is this operation which causes NPE to be thrown. Solution 1: Make the map of type <Character, Integer> instead. Solution 2: Change the offending line to: ***int value = romanToNum.get(String.valueOf(ch));*** A: The problem is that you are calling get using a char, which is auto boxed to a Character. char ch = s.charAt(i); int value = romanToNum.get(ch); Since no data is actually stored with Character keys, a null is returned. As others have pointed out, the null Integer is auto unboxed to an int, resulting in a NullPointerException.
{ "pile_set_name": "StackExchange" }
Q: Mootools slide not working in dropdown I have an html5 page with a dropdown menu using mootools. It's working if I use the hide() and show() functions. But, I want the menu's to slide in and out, like this: var m = e.getElement(".dropdown-menu, .sidebar-dropdown-menu"); if (e.hasClass('active')) { m.hide(); e.removeClass('active'); } else { m.show(); e.addClass('active'); } Instead of hide and show I want slideIn and slideOut: var m = new Fx.Slide(e.getElement(".dropdown-menu, .sidebar-dropdown-menu")); if (e.hasClass('active')) { m.slideOut(); e.removeClass('active'); } else { m.slideIn(); e.addClass('active'); } Working example: http://jsfiddle.net/wzzeZ/ Not working: http://jsfiddle.net/37V53/1/ It's not throwing errors; where do I look to fix it? A: There are a few things going on here. First of all, you're not seeing any errors because there are none. If you litter the code with console.log() calls, they all run. It's a style issue that's preventing the menus from displaying. The FX.Slide Class in Mootools doesn't seem to explicitly set the 'display' property of the element you're sliding to block. You still need to call .show() for it to work. Next, if you check out the docs for FX.Slide, you'll notice that it creates a wrapper element to do the slide effect (the container is needed for the height animation, overflow: hidden, etc.) Unfortunately that seems to be messing with the positioning of the menu, which is positioned relatively to its containing element - but the containing element has height and overflow: hidden styles which then hide the menu (not to mention, even if you could see it, it's in the right place). To see what I'm talking about check out this updated Fiddle here: http://jsfiddle.net/37V53/2/ If you run that in Firefox with Firebug, and you hover your cursor over the element that's logged to the console, you'll see Firebug's blue hilight appearing where your element actually is being displayed - in the middle of the window, and hidden from view. This is a combination of assumptions made in the MooTools Classes you're using working against each other; You'll probably be better off writing your own (simple) slide-out script using FX.Tween rather than FX.Slide. I created a sample of how to do this based on the original Fiddle (that works) - http://jsfiddle.net/LkLgk/ Trick is to show the element to the browser but not the user (by setting visibility: hidden before display: block, grab the height, set height to 1px, visibility back to visible, then tween the height to the previously detected value. Hope that points you in the right direction; remember, when in doubt, console.log everything!
{ "pile_set_name": "StackExchange" }
Q: Powershell Expanding Variables in Where $_ -like $Var Ok I am trying to do something like the following: Simplified Example: $Var = "MyProduct*MyProduct" $List += "MyProduct 11 MyProduct" $List += "YourProduct 11 YourProduct" $List += "SomethingElse" $NewVar = $List | Where {$_ -like "$Var"} I want the "*" in $Var to be expanded then check if it is -like "$_" so that it will recognize there is a wildcard in the var and get results based on that.. Is there any way to do that? A: $list is not an array, each time you add to it you are actually concatenating to it. You can start with a single item array, using the unary comma operator (this is just one way to do it), now each addition will add a new array item: PS> $List = ,"MyProduct 11 MyProduct" PS> $List += "YourProduct 11 YourProduct" PS> $List += "SomethingElse" PS> $list MyProduct 11 MyProduct YourProduct 11 YourProduct SomethingElse PS> $List -like $var MyProduct 11 MyProduct
{ "pile_set_name": "StackExchange" }
Q: How to use props type from a styled component? Sometimes I have a styled component like: import styled from 'styled-components'; const StyledButton = styled.button; And then I need to use it like this export default function CloseButton() { return <StyledButton>Close</StyledButton> } And use it like <CloseButton />. But what if I need to use it like <CloseButton onClick={doSomething} />? I would have to change my CloseButton component to: type Props = { onClick: () => void; } export default function CloseButton(props: Props) { return <StyledButton onClick={props.onClick}>Close</StyledButton> } This sucks. So a better way would be just to pass all the props like: export default function CloseButton(props: any) { return <StyledButton {...props}>Close</StyledButton> } Thats clean and simple... but how to avoid any type of props and tell typescript to use props from StyledButton? A: It seems that this: export default function CloseButton(props: typeof StyledButton.defaultProps) { return <StyledButton {...props}>Close</StyledButton> } is working almost perfect. It does show HTML attributes of a <button> element, although it does not show StyledComponents props like as and forwardAs
{ "pile_set_name": "StackExchange" }
Q: How to invoke a action on a link button click in ASP.Net MVC app? I want to invoke an action (which is in HomeController) on link button click? The link button is present on a empty View which I have added to Views which is not a stronly typed view? regards, kapil A: If you want to use a button then it needs its own form and the form helper method needs to show the controler and action you are using. <% using (Html.BeginForm("ActionName", "ControllerName" )) { %> <input type="submit" value="Run Action" /> <% } %> Or, if you want to just use a text link then you can use this: <%= Html.ActionLink("Link text", "ActionName", "ControllerName"); %> If your view is for the same controler as the action you want to direct to then you do not need to specify the controller name. If you wish to pass extra info to the action method you can pass an anonymous object like this: <%= Html.ActionLink("Link text", "ActionName", "ControllerName", new {variableName="a value", anotherVariableName=78}); %>
{ "pile_set_name": "StackExchange" }
Q: How do I get a list of control qubits from Q# operations when tracing the simulation in C#? I want to write code that prints out the controls of each operation executed during a simulation in Q#. For example this code prints the control counts: var qsim = new QCTraceSimulator(config); qsim.OnOperationStart += (op, arg) => { Console.WriteLine($"{Controls(op, arg).Length"}); } I'm having trouble writing the Controls function, which extracts a list of qubits being used as controls. When the operation is uncontrolled, or controlled by 0 qubits, the returned array should be of length 0. The issue I'm running into is that the type and layout of arg.Value varies from operation to operation, even after conditioning on op.Variant being OperationFunctor.ControlledAdjoint or OperationFunctor.Controlled. I can handle individual cases by inspecting the types, but I keep running into new unhandled cases. This indicates there's probably a "correct" way to do this that I'm missing. In short, how do I implement this function: object[] Controls(ICallable op, IApplyData arg) { ??? } By "controls" I always mean the cs in Controlled Op(cs, ...). The same operation may have different controls when expressed in different ways. For example, the controls list of Controlled Toffoli(a, (b, c, d)) is the list [a] whereas the controls list of Controlled X([a, b, c], d) is the list [a, b, c]. A further example: the controls list of Toffoli(b, c, d) is [], even though normally one might think of the first two arguments as the controls. It is of course expected that within Toffoli(b, c, d) there may be a sub-operation Controlled X((b, c), d) where the controls list is [b, c]; I'm not thinking of controls as some kind of absolute concept that is invariant as you go down through layers of abstraction. A: arg.Value contains the actual tuple that the controlled operation receives at runtime. It's a two item tuple in which the first item is the control qubits, and the second another tuple with the arguments the operation normally expects, so in your case you are only interested in the first item of this tuple. Overall, arg.Value can be anything, thus it has object as type, but fear not, using a little bit of C#'s reflection is easy to retrieve its content. The implementation you are looking for is this: static Qubit[] Controls(ICallable op, IApplyData arg) { // Uncontrolled operations have no control qubits. if (op.Variant != OperationFunctor.Controlled && op.Variant != OperationFunctor.ControlledAdjoint) { return new Qubit[0]; } // Get the first item of the (controls, args) tuple. dynamic v = arg.Value; QArray<Qubit> ctrls = v.Item1; return ctrls.ToArray(); } Notice the array of Qubits is encapsulated in something called a QArray<Qubit>, QArray is the data structure we use in simulation for all Q# arrays.
{ "pile_set_name": "StackExchange" }
Q: Is the origin of the term "blackleg" racist? A blackleg is defined as: a person who continues working when fellow workers are on strike When did this term originate? Does it's origin have racist connotations? A: Its etymology seems to be without racist connotations; at least according to the website for National Coal Mining Museum for England: Blackleg Term for a worker who breaks a strike and continues working. The name comes from working miners trying to hide the fact that they had been working could be found out if their trousers were rolled up: they would have black legs. See scab, strike breaker. — The 1984-5 Miners Strike Resource On the other hand, wordsmith.org says noun: 1. One who works while other workers are on strike. 2. A swindler, especially in games such as gambling. 3. One of various diseases of plants or cattle. ETYMOLOGY: It’s unclear how the term came to be employed for a strikebreaker. Earliest documented use: 1722. ... so it's hard to be 100% sure! A: There are different assumptions about the origin of the term used to refer to strikers who cheat going to work. According to the following, the meaning derives from the bird rook known for its rapacious appetite and its black legs: The expression blackleg originated from the bird rook. As we all know, this bird is black in colour and has got black legs. Rooks are very cunning and they know how to steal food. Needless to say, few people like them. Even today, the term rook is sometimes used to refer to a person who takes advantage of gullible individuals. Since rooks have black legs, cheats are also called blacklegs. As time went by, this expression began to be used to refer to workers who cheat by going to work when their fellow employers are on strike. (English Grammar) Another assumption is that the expression originated among coal mine strikers: The term is said to have come from strikes in the coal mines. Those who were on strike had washed and brushed up after their last trip down the mine and therefore anyone covered in coal dust was a strike-breaker - a blackleg. The derogatory term scab is also used for such people. It is not a direct synonym of strike-breaker since a blackleg is specifically someone who works at a job while his colleagues are on strike. (Words, Words and Phrases) A: From yet another source (unfortunately unavailable): 'Blackleg' dates from the very early 1700s. Eric Partridge gives alternative uses and origins. By 1722 it is certainly being used as a description of a disease affecting the legs of sheep and cattle. Tempting though it is to suggest that the earliest organised wage workers, the wool combers, who were noted for trade union militancy, used the term there is no direct evidence that this was so. Another version of its origins has it as a gaming term, dating from 1771. According to this view, blacklegs were firstly "turf-swindlers", the name coming from a fashion amongst them for wearing a certain kind of black boot. Another, related possibility is that gamecocks, used in the then very popular `sport' of cock-fighting, were invariably the possessors of black legs. Yet another version of its origin is supposed to be from the mining industry. The term was certainly used in miners' songs of the 1830's. (See A L Lloyd's "Come All Ye Bold Miners - ballads and songs of the coalfields" [1978] ", published by Lawrence and Wishart, for various examples.) This raises the question of whether it is a word special to the mining industry in origin. For this was the period when the word "blacksheep" was current. It has often been suggested that in the context of the coal industry the word `blacklegs' has a double edge to it. For, in the days before pithead baths, a working miner in a strike situation could easily be found by the simple expedient of lifting his trouser leg to discover his own leg blackened by coal dust! This seems a little fanciful, whilst there is no academic backing for the notion. After all, mining strikes took place in closed communities where there was little chance of discovering a wayward spirit. There could however be some derisory value involved here and the sporting origin - especially of cock fighting - would fit the social milieu of the collier better. From this account it may be readily seen that no racist intent or connotation is involved in the term "blackleg", arising from the use of the word `black' as a negative force. Nonetheless, modern dislike of the term arises from the method whereby the word "black" is frequently used in this way- as in black arts or witchcraft, black mood, black day, black outlook, etc. etc. Sidenote: In Swedish it is a similar word word for this "svartfot" (black foot), probably translated from the English word. Funnily enough(?) there are other racist sounding words for similar issues that aren't either. "Gulingar" (Yellows), comes from employer friendly unions that had was called The Yellow Union. And we also have "bruntungor" (brown tounges) which is a euphemism for "kiss ass" as you might imagine why.
{ "pile_set_name": "StackExchange" }
Q: Remove dict from list of dict if key and value doesnt match with other dict I have a list of dictionaries and I want to filter it by values from other dictionary. orig_list = [{"name":"Peter","last_name":"Wick","mail":"[email protected]","number":"111"}, {"name":"John","last_name":"Hen","mail":"[email protected]","number":"222"}, {"name":"Jack","last_name":"Malm","mail":"[email protected]","number":"542"}, {"name":"Anna","last_name":"Hedge","mail":"[email protected]"}, {"name":"Peter","last_name":"Roesner","mail":"[email protected]","number":"445"}, {"name":"Tino","last_name":"Tes","mail":"[email protected]","number":"985"},] expected result example 1: filter = {"name":"Peter"} orig_list[{"name":"Peter","last_name":"Wick","mail":"[email protected]","number":"111"}, {"name":"Peter","last_name":"Roesner","mail":"[email protected]","number":"445"}] expected result example 2: filter = {"name":"Peter","number":"445"} orig_list[ {"name":"Peter","last_name":"Roesner","mail":"[email protected]","number":"445"}] The filter can have multiple keys. possible keys are(name,last_name,number). Basically what I want, is to go through the list of dict and check every dict if the dict contains key from given filter and if it does, check if the key values match. If they dont, remove the whole dict from the list of dict. The final list does not have to be the orig_list. It can be a new list. So its not mandatory to delete dicts from the orig_list. The dicts can be also copied to new list of dicts. A: You can use list comprehension: orig_list = [{"name":"Peter","last_name":"Wick","mail":"[email protected]","number":"111"}, {"name":"John","last_name":"Hen","mail":"[email protected]","number":"222"}, {"name":"Jack","last_name":"Malm","mail":"[email protected]","number":"542"}, {"name":"Anna","last_name":"Hedge","mail":"[email protected]"}, {"name":"Peter","last_name":"Roesner","mail":"[email protected]","number":"445"}, {"name":"Tino","last_name":"Tes","mail":"[email protected]","number":"985"},] filter_by = {"name":"Peter"} result = [dic for dic in orig_list if all(key in dic and dic[key] == val for key, val in filter_by.items())] print(result) Output: [ { "name": "Peter", "last_name": "Wick", "mail": "[email protected]", "number": "111" }, { "name": "Peter", "last_name": "Roesner", "mail": "[email protected]", "number": "445" } ] For filter_by = {"name":"Peter","number":"445"} you get: [ { "name": "Peter", "last_name": "Roesner", "mail": "[email protected]", "number": "445" } ]
{ "pile_set_name": "StackExchange" }
Q: Receiving 400 (Bad Request) on jQuery ajax post to Product Controller I am receiving 400 (Bad Request) on jQuery ajax post to Product Controller. I am trying to post an array to my database. Path attr <a id="store-product" data-path="{{ path_for('product.design', {sku: design.sku}) }}">Submit</a> Ajax code /** Call to the Fancy Product Designer **/ fpd = new FancyProductDesigner(_container, pluginOpts); var _storeProduct = jQuery('#store-product'); _storeProduct.click(function() { var url = _storeProduct.attr("data-path"); var productViews = fpd.getProduct(); /******* //console.log(productViews); //Works Fine upto here with the log array below //Array[5]0: Object1: Object2: Object3: Object4: Objectlength: 5__proto__: Array[0] *******/ jQuery.ajax({ url: url, type: "post", data: JSON.stringify({ action: 'store', views: productViews }), contentType: "application/json; charset=utf-8", success: function (data) { if(parseInt(data) > 0) { alert('Product with ID ' + data + ' stored!'); } else { alert('Error: ' + data + ''); } } }); }); Not sure what i have wrong here. Controller Code public function design($sku, Request $request, Response $response) { $design = Design::where('sku', $sku)->first(); if($request->getParam('action') == 'store') { $views = $request->getParam('views'); $design->update([ 'views' => $views ]); return $response->withRedirect($this->router->pathFor('product.get', [ 'sku' => $sku, ])); } } UPDATE Apache Access Log ::1 - - [18/Jan/2017:16:27:25 +0700] "POST /projects/GolfBag/public/golf-bags/design/2563901 HTTP/1.1" 400 18 "http://localhost/projects/GolfBag/public/golf-bags/2563901" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36" Routes $app->get('/golf-bags/{sku}', ['Base\Controllers\ProductController', 'getProducts'])->setName('product.get'); $app->post('/golf-bags/design/{sku}', ['Base\Controllers\ProductController', 'design'])->setName('product.design'); A: After a bit of digging i found the issue was that the CSRF token is not applied to the post data
{ "pile_set_name": "StackExchange" }
Q: Cant create excel sheet with version 2003 using PHP I am trying for create excel sheet with the version 2003,using php But i dont get .Wth xlsx extension in my code i dont get excel sheet.I changed the version to xls in my code ,got excel sheet but cant open that file.2003 is installed in system.Any body help me please.. My code i given below. <?php error_reporting(E_ALL ^ E_NOTICE); session_start(); //error_reporting(E_ALL); ini_set('display_errors', TRUE); ini_set('display_startup_errors', TRUE); date_default_timezone_set('Europe/London'); define('EOL',(PHP_SAPI == 'cli')? PHP_EOL : '<br />'); require_once("../../../codelibrary/inc/variables.php"); require_once("../../../codelibrary/inc/functions.php"); /** Include PHPExcel */ require_once '../../Classes/PHPExcel.php'; // Create new PHPExcel object $objPHPExcel = new PHPExcel(); $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A2:E2'); $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A2','Sales Register'); $objPHPExcel->setActiveSheetIndex(0)->getStyle('A2')->getAlignment()-> setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $styleArray = array('font' => array('bold' => true)); $objPHPExcel->setActiveSheetIndex(0)->getStyle('A2')-> applyFromArray($styleArray); $objPHPExcel->getActiveSheet()->getStyle("A2:D2")->getFont()->setSize(16); $objPHPExcel->setActiveSheetIndex(0) ->setCellValue('A4', 'Sl No') ->setCellValue('B4', 'Date') ->setCellValue('C4', 'Ledger Account') ->setCellValue('D4', 'Debit Amount') ->setCellValue('E4', 'Credit Amount'); $styleArray = array('font' => array('bold' => true)); $objPHPExcel->setActiveSheetIndex(0)->getStyle('A4')-> applyFromArray($styleArray); $objPHPExcel->setActiveSheetIndex(0)->getStyle('B4')-> applyFromArray($styleArray); $objPHPExcel->setActiveSheetIndex(0)->getStyle('C4')-> applyFromArray($styleArray); $objPHPExcel->setActiveSheetIndex(0)->getStyle('D4')-> applyFromArray($styleArray); $objPHPExcel->setActiveSheetIndex(0)->getStyle('E4')-> applyFromArray($styleArray); //ALIGN HEADING TO THE CENTER $objPHPExcel->setActiveSheetIndex(0)->getStyle('A4')-> getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $objPHPExcel->setActiveSheetIndex(0)->getStyle('B4')-> getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $objPHPExcel->setActiveSheetIndex(0)->getStyle('C4')-> getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $objPHPExcel->setActiveSheetIndex(0)->getStyle('D4')->g etAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $objPHPExcel->setActiveSheetIndex(0)->getStyle('E4')-> getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); //FOR SETTING WIDTH OF EACH COLUMN $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5); $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15); $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15); $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15); $sl_no=1; $r=5; $sql = "SELECT * FROM customer"; $qry = mysql_query($sql); if(mysql_num_rows($qry)>0) { while($res=mysql_fetch_assoc($qry)) { $cell1 = 'A'.$r; $cell2 = 'B'.$r; $cell3 = 'C'.$r; $cell4 = 'D'.$r; $cell5 = 'E'.$r; $objPHPExcel->getActiveSheet()->setCellValue($cell1,$sl_no); $objPHPExcel->getActiveSheet()->setCellValue($cell2,$res['name']); $objPHPExcel->getActiveSheet()->setCellValue($cell3,$res['address']); $objPHPExcel->getActiveSheet()->setCellValue($cell4,$res['email']); $objPHPExcel->getActiveSheet()->setCellValue($cell5,$res['supp_id']); $sl_no++; $r++; } } / /Redirect output to a client's web browser (Excel2007) header('Content-Type: application/vnd.openxmlformats- officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="Sales Register.xlsx"'); header('Cache-Control: max-age=0'); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007'); $objWriter->save('php://output'); exit; ?> A: As a standard install, MS Excel 2003 reads and writes BIFF-format files (.xls extension), though there is an optional "compatibility toolkit" plug-in that also allows it to read/write OfficeOpenXML-format files (.xlsx extension). PHPExcel's Excel5 Writer creates BIFF-format files; the Excel2007 Writer creates OfficeOpenXML-format files. If you're generating output for MS Excel 2003, then you should use the Excel5 Writer, unless you know that the "compatibility toolkit" plug-in has been installed for the MS Excel 2003 users who you're creating the files for
{ "pile_set_name": "StackExchange" }
Q: Performance issues running Ubuntu 10.04 as guest OS in VmWare with Windows 7 host? I have (portable) Virtualbox installed on a USB key running on a 64-bit Windows 7 host. I installed 32 bit Ubuntu 10.04 as a guest OS. During spikes in processor usage on the guest OS (based on looking at top), the Ubuntu virtual box freezes up for 5-10 seconds. The guest becomes unresponsive with the VirtualBox window showing as "not responding". There seems to maybe be a correlation between this behavior and network accesses. I've experimented with the number of CPUs allocated to the virtual box, added and removed RAM, and adding video memory -- all to no avail. I have not attempted disabling or changing the processor level virtualization (VT-x). I'm wondering if there's anything particular about Ubuntu 10.4 that might be impacting this? Should I have installed 64-bit Ubuntu (or should it matter!?). Is there a VirtualBox setting I'm missing that would improve my experience? Any help is appreciated. A: I suppose that running VirtualBox on a USB key is the problem. USB keys have slower write times than harddrives. So what happens is that the Ubuntu VM writes data to it's disk (which is also stored on the USB key I suppose) and the data can't be written fast enough on the key so the VM hangs. If you copy the Ubuntu hard disk image to your harddrive and use this one to boot Ubuntu are you experiencing the same problems?
{ "pile_set_name": "StackExchange" }
Q: How to control DynamicResource implementation in C# In my program I would like to implement a DynamicResource from code-behind. Right now I am binding the Content of a Label to a string property in my Data Model... <Label Content="{Binding DataModel.StringValue}" ... /> Following this question, I have implemented the string in my Data Model like so: private string _stringValue = (string)Application.Current.Resources["nameOfResource"]; public string StringValue { get { return _cartsInSystem; } set { _cartsInSystem = value; NotifyPropertyChange(() => CartsInSystem); } } I would like to make it so that every time the user changes the Resource Dictionary, this string value updates with the new value. I am trying to achieve the same effect as something like this: <Label Content="{DynamicResource nameOfResource}" ... /> Please let me know what I am doing wrong, and how I might correctly implement something like this. UPDATE 1: As requested by @HighCore, this is an example of my code where I only have access to string values from code-Behind (or C# class) (This is part of a ViewModel of a TreeView in my MainWindow) //The "DisplayNames" for these nodes are created here and not accessible through xaml. //This is because the xaml window has access to this code through it's itemsSource private HierarchicalVM CreateCartsNode() { return new HierarchicalVM() { DisplayName = "Carts", Children = { new CartConnection() { ConnectionDataModel = new CartConnectionModel(), DisplayName = "Cart Connection" }, new HierarchicalVM() { DisplayName = "Cart Types", Children = { CreateCartType( new CartConfigModel() { DisplayName = "Default" }, new CartIO_Model() ), }, Commands = { new Command(OpenAddCart) {DisplayName = "Add..."} } } } }; } This is the xaml of the above TreeView: <!-- Tree view items & Functions --> <TreeView ItemsSource="{Binding DataTree.Data}" ... /> Update 2: I have another perfect example of my problem... I have a comboBox that has it's itemsSource bound to an ObservableCollection in my Data Model. Like so: private ObservableCollection<string> _objCollection; private string _notUsed = "Not Used"; private string _stop = "Stop"; private string _slow = "Slow"; public DataModel() { ObjCollection = new ObservableCollection<string>() { _notUsed, _stop, _slow }; } public ObservableCollection<string> ObjCollection {...} xaml: <ComboBox ItemsSource="{Binding DataModel.ObjCollection}" ... /> If I want to make it so that the items in this comboBox change when the resource dictionary is changed, it looks like I'll need to handle it in C# rather than xaml. A: After OP's UPDATE 2 and having a chat with him for a different question, I understood he was trying achieve localisation for his application. He would change Resource Dictionaries (for different languages) on the fly, and he wanted his C# code re-read/load values from Application.Current.Resources. APPROACH ONE After you changing the Resource Dictionary, You could use something like EventAggregator/Mediator to let other parts of the application (including ViewModels) know about Resource Dictionary change, and they respond to it by re-loading/reading resources/values from Application.Current.Resources APPROACH TWO OP doesn't want to introduce any new dependencies like EventAggregator/Mediator. So, I suggested this second approach. I know, it is not pretty, but here it goes.. You could have a global static event instead of EventAggregator/Mediaotr to let other parts of the application know that you swapped resource dictionary, and they will re-load/read values. Read this answer about potential problems with static events and their subscriptions.
{ "pile_set_name": "StackExchange" }
Q: JXBrowser failed to launch in Ubuntu18.04 I tried to launch the application from JXBrowser in ubuntu 18.04 OS. It is giving the following error. But it is working fine with other versions of Ubuntu. 2019-02-19 21:05:20,407 [Thread-1] ERROR c.m.m.g.w.jxbrowser.JXBrowserHandler - JXBrowser failed to launch. Failed to start IPC process. com.teamdev.jxbrowser.chromium.internal.ipc.IPCException: Failed to start IPC process. at com.teamdev.jxbrowser.chromium.internal.ipc.d.run(SourceFile:208) ~[jxbrowser-6.22.1.jar:6.22.1] at java.lang.Thread.run(Thread.java:748) [na:1.8.0_162] Caused by: java.lang.IllegalStateException: Missing dependendecies have been detected. Check the log for details. at com.teamdev.jxbrowser.chromium.internal.ipc.ExternalChromiumProcessLinux.preProcessRun(SourceFile:3150) ~[jxbrowser-6.22.1.jar:6.22.1] at com.teamdev.jxbrowser.chromium.internal.ipc.ExternalChromiumProcess.doStart(SourceFile:62) ~[jxbrowser-6.22.1.jar:6.22.1] at com.teamdev.jxbrowser.chromium.internal.ipc.ChromiumProcess.start(SourceFile:235) ~[jxbrowser-6.22.1.jar:6.22.1] at com.teamdev.jxbrowser.chromium.internal.ipc.d.run(SourceFile:199) ~[jxbrowser-6.22.1.jar:6.22.1] ... 1 common frames omitted A: JxBrowser 6.22.1 is based on Chromium 64 engine which requires some dependencies installed in the system. The issue should be fixed after running of those commands: sudo apt install libgconf2-4 or sudo apt-get install -f The dependency issue on Linux is fixed in Chromium 67+ versions. We can provide you with a JxBrowser build which includes an updated Chromium engine if you contact us at [email protected]
{ "pile_set_name": "StackExchange" }
Q: i want to sum 6 inputs and set the value to another input with javascript I want to sum 6 inputs and set the value to another input with javascript. https://jsfiddle.net/arispapapro/1qbjd36c/9 <form> <input type="text" name="no301" class="form-control" id="no301" placeholder=""> <input type="text" name="no301" class="form-control" id="no302" placeholder=""> <input type="text" name="no301" class="form-control" id="no303" placeholder=""> <input type="text" name="no301" class="form-control" id="no304" placeholder=""> <input type="text" name="no301" class="form-control" id="no305" placeholder=""> <input type="text" name="no301" class="form-control" id="no306" placeholder=""> <input type="text" name="no307" class="form-control" id="thesum" placeholder="307"> </form> Javascript: var no301 = document.getElementById("no301").value; var no302 = document.getElementById("no302").value; var no303 = document.getElementById("no303").value; var no304 = document.getElementById("no304").value; var no305 = document.getElementById("no305").value; var no306 = document.getElementById("no306").value; var no307 = document.getElementById("no307").value; var sum = no301 + no302 + no303 + no304 + no305 + no306; sum.onchange = function() { thesum.value = sum; } thesum.onchange = function() { sum.value = thesum; } A: Check the fiddle: https://jsfiddle.net/1qbjd36c/13/ $("form .form-control").not("#thesum").on("input", function() { var getSum = 0; $("form .form-control").not("#thesum").filter(function() { if($.isNumeric($(this).val())) return $(this).val(); }).each(function() { getSum+=parseFloat($(this).val()); }); $("#thesum").val(getSum); }); $("form .form-control") A tag and class selector has been utilized to reference the target. not("#thesum") added a not selector in order to avoid the change of input of Resulting TEXT field. on("input", function() { utilized ON-INPUT event, to trigger all input formats, which includes paste of clip text too. .filter(function() { utilized filter function to value only numeric values. getSum+=parseFloat($(this).val());, here use of + indicates summing upon with the previous value to the variable, in other words, recursive change on value, which returns the sum of all iterated values.
{ "pile_set_name": "StackExchange" }
Q: Compilation error with boost on LINUX I just installed the boost library on Linux and written a sample application : #include <iostream> #include <string> #include "boost/date_time/gregorian/gregorian.hpp" int main() { std::string ds("2002-JAN-01"); boost::gregorian::date d(boost::gregorian::from_string(ds)); std::cout<< boost::gregorian::to_simple_string(d) <<std::endl; std::cout<< d<<std::endl; } I am compiling it as gcc -I /home/test/code/thirdParty/boost_1_46_1/ -L /home/test/code/thirdParty/boost_1_46_1/stage/lib/ test.cpp but getting lots of error as: /tmp/ccAfgB8z.o: In function `__static_initialization_and_destruction_0(int, int)': test.cpp:(.text+0xd3): undefined reference to `std::ios_base::Init::Init()' test.cpp:(.text+0xec): undefined reference to `boost::system::generic_category()' test.cpp:(.text+0xf8): undefined reference to `boost::system::generic_category()' test.cpp:(.text+0x104): undefined reference to `boost::system::system_category()' /tmp/ccAfgB8z.o: In function `__tcf_4': test.cpp:(.text+0x2be): undefined reference to `std::ios_base::Init::~Init()' /tmp/ccAfgB8z.o: In function `main': test.cpp:(.text+0x2d5): undefined reference to `std::allocator<char>::allocator()' test.cpp:(.text+0x2e7): undefined reference to `std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&)' test.cpp:(.text+0x2f0): undefined reference to `std::allocator<char>::~allocator()' test.cpp:(.text+0x2fd): undefined reference to `std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)' test.cpp:(.text+0x316): undefined reference to `std::allocator<char>::~allocator()' test.cpp:(.text+0x33e): undefined reference to `std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()' test.cpp:(.text+0x357): undefined reference to `std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()' test.cpp:(.text+0x379): undefined reference to `std::cout' test.cpp:(.text+0x37e): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <char, std::char_traits<char>, std::allocator<char> >(std::basic_ostream<char, std::char_traits<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)' test.cpp:(.text+0x386): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)' test.cpp:(.text+0x38b): undefined reference to `std::basic_ostream<char, std::char_traits<char> >::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&))' test.cpp:(.text+0x394): undefined reference to `std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()' test.cpp:(.text+0x3ad): undefined reference to `std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()' test.cpp:(.text+0x3c2): undefined reference to `std::cout' test.cpp:(.text+0x3cf): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)' test.cpp:(.text+0x3d4): undefined reference to `std::basic_ostream<char, std::char_traits<char> >::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&))' test.cpp:(.text+0x418): undefined reference to `std::locale::locale()' test.cpp:(.text+0x431): undefined reference to `std::locale::~locale()' test.cpp:(.text+0x43d): undefined reference to `std::cout' test.cpp:(.text+0x442): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <char, std::char_traits<char>, std::allocator<char> >(std::basic_ostream<char, std::char_traits<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)' test.cpp:(.text+0x462): undefined reference to `std::locale::~locale()' test.cpp:(.text+0x470): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)' Anyone have any idea? In normal compilation i don't use any std library in the command line option. A: You need to compile C++ code with g++, not gcc.
{ "pile_set_name": "StackExchange" }
Q: Equivalent of \chapter[title]{title} in ConTeXt In LaTeX, one can use \chapter[A]{B}, such that, in the table of contents, "A" appears, but in the actual page where the chapter begins, "B" appears. This allows one to print different text in the table of contents. What is the equivalent of this in ConTeXt? A: \starttext \placecontent \startchapter[title=B,list=A] \input tufte \stopchapter \stoptext
{ "pile_set_name": "StackExchange" }
Q: mariadb varchar 120 characters primary key I have a mariadb (version 10.2.10) table with utf8mb4 enabled. There is a varchar(120) column jobID which uniquely identifies the row. At present, I am using jobID with length of 60 characters(with option to increase in the future). So, I made that into primary key. Now, I have 60K records. So, when I checked the size of the datafile + indexfile using detail given here, its coming as datafile size almost equal to indexfile. Thus, the index file is rising 1:1 as the datafile is rising because of the primary key which I declared. So, I started thinking of adding a integer auto increment primary key as discussed here and make the jobID column as unique key. But the problem of Index file rising 1:1 with the data file and also the reduction in performance of new inserts to the table as the size of table rises (the table will have 20 million records in the coming days) made me confused. What should be the right approach? Thanks in advance. My present create table. CREATE TABLE jobsTable ( `jobId` varchar(100) NOT NULL, `status` varchar(15) NOT NULL, `addedTime` varchar(13) NOT NULL, PRIMARY KEY(`jobId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; A: A PRIMARY KEY is, by definition (in MySQL), UNIQUE. It sounds like you have this: CREATE TABLE ... ... PRIMARY KEY(jobID), UNIQUE(jobID) -- redundant, and a waste of space; DROP it. ... In InnoDB, the data and the PK coexist ("clustered"). But every "secondary" key takes up more space. If that does not explain it, then ... Can't answer without seeing SHOW CREATE TABLE. And what does a sample jobID look like? Depending on the number of secondary keys, and what they are like, I may recommend for or against using an AUTO_INCREMENT PK.
{ "pile_set_name": "StackExchange" }
Q: How to detect when arrow key down is pressed / C# WPF I'm working with WPF C# app, and I need to implement some action when arrow key down on keyboard is pressed, for example: private void Window_KeyDown(object sender, KeyEventArgs e) { // Here I gotta check is that arrow key down which invoked this event.. then call a method DoSomething(); } I simply can not figure out in wpf how to detect a arrow key down .. Any kind of help would be great! Thanks ! A: The KeyEventArgs hold information about the pressed key in the KeyEventArgs.Key property and so you can check for the down arrow key by checking if e.Key is equal to Key.Down, which is the enumeration value for the arrow down key. private void Window_OnKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Down) // The Arrow-Down key { DoSomething(); } }
{ "pile_set_name": "StackExchange" }
Q: iOS - use device camera to recognise a 3D object I'm developing an app that makes use of an augmented reality feature whereby the user can point the device's camera at a point of interest such as a building and get information on that building. Are there any frameworks out there for the iOS SDK that allow for this functionality? I've looked at the Vuforia framework, however this doesn't seem to support this feature. If anyone could point me in the right direction I'd appreciate it. Thanks in advance! A: If you can put some markers on the buildings, you can try ARToolKit. If you cannot, it will be a much more difficult problem. If the buildings look similar, it is impossible to distinguish them by their appearance. If they look very different, you may try feature detection techniques such as SIFT or SURF. GPS information will make your job easier, if you know the exact location of these buildings.
{ "pile_set_name": "StackExchange" }
Q: Ensure one property is not empty in JSON schema For the given schema below, is it possible to ensure that at least one property contains a value (ie, minLength is 1): { "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "fundRaiseId": { "type": "string" }, "productTypeId": { "type": "string" }, "businessLineId": { "type": "string" } } } So this would pass validation: { "fundRaiseId": "x" } And this would fail as no values are present: { "fundRaiseId": "", "productTypeId": "", "businessLineId": "" } A: Is it a requirement that you allow the values to be empty? You can write a much cleaner schema if you requiring that all the strings are non-empty. { "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "fundRaiseId": { "$ref": "#/definitions/non-empty-string" }, "productTypeId": { "$ref": "#/definitions/non-empty-string" }, "businessLineId": { "$ref": "#/definitions/non-empty-string" } }, "anyOf": [ { "required": ["fundRaiseId"] }, { "required": ["productTypeId"] }, { "required": ["businessLineId"] } ], "definitions": { "non-empty-string": { "type": "string", "minLength": 1 }, } } A: I would try something like { "allOf": [{ "type": "object", "properties": { "fundRaiseId": { "type": "string" }, "productTypeId": { "type": "string" }, "businessLineId": { "type": "string" } } }, { "anyOf": [{ "properties": { "fundRaiseId": { "$ref": "#/definitions/nonEmptyString" } } }, { "properties": { "productTypeId": { "$ref": "#/definitions/nonEmptyString" } } }, { "properties": { "businessLineId": { "$ref": "#/definitions/nonEmptyString" } } }] }], "definitions": { "nonEmptyString": { "type": "string", "minLength": 1 } } } Explanation: the JSON to be validated should conform to 2 root-level schemas, one is your original definition (3 string properties). The other one contains 3 additional sub-schemas, each defining one of your original properties as non-empty string. These are wrapped in an "anyOf" schema, so at least one of these should match, plus the original schema.
{ "pile_set_name": "StackExchange" }
Q: When did Black Canary get her "Canary Cry"? In which episode of the Arrow does the Black Canary get her "cry"? Or was it a Flash episode? I seemed to have missed this one. A: The current Black Canary no longer has a "Canary Cry" device; she's a metahuman who can make that sound naturally. The device that Laurel used, called the Canary Cry, was given to her on an episode of The Flash called "Who is Harrison Wells?" (S01E19). This is a minor crossover, where Joe and Cisco go to Starling City to dig up information on Harrison Wells, whom they are beginning to suspect is hiding something. Cisco takes one of Sara Lance's "sonic grenades" and converts it into the Canary Cry for Laurel, and gives it to her at the end of that episode. The "sonic grenades" are devices Sara was shown using from the very first episode she appeared in. I don't think we are told where she got them, but they are the kind of slightly-exotic weapon you might expect the League of Assassins to have. Sara had multiples of these, and typically threw them on the ground like a grenade, as opposed to using it via her own voice.
{ "pile_set_name": "StackExchange" }
Q: Not to marry a divorcée I remember hearing in a daf yomo shiur (and I want to find where is it written) something similar to this: it is preferable not to marry a divorced woman (if her ex-husband is still alive) because it might not be good for your future children (since she might be thinking about her first husband, but that if she is a widow then there is no fear of this.) Please help me find where something like this is written. A: It is a gemara in Pesachim 112a which talks about advice from the chachamim (I don't believe this is quoted in the poskim - not sure): לא תבשל בקדירה שבישל בה חבירך מאי ניהו גרושה בחיי בעלה דאמר מר גרוש שנשא גרושה ארבע דעות במטה ואי בעית אימא אפילו באלמנה לפי שאין כל אצבעות שוות Do not cook in a pot that your friend already cooked in. What does this mean: that a man should not marry a divorcee who's husband is still alive, for Master says a divorced man who marries a divorcee there are 4 minds in the bed, or if you prefer to say that even a widow is a problem since all fingers are not equal (she may think about her previous husband). See Rashi.
{ "pile_set_name": "StackExchange" }
Q: VBA: Won't allow me to change the RecordSource of another Form in Microsoft Access I'm working on a database that holds and displays cources for employees, every employee has a different date on which he or she has to do the specific course again. I made a few tabels that hold all the information. I can display the information in a form, this form contains a few buttons which allow me to choose between different Queries. All Queries output the same type of data in the same form. For easy reference I will call this form FormA. This all works fine but a few hours ago I added a button which should allow me to update the information of a certain record. This updating happens in a different form lets call it FormB. In the old situation I used a specific form for every training but I thought that this was every unefficient. I made a form that can display the information of every query. The problem that i'm encountering is the fact that whenever I press the button to update a certain record. It always displays the information of the top record in the query/form. I have been stuck on this for a few hours now and I just cant get it to work. If I manually set the RecordSource of FormB to the right query it all works like it should. But this requires me to make a lot of the same forms. I will try to link all the code that I think is relevant. If something else is needed please say so. The code used on the update button placed on FormA: Private Sub btnUpdate_Click() Dim stDocName As String If Forms!FormA.RecordSource = "QryFG" Then stDocName = "FormB" ' we open first the form: DoCmd.OpenForm stDocName, , , "peoplesoftnr = " & Me!PeopleSoftNr ' we then set up it's RecordSource: Forms!FormB.RecordSource = "QryFG" End If This if statement is repeated five times of all the different trainings, they are all the same so I won't include them in this post. The code fills my textboxes in my FormB. But it always picks the top record. Even when I press the button that is not in the same row (FormA). When I comment out the following line: ' Forms!FormB.RecordSource = "QryFG": And manually set the QryFG as the RecordSource of FormB, it does what its supposed to do. But by doing this I will have to create alot of the same forms. I hope there is a better way of doing this. Thanks in advance for your time and efford. My native language is not English so please ignore the spelling and grammar mistakes ;). Thanks again! Joeri Rommers A: By setting the form's recordsource, you overwrite the filter that you previously set in DoCmd.OpenForm, so it shows all records of QryFG, starting with the first. There are multiple ways around that, e.g. ' Open without filter DoCmd.OpenForm stDocName ' Limit recordsource to current record Forms!FormB.RecordSource = "SELECT * FROM QryFG WHERE peoplesoftnr = " & Me!PeopleSoftNr or set the filter after changing the recordsource: DoCmd.OpenForm stDocName With Forms(stDocName) .RecordSource = "QryFG" .Filter = "peoplesoftnr = " & Me!PeopleSoftNr .FilterOn = True End With If the form "flickers" while doing that, you can open it with WindowMode:=acHidden and then set it to .Visible = True after changing RecordSource/Filter.
{ "pile_set_name": "StackExchange" }
Q: Generate tree nodes in powershell on the fly I am currently new to and in process of learning powershell for andmistrative purposes. I am posting this question since I couldnt find much information regarding this anywhere. I am creating a script with a gui which lists all our servers as treenodes. From there I want to generate/populate/create the child nodes of the server on the fly (i.e when the node'server1' is clicked or selected , it should generate child nodes as below). Since we have large quantity of servers, I dont want to update child nodes on every server when a new property is added. Can anyone please tell me how to accomplish this? If my description doesn't make sense I can explain more. .....Server1 . . ......BIOSInfo (I am distiguishing server nodes and its child nodes by using tags) . . ......PROCInfo etc I am using sapien primal forms with powershell 3.0 here is the sample code; function NodeClick( $object ) { if ($this.SelectedNode.Tag -eq "Server") { $Server = $this.selectednode.text $richTextBox1.Text = "Script for $Server Information" #~~< TreeNode11 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $TreeNode1111 = New-Object System.Windows.Forms.TreeNode("OS") $TreeNode1111.Tag = "DevInfo" $TreeNode1111.Text = "OS" #~~< TreeNode12 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $TreeNode1222 = New-Object System.Windows.Forms.TreeNode("Domain") $TreeNode1222.Tag = "DevInfo" $TreeNode1222.Text = "Domain" #~~< TreeNode13 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $TreeNode1333 = New-Object System.Windows.Forms.TreeNode("Serial") $TreeNode1333.Tag = "DevInfo" $TreeNode1333.Text = "Serial" #~~< TreeNode14 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $TreeNode1444 = New-Object System.Windows.Forms.TreeNode("BIOS") $TreeNode1444.Tag = "DevInfo" $TreeNode1444.Text = "BIOS" #~~< TreeNode15 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $TreeNode1555 = New-Object System.Windows.Forms.TreeNode("Processor") $TreeNode1555.Tag = "DevInfo" $TreeNode1555.Text = "Processor" #~~< TreeNode16 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $TreeNode1666 = New-Object System.Windows.Forms.TreeNode("Memory") $TreeNode1666.Tag = "DevInfo" $TreeNode1666.Text = "Memory" #~~< TreeNode17 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $TreeNode1777 = New-Object System.Windows.Forms.TreeNode("Partitions") $TreeNode1777.Tag = "DevInfo" $TreeNode1777.Text = "Partitions" #~~< TreeNode18 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $TreeNode1888 = New-Object System.Windows.Forms.TreeNode("Drive") $TreeNode1888.Tag = "DevInfo" $TreeNode1888.Text = "Drive" #~~< TreeNode19 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $TreeNode1999 = New-Object System.Windows.Forms.TreeNode("IPInfo") $TreeNode1999.Tag = "DevInfo" $TreeNode1999.Text = "IPInfo" #~~< TreeNode110 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $TreeNode2111 = New-Object System.Windows.Forms.TreeNode("PrintInfo") $TreeNode2111.Tag = "DevInfo" $TreeNode2111.Text = "PrintInfo" #~~< TreeNode111 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $TreeNode2222 = New-Object System.Windows.Forms.TreeNode("FolderShare") $TreeNode2222.Tag = "DevInfo" $TreeNode2222.Text = "FolderShare" #~~< TreeNode112 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $TreeNode2333 = New-Object System.Windows.Forms.TreeNode("Tasks") $TreeNode2333.Tag = "DevInfo" $TreeNode2333.Text = "Tasks" #~~< TreeNode113 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $TreeNode2444 = New-Object System.Windows.Forms.TreeNode("Services") $TreeNode2444.Tag = "DevInfo" $TreeNode2444.Text = "Services" #~~< TreeNode114 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $TreeNode2555 = New-Object System.Windows.Forms.TreeNode("Software") $TreeNode2555.Tag = "DevInfo" $TreeNode2555.Text = "Software" $this.SelectedNode = New-Object System.Windows.Forms.TreeNode("DOCACT01", [System.Windows.Forms.TreeNode[]] ( @($TreeNode1111, $TreeNode1222, $TreeNode1333, $TreeNode1444, $TreeNode1555, $TreeNode1666, $TreeNode1777, $TreeNode1888, $TreeNode1999, $TreeNode2111, $TreeNode2222, $TreeNode2333, $TreeNode2444, $TreeNode2555) )) $this.SelectedNode.Tag = "Server" $this.SelectedNode.Text = "$Server" $form1.refresh() } else { $this.SelectedNode.expand() $richTextBox1.Text = "Script for Server Information" } A: Got it working as following; function NodeClick( $object ) { if (($this.SelectedNode.Tag -eq "Server") -and ($this.SelectedNode.nodes.count -eq 0)) { $Parent = $this.SelectedNode $richTextBox1.text = "Server Inventory Script" $Server = $Parent.text $Childs = ("OS", "Domain", "Serial", "BIOS", "Processor", "Memory", "Partitions", "Drive", "IPInfo", "PrintInfo", "FolderShare", "Tasks", "Services", "Software") $childs | %{ $newNode = New-Object System.Windows.Forms.TreeNode $newNode.Name = $_ $newNode.Text = $_ $newNode.Tag = "DevInfo" $Parent.Nodes.Add($newNode) | Out-Null return $newNode $Form1.refresh() } }
{ "pile_set_name": "StackExchange" }
Q: Enforce absolute child element to fit parent with padding How can I force a child with absolute positioning to fit parent with padding? Absolute positioning on child is a must in my case. EDIT: I want child to get inside parent's content box, not just fit into the box. <body> <div id="wrapper"> <div id="elem"> </div> </div> </body> <style> #wrapper{ padding:25px; height:100%; width:100%; background-color:blue; position:relative; } #elem{ width:100%; height:100%; position:absolute; background-color:green; } </style> Link to jsfiddle: https://jsfiddle.net/wmbszuzo/ A: You could do this using box-sizing: border-box; and width: calc(100% - 50px); https://jsfiddle.net/wmbszuzo/10/
{ "pile_set_name": "StackExchange" }
Q: Applescript: "can't get tab group 1 of window" (El Capitan) The following is an applescript that I use to change audio output devices: tell application "System Preferences" activate set current pane to pane "com.apple.preference.sound" end tell tell application "System Events" tell application process "System Preferences" tell tab group 1 of window "Sound" click radio button "Output" if (selected of row 2 of table 1 of scroll area 1) then set selected of row 1 of table 1 of scroll area 1 to true set deviceselected to "Headphones" else set selected of row 2 of table 1 of scroll area 1 to true set deviceselected to "MX279" end if end tell end tell end tell tell application "System Preferences" to quit It worked on Yosemite, but when I updated to El Capitan it is giving me the following error: "System Events got an error: Can't get tab group 1 of window \"Sound\" of application process \"System Preferences\". Invalid index" I'm pretty unfamiliar with applescript, so any ideas why this might be happening will be much appreciated. A: In the first part of your script you load the Sound preference pane. It can happen that the pane isn't fully loaded before you send commands to it in the second part of the script. The error says that the tab group 1 (the one that contains the Output tab) doesn't exist at the moment you are trying to access it. To make sure the tab group 1 exists, we can wait for it with these two lines: repeat until exists tab group 1 of window "Sound" end repeat The full script: tell application "System Preferences" activate set current pane to pane "com.apple.preference.sound" end tell tell application "System Events" tell application process "System Preferences" repeat until exists tab group 1 of window "Sound" end repeat tell tab group 1 of window "Sound" click radio button "Output" if (selected of row 2 of table 1 of scroll area 1) then set selected of row 1 of table 1 of scroll area 1 to true set deviceselected to "Headphones" else set selected of row 2 of table 1 of scroll area 1 to true set deviceselected to "MX278" end if end tell end tell end tell tell application "System Preferences" to quit
{ "pile_set_name": "StackExchange" }
Q: Twig doesn't output compiled template, just echoes template filename I'm in a Wordpress environment, PHP 5.4.1, and Apache. The following is in my functions.php: require_once( get_template_directory() . '/libs/twig/lib/Twig/Autoloader.php' ); Twig_Autoloader::register(); $loader = new Twig_Loader_String( get_template_directory().'/partials/twig-templates' ); $Twig = new Twig_Environment($loader); //doesn't work, outputs "test.html" in plain text echo $Twig->render('test.html', array('name' => 'Cameron')); //this does output a compiled template, "hey Cameron" echo $Twig->render('hey {{name}}', array('name' => 'Cameron')); I've verified that Twig is loaded properly and the file path to the template is correct. I'm guessing its something simple that I'm overlooking. Any thoughts? Thanks! A: Your loader is Twig_Loader_String which can be used only with string inputs. For a file to be rendered, use $loader = new Twig_Loader_Filesystem('/path/to/templates'); http://twig.sensiolabs.org/doc/intro.html
{ "pile_set_name": "StackExchange" }
Q: How Do I Modify This Code From getByID to getByClass? I have been using the following code to replace various text within an id on my page: function setInnerHTML(elementId, innerHTML) { var el = document.getElementById(elementId); if (el) { el.innerHTML = innerHTML; } } However, I now need to apply it to more elements and need to change it to using class instead of id. I understand you need to use getElementsByClassName, but can't get it to work. Can anyone give me a hand? A: function setInnerHTML(elementClass, innerHTML) { var elems = document.getElementsByTagName('*'), i; for (i in elems) { if((' ' + elems[i].className + ' ').indexOf(' ' + elementClass + ' ') > -1) { elems[i].innerHTML = innerHTML; } } }
{ "pile_set_name": "StackExchange" }
Q: Derived RequiredAttribute doesn't work I'm trying to implement my own RequiredAttribute, in which I call a custom resource handler: public class LocalizedValidationAttributes { public class LocalizedRequiredAttribute : RequiredAttribute { private String _resourceString = String.Empty; public new String ErrorMessage { get { return _resourceString; } set { _resourceString = GetMessageFromResource(value); } } } private static String GetMessageFromResource(String resourceTag) { return ResourceManager.Current.GetResourceString(resourceTag); } } I call this the following way: [LocalizedValidationAttributes.LocalizedRequiredAttribute(ErrorMessage = "test")] public String Text { get; set; } But the getter of ErrorMessage is never called. Any hints? Thanks! A: Try like this: public class LocalizedRequiredAttribute : RequiredAttribute { public override string FormatErrorMessage(string name) { return ResourceManager.Current.GetResourceString(name); } } or like this: public class LocalizedRequiredAttribute : RequiredAttribute { public LocalizedRequiredAttribute(string resourceTag) { ErrorMessage = GetMessageFromResource(resourceTag); } private static String GetMessageFromResource(String resourceTag) { return ResourceManager.Current.GetResourceString(resourceTag); } } and then: [LocalizedValidationAttributes.LocalizedRequiredAttribute("test")] public String Text { get; set; }
{ "pile_set_name": "StackExchange" }
Q: In Neo4j, can one find all nodes whose relationships are a superset of another node's relationships? Given the following contrived database: CREATE (a:Content {id:'A'}), (b:Content {id:'B'}), (c:Content {id:'C'}), (d:Content {id:'D'}), (ab:Container {id:'AB'}), (ab2:Container {id:'AB2'}), (abc:Container {id:'ABC'}), (abcd:Container {id:'ABCD'}), ((ab)-[:CONTAINS]->(a)), ((ab)-[:CONTAINS]->(b)), ((ab2)-[:CONTAINS]->(a)), ((ab2)-[:CONTAINS]->(b)), ((abc)-[:CONTAINS]->(a)), ((abc)-[:CONTAINS]->(b)), ((abc)-[:CONTAINS]->(c)), ((abcd)-[:CONTAINS]->(a)), ((abcd)-[:CONTAINS]->(b)), ((abcd)-[:CONTAINS]->(c)), ((abcd)-[:CONTAINS]->(d)) Is there a query that can detect all Container node pairs where one CONTAINS either a superset of or the same Content nodes as the other Container node? For my example database, I would want the query to return: (ABCD) is a superset of (ABC), (AB), and (AB2) (ABC) is a superset of (AB), and (AB2) (AB) and (AB2) contain the same nodes If cypher is unsuitable for this but another query language is well suited to it, or if Neo4j is unsuitable for this but another database is well suited to it, I'd appreciate input on that as well. Answer query performance (as of 2017-02-28T21:56Z) I am not experienced enough yet with Neo4j or graph DB querying to analyze the performance of the answers, and I have not yet constructed my large data set for a more meaningful comparison, but I thought I'd run each with the PROFILE command and list the DB hit cost. I omitted the timing data as I could not make it consistent or meaningful with such a small data set. stdob--: 129 total db hits Dave Bennett: 46 total db hits InverseFalcon: 27 total db hits A: // Get contents for each container MATCH (SS:Container)-[:CONTAINS]->(CT:Content) WITH SS, collect(distinct CT) as CTS // Get all container not equal SS MATCH (T:Container) WHERE T <> SS // For each container get their content MATCH (T)-[:CONTAINS]->(CT:Content) // Test if nestd WITH SS, CTS, T, ALL(ct in collect(distinct CT) WHERE ct in CTS) as test WHERE test = true RETURN SS, collect(T)
{ "pile_set_name": "StackExchange" }
Q: loop through a text file and insert a line with batch file I am trying to search through a text file for keywords, then insert a number of lines after a specific line/keyword (not end of file). My code can find the keywords, however I am struggling to add the lines. My code adds the line to the end of the file, so the bit I need help with is after :ADD THE TEXT. myfile.text looks like: QFU; text2; LastUpdate=20180323; text3; I would like to add a list of static lines after LastUpdate, which makes the file look like: QFU; text2; LastUpdate=20180323; Inserted text1 Inserted text2 text3; This is my code: @echo SET /A COND1=0 for /F "tokens=*" %%i in (myfile.txt) do call :process %%i goto thenextstep :process set VAR1=%1 IF "%VAR1%"=="QFU" SET /A COND1=1 IF "%VAR1%"=="QFU" ( msg * "QFU line found !!" ) :If QFU line is found then look for Last update IF "%COND1%"=="1" IF "%VAR1%"=="LastUpdate" ( msg * "LastUpdate line found !!" :ADD THE TEXT echo. text to be added>>myfile.txt :reset COND1 to 0 set /A COND1=0 ) A: @echo off setlocal enabledelayedexpansion call :get_insert_index if not defined index ( >&2 echo index not defined. exit /b 1 ) set "i=0" ( for /f "tokens=*" %%A in (myfile.txt) do ( set /a "i+=1" echo %%A for %%B in (%index%) do if !i! equ %%B ( echo --- INSERT ) ) ) > myupdate.txt exit /b :get_insert_index setlocal enabledelayedexpansion set "i=0" set "qfu=" set "total=" for /f "tokens=*" %%A in (myfile.txt) do ( set /a i+=1 set "line=%%~A" if "%%~A" == "QFU;" ( set /a "qfu=!i! + 1" ) else if "!line:~,11!" == "LastUpdate=" ( if defined qfu ( if !i! gtr !qfu! ( if defined total (set total=!total! !i!) else set total=!i! set "qfu=" ) ) ) ) endlocal & set "index=%total%" exit /b This will insert text after the 1st line starting with LastUpdate=, after the line of QFU;, but not the line starting with LastUpdate= which is the next line after QFU;. The label :get_insert_index is called and uses a for loop to read myfile.txt to get the line index of LastUpdate= mentioned in the above paragraph. The variable qfu stores the line index + 1 of QFU; so LastUpdate= cannot be matched on the next line. If gfu and LastUpdate= is found and the line index is greater then gfu, then the line index is appended to total. qfu is undefined to avoid further matches to LastUpdate= until QFU; is matched again. The loop will end and the global variable index is set the value of total. The label returns control back to the caller. index is checked if defined at the top of the script after the call of the label. The top for loop reads myfile.txt and echoes each line read. The nested for loop checks the index variable to match the current line index and if equal, will echo the new text. The echoes are redirected to myupdate.txt. Used substitution of "!line:~,11!" so view set /? for help. Used enabledelayedexpansion so view setlocal /? for help. Text using ! may find ! being interpreted as a variable so avoid using !. Used gtr which can be viewed in if /?. gtr is "Greater than". Alternative to avoid creation of an index: @echo off setlocal enabledelayedexpansion set "i=0" set "gfu=" for /f "tokens=*" %%A in (myfile.txt) do ( set /a i+=1 set "line=%%~A" >> myupdate.txt echo(%%A if "%%~A" == "QFU;" ( set /a "qfu=!i! + 1" ) else if "!line:~,11!" == "LastUpdate=" ( if defined qfu ( if !i! gtr !qfu! ( >> myupdate.txt echo --- INSERT set "qfu=" ) ) ) ) exit /b >> myupdate.txt echo(%%A writes each line. >> myupdate.txt echo --- INSERT writes new line to insert. If system memory permits based on file size, this is much faster: @echo off setlocal enabledelayedexpansion set "i=0" set "gfu=" ( for /f "tokens=*" %%A in (myfile.txt) do ( set /a i+=1 set "line=%%~A" echo(%%A if "%%~A" == "QFU;" ( set /a "qfu=!i! + 1" ) else if "!line:~,11!" == "LastUpdate=" ( if defined qfu ( if !i! gtr !qfu! ( echo --- INSERT set "qfu=" ) ) ) ) ) > myupdate.txt exit /b Used on 2.74 MB file, Time reduced from 70s to 21s. The write handle to myupdate.txt remains open for the entire loop, thus the write is cached.
{ "pile_set_name": "StackExchange" }
Q: Pushing on-fly transcoded video to embeded http results with no seekbar I'm trying to achieve a simple home-based solution for streaming/transcoding video to low-end machine that is unable to play file properly. I'm trying to do it with ffmpeg (as ffserver will be discontinued) I found out that ffmpeg have build in http server that can be used for this. The application Im' testing with (for seekbar) is vlc I'm probably doing something wrong here (or trying to do something that other does with other applications) My ffmpeg code I use is: d:\ffmpeg\bin\ffmpeg.exe -r 24 -i "D:\test.mkv" -threads 2 -vf scale=1280:720 -c:v libx264 -preset medium -crf 20 -maxrate 1000k -bufsize 2000k -c:a ac3 -seekable 1 -movflags faststart -listen 1 -f mpegts http://127.0.0.1:8080/test.mpegts This code also give me ability to start watching it when I want (as opposite to using rtmp via udp that would start video as soon as it transcode it) I readed about moving atoom thing at file begging which should be handled by movflags faststart I also checked the -re option without any luck, -r 25 is just to suppress the Past duration 0.xx too large warning which I read is normal thing. test file is one from many ones with different encoder setting etc. The setting above give me a seekbar but it doesn't work and no overall duration (and no progress bar), when I switch from mpegts to matroska/mkv I see duration of video (and progress) but no seekbar. If its possible with only ffmpeg I would prefer to stick to it as standalone solution without extra rtmp/others servers. A: after some time I get to point where: seek bar is a thing on player side , hls in version v6 support pointing to start item as v3 start where ever it whats (not more than 3 items from end of list) playback and seek is based on player (safari on ios support it other dosn't) also ffserver is no needed to push the content. In the end it work fine without seek and if seek is needed support it on your end with player/js.player or via middle-ware like proxy video server.
{ "pile_set_name": "StackExchange" }
Q: I want to sort the array by keys in php I have an array, $data, in the form of : Array ( [1] => Array ( [group_exp] => Group 2 [cat_exp] => Category 3 [sub_exp] => Sub Category 4 ) [2] => Array ( [group_exp] => Group 3 [cat_exp] => Category 4 [sub_exp] => Sub Category 5 ) ) but i want to save this array in this form : Array ( [0] => Array ( [group_exp] => Group 2 [cat_exp] => Category 3 [sub_exp] => Sub Category 4 ) [1] => Array ( [group_exp] => Group 3 [cat_exp] => Category 4 [sub_exp] => Sub Category 5 ) ) A: As the comments has shown, use array_values to reorder the indexes if the array already is in the correct order. $array = array_values($array); If the array should be sorted by its indices (if their inherent order is not sorted, such as [2], [1], [3], sort the array by key first: ksort($array); $array = array_values($array);
{ "pile_set_name": "StackExchange" }
Q: AOP: basic ideas - keep objects simple? I work with Spring Framework 3.0.5 and Id like to understand the basic principals of Spring. One of it is AOP. One basic idea of the spring framework is to keep the objects itself simple and to have clear code. DI follows this basic idea. It provides clear code and the objects itself can be very simple. The dont have to look up their dependencys. Now what about AOP: I mean, code is for sure clearer with AOP, but does AOP also have the basic idea of keeping the objects as simple as possible? Im not sure of that, thats why Id like to know some other opinions :-) Thanks in advance! A: The main motivation for AOP is to use it for so called cross-cutting concerns, as in functionality you need to provide in basically all parts of your application, usually these include: logging authentication auditing transactionality. AOP allows you to extract these functionalities into separate classes and just mark your classes which need these. Watch this excellent video to get the main idea. To answer your question, yes, it will help a lot to keep your classes clean, because they will only take care about their own functionality and don't have to provide boilerplate code over and over again. A: Take the following code snippets as an example. The easy way: @PersistenceContext private EntityManager em; @Transactional public void save(Object obj) { em.persist(obj); } The traditional way (you can manage transactions using EntityManager interface, but that is not the point): @PersistenceContext private EntityManager em; @Resource private AbstractPlatformTransactionManager transactionManager; public void save(final Object obj) { new TransactionTemplate(transactionManager).execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { em.persist(obj); } }); } What does it have to do with AOP? Transaction management is one of the most widely used examples of AOP and Spring is not an exception. The former code snippet uses @Transactional annotation to apply transaction demarcation using aspect, while the latter manages transactions manually. See the benefit? The key thing: use aspects for cross-cutting concerns like logging, profiling, etc. Don't build your business logic in aspects. This way your beans remain clear while irrelevant code from business perspective is hidden in the aspect. Also AOP allows you to do all sorts of sophisticated stuff with ease. Take for instance HTTP session handling - with session bean scope and AOP proxying you can access session without even realizing it. To summarize - it is great tool when used for the right job.
{ "pile_set_name": "StackExchange" }
Q: Dragging selected Item along with the mouse in WPF I am using the following code for performing Drag & Drop in my StackPanel Childran, XAML <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="601" Width="637"> <StackPanel Name="sp" AllowDrop="True" Background="SkyBlue" PreviewMouseLeftButtonDown="sp_PreviewMouseLeftButtonDown" PreviewMouseLeftButtonUp="sp_PreviewMouseLeftButtonUp" PreviewMouseMove="sp_PreviewMouseMove" DragEnter="sp_DragEnter" Drop="sp_Drop"> <Image Source="/Assets/Image1.jpg" Height="100" Width ="100"/> <Image Source="/Assets/Image2.jpg" Height="100" Width ="100"/> <Image Source="/Assets/Image3.jpg" Height="100" Width ="100"/> <Image Source="/Assets/Image4.jpg" Height="100" Width ="100"/> <Image Source="/Assets/Image5.jpg" Height="100" Width ="100"/> </StackPanel> Code Behind public partial class Window1 : Window { public Window1() { InitializeComponent(); } private bool _isDown; private bool _isDragging; private Point _startPoint; private UIElement _realDragSource; private UIElement _dummyDragSource = new UIElement(); private void sp_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (e.Source == this.sp) { } else { _isDown = true; _startPoint = e.GetPosition(this.sp); } } private void sp_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e) { _isDown = false; _isDragging = false; _realDragSource.ReleaseMouseCapture(); } private void sp_PreviewMouseMove(object sender, MouseEventArgs e) { if (_isDown) { if ((_isDragging == false) && ((Math.Abs(e.GetPosition(this.sp).X - _startPoint.X) > SystemParameters.MinimumHorizontalDragDistance) || (Math.Abs(e.GetPosition(this.sp).Y - _startPoint.Y) > SystemParameters.MinimumVerticalDragDistance))) { _isDragging = true; _realDragSource = e.Source as UIElement; _realDragSource.CaptureMouse(); DragDrop.DoDragDrop(_dummyDragSource, new DataObject("UIElement", e.Source, true), DragDropEffects.Move); } } } private void sp_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent("UIElement")) { e.Effects = DragDropEffects.Move; } } private void sp_Drop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent("UIElement")) { UIElement droptarget = e.Source as UIElement; int droptargetIndex=-1, i =0; foreach (UIElement element in this.sp.Children) { if (element.Equals(droptarget)) { droptargetIndex = i; break; } i++; } if (droptargetIndex != -1) { this.sp.Children.Remove(_realDragSource); this.sp.Children.Insert(droptargetIndex, _realDragSource); } _isDown = false; _isDragging = false; _realDragSource.ReleaseMouseCapture(); } } } What i am trying to implement is, I need to drag the clicked item along with my click and drag. In this implementation, While drag and drop a small rectangle dotted like selection appears and then it drops to the place where mouse pointer leaves. How can i hold that image along with my selection (drag & drop) Thanks in Advance, StezPet. A: If I understand you correctly and you want to have some visual feedback of the object that is being dragged in a drag and drop operation, then you'll need to use the Adorner Layer. From the linked page: Adorners are a special type of FrameworkElement, used to provide visual cues to a user... [and] are rendered in an AdornerLayer, which is a rendering surface that is always on top of the adorned element You can find a good article explaining how to do this with a code example in the WPF: Drag Drop Adorner post on Code Blitz.
{ "pile_set_name": "StackExchange" }
Q: LLVM Backend : Replacing indirect jmps for x86 backend I want to replace indirect jmp *(eax) instructions in the code to mov *(eax),ebx; jmp *ebx for the x86 executables. Before implementing this, i would like to make LLVM compiler, log an output every time it detects a jmp *(eax) instruction by adding some print statements. Then i want to move on to replacing the indirect sequence. From what i have seen from google searches and articles, i can probably achieve this by modifying the x86asmprinter in the llvm backend. But i am not sure how to go about it. Any help or reading would be appreciated. Note: My actual requirement deals with indirect jumps and pop, but i want to start with this to understand the backend a bit more before i dive into anything more. A: I am done with my project. Posting my approach for the benefit of others. The main function of LLVM backend is to convert the Intermediate Representation to the final executable depending on the target architecture and other specification. The LLVM backend itself consists of several phases which does target specific optimization,Instruction Selection, Scheduling and Instruction Emitting. These phases are required because the IR is a very generic representation and requires a lot of modifications to finally convert them to target specific executables. 1)Logging every time the compiler generates jmp *(eax) We can achieve this by adding print statements to the Instruction Emitting/Printing phase. After most of the main conversion from IR is done, there is an AsmPrinter pass which goes through each Machine Instruction in a Basic Block of every function. This main loop is at lib/CodeGen/AsmPrinter/AsmPrinter.cpp:AsmPrinter::EmitFunctionBody(). There are other related functions like EmitFunctionEpilogue,EmitFunctionPrologue. These functions finally call EmitInstruction for specific architecture eg: lib/Target/X86/X86AsmPrinter.cpp. If you tinker around a bit, you can call MI.getOpcode() and compare it with defined enums for the architecture to print a log. For example for a jump using register in X86, it is X86::JMP64r. You can get the register associated using MI.getOperand(0) etc. if(MI->getOpcode() == X86::JMP64r) dbgs() << "Found jmp *x instruction\n"; 2)Replacing the instruction The required changes vary depending on the type of replacement you require. If you need more context about registers,or previous instructions, we would need to implement the changes higher up in the Pass chain. There is a representation of instructions called Selection DAG( directed acyclic graph ) which stores dependencies of each instruction to previous instructions. For example, in the sequence mov myvalue,%rax jmp *rax The DAG would have the jmp instruction pointing to the move instruction ( and possibly other nodes before it) since the value of rax depends on the mov instruction. You can replace the Node here with your required Nodes. If done correctly, it should finally change the final instructions. The SelectionDAG code is at lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp. Always best to poke around first to figure out the ideal place to change. Each IR statement goes through multiple changes before the DAG is topologically sorted so that the Instructions are in a linear sequence. The graphs can be viewed using -view-dag* options seen in llc --help-hidden. In my case, I just added a specific check in EmitInstruction and added code to Emit two instructions that i wanted. LLVM documentation is always there, but i found Eli Bendersky's two articles more helpful than any other resources. Life of LLVM Instruction and Deeper look into LLVM Code Generation. The articles discuss the very complex TableGen descriptions and the instruction matching process as well which is kind of cool if you are interested.
{ "pile_set_name": "StackExchange" }
Q: Multiple build commands for output file in Xcode My xCode project for an OSX app gives me the following error. Warning: Multiple build commands for output file /Users/myusername/Library/Developer/Xcode/DerivedData/Flui-dpvozbfxcmsipwfrrannskcofgit/Build/Products/Debug/appname.app/Contents/Resources/Icons Is this something I should be worried about or fix immediately? Also is there a way to make this go away? A: Open the Copy Bundle Resources from the Build Phase in your project. Find the duplicate files in that list and delete their references.
{ "pile_set_name": "StackExchange" }
Q: Can C++ functions return a pointer to an array of known length? I have a class that contains a static constexpr array of const chars, which i would like to make available via a c_str() method: class my_class { private: static constexpr const char c_str_[6] = {'c', 'h', 'a', 'r', 's', '\0'}; public: static constexpr const char* c_str() { return c_str_; } }; This works, but has an unfortunate effect: It removes the length of the pointed-to array from the type: decltype(my_class::c_str()) // equivalent to const char* What I'd really like is some way to achieve this: decltype(my_class::c_str()) // equivalent to const char[6] I understand that in either case the returned object will be a pointer; I would just like to preserve the length of the pointed-to array in the type. Kind of like how decltype("string literal") is const char[15], not const char*. Is there a way to do this? A: You mean like returning a reference to c_str_? static constexpr decltype(c_str_)& c_str() { return c_str_; } or static constexpr auto& c_str() { return c_str_; } If you want a pointer, just swap the & for a * and return &c_str_. If you want to explicitly refer to the type, use an alias: using T = const char[6]; static constexpr T& c_str() { return c_str_; } Or if you really hate yourself: static constexpr const char (&c_str())[6] { return c_str_; } Note that you cannot have a function return a raw array by value. A: A modern alternative would be returning a string_view, which basically is the combination of a pointer to the string and the length. That allows the user of your function to directly access the length information. And the string could be stored in a null-terminated or non-null-terminated fashion in my_class. As far as I can see string_view supports a constexpr constructor too. However this doesn't allow for the signature const char* c_str(). If you are bound to that, the string must be null-terminated in order to allow the caller to retrieve the length (by counting).
{ "pile_set_name": "StackExchange" }
Q: Crop non symmetric area of an image with Python/PIL Is there a way to cut out non rectangular areas of an image with Python PIL? e.g. in this picture I want to exclude all black areas as well as towers, rooftops and poles. http://img153.imageshack.us/img153/5330/skybig.jpg I guess the ImagePath Module can do that, but furthermore, how can I read data of e.g. a svg file and convert it into a path? Any help will be appreciated. (My sub question is presumably the easier task: how to cut at least a circle of an image?) A: If I understood correctly, you want to make some areas transparent within the image. And these areas are random shaped. Easiest way (that I can think of) is to create a mask and put it to the alpha channel of the image. Below is a code that shows how to do this. If your question was "How to create a polygon mask" I will redirect you to: SciPy Create 2D Polygon Mask and look the accepted answer. br, Juha import numpy import Image # read image as RGB and add alpha (transparency) im = Image.open("lena.png").convert("RGBA") # convert to numpy (for convenience) imArray = numpy.asarray(im) # create mask (zeros + circle with ones) center = (200,200) radius = 100 mask = numpy.zeros((imArray.shape[0],imArray.shape[1])) for i in range(imArray.shape[0]): for j in range(imArray.shape[1]): if (i-center[0])**2 + (j-center[0])**2 < radius**2: mask[i,j] = 1 # assemble new image (uint8: 0-255) newImArray = numpy.empty(imArray.shape,dtype='uint8') # colors (three first columns, RGB) newImArray[:,:,:3] = imArray[:,:,:3] # transparency (4th column) newImArray[:,:,3] = mask*255 # back to Image from numpy newIm = Image.fromarray(newImArray, "RGBA") newIm.save("lena3.png") Edit Actually, I could not resist... the polygon mask solution was so elegant (replace the above circle with this): # create mask polygon = [(100,100), (200,100), (150,150)] maskIm = Image.new('L', (imArray.shape[0], imArray.shape[1]), 0) ImageDraw.Draw(maskIm).polygon(polygon, outline=1, fill=1) mask = numpy.array(maskIm) Edit2 Now when I think of it. If you have a black and white svg, you can load your svg directly as mask (assuming white is your mask). I have no sample svg images, so I cannot test this. I am not sure if PIL can open svg images.
{ "pile_set_name": "StackExchange" }
Q: Run migrations without loading initial_data.json I provide a lista of users for my application in a json located in my app: myapp/ fixtures/ initial_data.json it load everytime I run python manage.py migrate. I've read the Providing initial data for models document, but it does not mention anything about avoid loading it. I wonder if there's a command to run python manage.py migrate without load initial_data. A: Consider upgrade to Django==1.8. You shouldn't have many problems after upgrade. What's your Django version? Anyway, take a look at the documentation, since Django>=1.7 automatic loading of fixtures doesn't work: If an application uses migrations, there is no automatic loading of fixtures An application uses migrations when you have the migrations folder with the __init__.py file inside it. If you use Django>=1.7 and you use migrations in your app, you don't have automatic fixtures loading when you run python manage.py migrate. But, if you don't use migrations in your app, you always have automatic fixtures loading if your fixture file is named initial_data.json. You can rename the initial_data.json file to any other name (like mydata.json) in order to avoid automatic fixtures loading, then, you can load the data any time you want by running: django-admin.py loaddata mydata.json
{ "pile_set_name": "StackExchange" }
Q: Why is my var_dump() only showing when used outside of the function? I'm learning about var_dump() while trying to debug some code in my WordPress functions.php file. When var_dump() is used inside a function it does not display on the page. Nothing will display with this: function my_function() { $test_variable = 'some words'; var_dump($test_variable); } But when var_dump() is outside of a function it displays fine. This displays the dump: $test_variable = 'some words'; var_dump($test_variable); Why is my var_dump() only showing when used outside of the function? A: You have not called function any where. function my_function() { $test_variable = 'some words from inside my_function'; var_dump($test_variable); } $test_variable = 'some words from out side my_function'; var_dump($test_variable); my_function(); This show the both statement.
{ "pile_set_name": "StackExchange" }
Q: Browser setups to stay safe from malware and unwanted stuff I have to set up a browser to surf the internet. I'm trying to stay safe from malware as much as possible. (I already know that there's no way to stay 100% safe.) My idea is to use Firefox with these extensions: Adblock Plus, uBlock Origin, HTTPS Everywhere, and particularly NoScript Security Suite. I also thought about clearing the cache when Firefox is closed. But since I'm not an expert, I searched for recommendations on the internet. I found this Security.SE that says: disabling JS should not be considered a silver bullet for browser security Take into consideration that NoScript will also increase the attack surface Before reading it, I was pretty sure that No Script would have been enough to make browser very very safe. But now I'm wondering if there are safer ways to secure the browser, and I have these questions: Is my idea good? If so, what can I improve? Should I use Chrome instead of Firefox? I read Is Chrome more secure? which is why I'm asking. Are the extensions that I mention above good? I know that both Adblock Plus and uBlock Origin block more or less same ads, but I prefer to keep both. Browser performance is not a problem. Is there any other extension that I should install? Is there some other browser setting that I should enable/disable? (such as the option to clear cache when Firefox is closed) I already know basic rules, such as update browser and OS, don't open unsafe link etc etc. I would like to know advanced tips. I know that it also depends on the operating system and other stuff, but in this topic i would like to talk about the browser PS: I know that instead of NoScript I could just disable all scripts with the browser settings, but I like the way I can allow a script in a site because some sites don't without a specific script. A: First of all, good job on choosing Firefox and the right plugins, it's really the browser to go privacywise. To extend upon the points that nobody mentioned yet, an important part of you hardening your browser would be the configuration of your Firefox browser! You can do that by typing about:config into the address bar and accepting the risks. Then you search for the specific string I specify in this answer. I will draw a line where the security completely destroys functionality (judging from my experience, since I myself use this setup). First off, you're better off disabling WebGL: Motivation webgl.disabled = true Disabling WebRTC will prevent from getting your IP leaked behind VPNs (yes, NoScript SHOULD protect you but you can never be too safe): media.peerconnection.turn.disable = true media.peerconnection.use_document_iceservers = false media.peerconnection.video.enabled = false media.peerconnection.identity.timeout = 1 You're better off disabling third-party cookies: network.cookie.cookieBehavior = 1 (Only accept from the originating site (block third-party cookies)) Never store extra information about a session: contents of forms, scrollbar positions, cookies, and POST data: browser.sessionstore.privacy_level = 2 Activate integrated privacy measures: privacy.firstparty.isolate = true privacy.resistFingerprinting = true privacy.trackingprotection.fingerprinting.enabled = true privacy.trackingprotection.cryptomining.enabled = true (disables cryptomining on piratebay) browser.send_pings = false browser.sessionstore.max_tabs_undo = 0 (Firefox doesn't remember your recent closed tabs anymore) browser.urlbar.speculativeConnect.enabled = false (disable preloading of autocomplete URLs) media.navigator.enabled = false This enables the integrated privacy guard (uses mostly Disconnect.me filters, also breaks Captchas, but you can disable it for certain sites, since it will be like 1% of your total surfing): privacy.trackingprotection.enabled = true Disable the DOM Clipboard Event: dom.event.clipboardevents.enabled = false Protect yourself against punycode phishing attacks: network.IDN_show_punycode = true Disable WebAssembly: javascript.options.wasm = false In the normal browser settings you can also disable Pocket, erase history, cache, cookies upon exiting Firefox. That should be more than enough. DANGER ZONE disables playback of DRM-controlled HTML5 content, which, if enabled, automatically downloads the Widevine Content Decryption Module provided by Google Inc. This will break Netflix et al.! media.eme.enabled = false media.gmp-widevinecdm.enabled = false Send Referer only when the full hostnames match: network.http.referer.XOriginPolicy = 2 Only send scheme, host, and port in Referer: network.http.referer.XOriginTrimmingPolicy = 2 If you're near-paranoid you can even disable Referer: network.http.sendRefererHeader = 0 If you need even more privacy check this out. You can also blacklist hosts if you haven't already so other apps don't have such a huge attack surface. There is also a plugin called LibreJS which blocks proprietary, non-trivial and obfuscated JavaScript code. Also setting the locale to en-US in your browser is a good approach to privacy. A: As you correctly point out, there is no 100% guarantee that you cannot be infected by malware through a browser. I think it would be best to adhere to a multilayered strategy here. How deep you go of course depends on your security and other requirements. The first layer is to be mindful of the websites you visit. If you limit yourself to a few very well known sites that have been bookmarked this severely limits your exposure. Second layer is to always stay current on security updates, not only for your browser but also for the operating system. Malware is usually dependent on some sort of misconfiguration or known security vulnerability. The second one and sometimes the first one can be solved by keeping current on updates. Third layer would be the tools that you mentioned. I am not going to discuss them separately, since there are already good pointers in the comments. Keep in mind, however, that every additional tool that you use might also be a security risk in itself for various reasons. Fourth layer is to separate the environment in which your browser is running from your other (important) data. This can be done by using a virtual machine or even a physically different host. This, however, is some work because you would have another operating system to configure and maintain. The order of layers can be argued about, but you get the picture.
{ "pile_set_name": "StackExchange" }
Q: C# JSON .NET deserialize with JsonObjects in another object I've created a PHP interface that connects to a database, by encoding JSON in PHP and decoding it on the C# using JSON .NET. Everything has worked fine so far. I have a few classes that I use, which I all created to be used with JSON .NET { "ReceptId": "1", "Naam": "Rijst met ragout", "GramPerPersoon": "280", "Type": "Eten", "Instructies": [ "Maak rijst warm", "Doe ragout op de rijst" ], "Benodigdheden": [{ "Hoeveelheid": "70", "Eenheid": "gram", "Ingredient": { "Ingredient_id": "1", "Naam": "Rijst", "Beschrijving": "Rijst behoort zoals alle granen tot de grassenfamilie. Rijst is het belangrijkste voedsel voor een groot deel van de wereldbevolking, vooral in de warmere streken.", "Energie": "355", "Vetten": "0.5", "VerzadigdeVetten": "0.2", "KoolHydraten": "79", "Eiwitten": "7.5" } }, { "Hoeveelheid": "30", "Eenheid": "gram", "Ingredient": { "Ingredient_id": "2", "Naam": "Ragout", "Beschrijving": "Ragout (Nederlands-Nederlands) of vol-au-vent (Vlaams) is van oorsprong een gerecht dat bestaat uit stukjes gesneden vlees, gevogelte of vis in saus.", "Energie": "98", "Vetten": "5.5", "VerzadigdeVetten": "2.2", "KoolHydraten": "3.8", "Eiwitten": "8.3" } }] } The problem is that the Ingredient object is always NULL, even when I serialize the object itself. The classes have been built very simplistic, using C# properties to store variables. Normal lists of strings have worked fine previously, for example Instructies. The class I'm trying to parse is Recept, which I do like this: Recept recept = JsonConvert.DeserializeObject(json); With JSON being the JSON input you can view above here. Recept contains a few properties, which all work fine except for Benodigdheden. [JsonProperty] public List<Benodigdheid> Benodigdheden { get; private set; } [JsonProperty] public List<string> Instructies { get; private set; } [JsonProperty] public int ReceptId { get; private set; } [JsonProperty] public string Naam { get; private set; } [JsonProperty] public ReceptType Type { get; private set; } [JsonProperty] public int GramPerPersoon { get; private set; } public Recept(int id, string naam, ReceptType receptType, int gramPP, List<string> instructies, List<Benodigdheid> benodigdheden) { this.ReceptId = id; this.Naam = naam; this.Type = receptType; this.GramPerPersoon = gramPP; this.Instructies = instructies; getBenodigdHeden(); } The Benodigdheid class contains only 3 properties, which are: [JsonProperty] public Ingredient Ingredient { get; private set; } [JsonProperty] public int Hoeveelheid { get; private set; } [JsonProperty] public string Eenheid { get; private set; } public Benodigdheid(Ingredient ingredient, int hoeveelheid, string eenheid) { this.Ingredient = ingredient; this.Hoeveelheid = hoeveelheid; this.Eenheid = eenheid; } Then there is the last class named Ingredient (which means the same in english) [JsonProperty] public int Ingredient_id { get; private set; } [JsonProperty] public string Naam { get; private set; } [JsonProperty] public string Beschrijving { get; private set; } [JsonProperty] public float Energie { get; private set; } [JsonProperty] public float Vetten { get; private set; } [JsonProperty] public float VerzadigdeVetten{ get; private set; } [JsonProperty] public float KoolHydraten { get; private set; } [JsonProperty] public float Eiwitten { get; private set; } public Ingredient(int id, string naam, string beschrijving, float energie, float vetten, float verzadigde_vetten, float koolhydraten, float eiwitten) { this.Ingredient_id = id; this.Naam = naam; this.Beschrijving = beschrijving; this.Energie = energie; this.Vetten = vetten; this.VerzadigdeVetten = verzadigde_vetten; this.KoolHydraten = koolhydraten; this.Eiwitten = eiwitten; } A: You do not need to decorate your c# class with these attributes. from the json you posted, with http://json2csharp.com/, I've generated theses classe, which I think it is enough to you deserialize your json data. public class Ingredient { public string Ingredient_id { get; set; } public string Naam { get; set; } public string Beschrijving { get; set; } public string Energie { get; set; } public string Vetten { get; set; } public string VerzadigdeVetten { get; set; } public string KoolHydraten { get; set; } public string Eiwitten { get; set; } } public class Benodigdheden { public string Hoeveelheid { get; set; } public string Eenheid { get; set; } public Ingredient Ingredient { get; set; } } public class RootObject { public string ReceptId { get; set; } public string Naam { get; set; } public string GramPerPersoon { get; set; } public string Type { get; set; } public List<string> Instructies { get; set; } public List<Benodigdheden> Benodigdheden { get; set; } }
{ "pile_set_name": "StackExchange" }
Q: View and variables Im new in Kohana framework. I want create controller and display variables in view. My Controller Start.php: <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Start extends Controller_Template { public function action_index() { $view = View::factory('start') ->set('title', array('tytul 1', 'tytul 2')); $this->response->body($view); } } in APPPATH/views have Start.php: <h1><?php echo $title[0] ?></h1> When I open site have error: View_Exception [ 0 ]: The requested view template could not be found When I display data from action with: $this->response->body('test'); when I open site have 'test' What is wrong with my view? A: Your controller is missing the template definition, Piotr. What you have to do in your Controller is to define what view your controller need to use: class Controller_Start extends Controller_Template { // This has to be defined public $template = 'start'; public function action_index() { $this->template->set('title', array('tytul 1', 'tytul 2')); // No need to do this if you're extending Controller_Template // $this->response->body($view); } } my_view is the filename (without the .php extension) of a template file located in your /application/views folder. If it's in a subfolder, then provide it in there, e.g.: public $template = 'subfolder/start'; Note that it has to be defined as string, as the Controller_Template::before() method will transform it to a View object. This means that you do not have to create your own $view object within the action_index(), unless you want to override the default one. Then you'd need to do something like: class Controller_Start extends Controller_Template { public function action_index() { $view = View::factory('start') ->set('title', array('tytul 1', 'tytul 2')); $this->template = $view; // And that's it. Controller_Template::after() will set the response // body for you automatically } } If you want to have full control over the template and don't want Kohana to interfere I'd suggest not extending the Controller_Template class, but rather use the plain Controller and render the view yourself, e.g.: class Controller_Start extends Controller { public function action_index() { $view = View::factory('start') ->set('title', array('tytul 1', 'tytul 2')); // Render the view and set it as the response body $this->response->body($view->render()); } }
{ "pile_set_name": "StackExchange" }
Q: Android Sync Adapter not firing in android nought (API > 23) I need to connect the system server for each 1 minute from my mobile app to sync data. For that I am using SyncAdapter class in my app. It works fine for mobiles having api < 23 (upto marshmallow it works fine). When I test my app in mobile having api > 23 , the sync adapter class not firing. It fires only the first time I install the app in the device. I am using the following code in my app. Can anyone help me to solve the problem? public class MyServiceSyncAdapter extends AbstractThreadedSyncAdapter { //TODO change this constant SYNC_INTERVAL to change the sync frequency public static final int SYNC_INTERVAL = 20; //60 * 180; // 60 seconds (1 minute) * 180 = 3 hours public static final int SYNC_FLEXTIME = SYNC_INTERVAL/3; private static final int MOVIE_NOTIFICATION_ID = 3004; public static DataBaseConnection mCon; public MyServiceSyncAdapter(Context context, boolean autoInitialize) { super(context, autoInitialize); mCon = new DataBaseConnection(this.getContext()); } @Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { Log.i("MyServiceSyncAdapter", "onPerformSync"); //TODO get some data from the internet, api calls, etc. //TODO save the data to database, sqlite, couchbase, etc try{ //my code to perform the task }catch (Exception e){ } } public static void configurePeriodicSync(Context context, int syncInterval, int flexTime) { Account account = getSyncAccount(context); String authority = context.getString(R.string.content_authority); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // we can enable inexact timers in our periodic sync SyncRequest request = new SyncRequest.Builder() .syncPeriodic(syncInterval, flexTime) .setSyncAdapter(account, authority) .setExtras(new Bundle()).build(); ContentResolver.requestSync(request); } else { ContentResolver.addPeriodicSync(account, authority, new Bundle(), syncInterval); } } public static void syncImmediately(Context context) { Log.i("MyServiceSyncAdapter", "syncImmediately"); Bundle bundle = new Bundle(); bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); ContentResolver.requestSync(getSyncAccount(context), context.getString(R.string.content_authority), bundle); } public static Account getSyncAccount(Context context) { AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE); // Get an instance of the Android account manager Account newAccount = new Account(context.getString(R.string.app_name), context.getString(R.string.sync_account_type)); // Create the account type and default account // If the password doesn't exist, the account doesn't exist if (accountManager.getPassword(newAccount) == null) { if (!accountManager.addAccountExplicitly(newAccount, "", null)) { Log.e("MyServiceSyncAdapter", "getSyncAccount Failed to create new account."); return null; } onAccountCreated(newAccount, context); } return newAccount; } private static void onAccountCreated(Account newAccount, Context context) { Log.i("MyServiceSyncAdapter", "onAccountCreated"); MyServiceSyncAdapter.configurePeriodicSync(context, SYNC_INTERVAL, SYNC_FLEXTIME); ContentResolver.setSyncAutomatically(newAccount, context.getString(R.string.content_authority), true); syncImmediately(context); } public static void initializeSyncAdapter(Context context) { Log.d("MyServiceSyncAdapter", "initializeSyncAdapter"); getSyncAccount(context); } } A: Are you sure the adapter is not firing and not just taking a very long time to run? From the documentation for syncPeriodic: pollFrequency long: the amount of time in seconds that you wish to elapse between periodic syncs. A minimum period of 1 hour is enforced. So, if you wait long enough, you may see your periodic sync start. I have timed this (slow day) and the sync does start...eventually. Update Based upon a demo sync app here, I recorded onPerformSync() start times for APIs 23, 24 and 28. Times in the following table have been normalized to midnight. The sync period in all cases is attempted at one minute. As you can see, onPerformSync() runs about once per minute for API 23. However, API 24 and API 28 do seem to latch the time between calls to onPerformSync() at 15 minutes give or take. APIs earlier than API 23 honor the one minute period request. Recently, I haven't seen the one hour minimum, but I am sure I have in the past. You may want to look into other ways to do syncing depending upon your requirements. Take a look at WorkManager, JobScheduler and AlarmManager in that order. (Use WorkManager if you can though.)
{ "pile_set_name": "StackExchange" }
Q: What's an adjective for someone who is quick to comment on a situation but unwilling (or unable) to commit to providing a helpful answer? It seems to me that many people exhibit this tendency and I am looking for a good word to describe them. They love providing feedback but in a passive-aggressive way. They love giving their two cents but stop short of actually putting themselves in the position of having to commit to an answer. For example, I might write the following sentence: On the English Language & Usage stack exchange, certain ________ people are more ready to populate the comment section than they are to provide answers. A: This reminds me of the difference between "involved" and "committed" being like ham and eggs (the chicken is involved, the pig is committed). "Uncommitted" sort of works, but maybe uninvested is better, as in not invested in participation. It's a usage based on one of the definitions of "invest": to involve or engage especially emotionally - M-W
{ "pile_set_name": "StackExchange" }
Q: Can’t execute test with more than 2 devices when using Appium grid Context: I have been writing automated test scripts with Appium for quite a while and everything works well most of the time, but now I’m trying to execute tests with multiple devices using Appium grid and I am encountering issues when I’m executing the tests with more than 2 devices. Problem: Can’t execute test with Appium grid when using more than 2 devices. I’m almost certain that the issue is with the node configuration, I simply tried to follow examples online, but didn’t find anywhere defined, what is mandatory in the node configs. My setup is this: Node config files: all the devices are physical LG K11: { "capabilities": [ { "deviceName":"xxxxxxx", "version":"7.1.2", "platformName":"Android", "automationName": "Appium”, "udid":"xxxxxxx" } ], "configuration": { "cleanUpCycle":3000, "timeOut":300000, "proxy":"org.openqa.grid.selenium.proxy.DefaultRemoteProxy", "url":"http://127.0.0.1:4723/wd/hub", "host":"127.0.0.1", "port": 4723, "register": true, "registerCycle": 5000, "hubPort":4444, "hubHost":"127.0.0.1", "hubProtocol": "http" } } Samsung Tablet S4: { "capabilities": [ { "deviceName":"xxxxxxx", "version":"8.1.0", "platformName":"Android", "automationName": "Appium", "udid":"xxxxxxx" } ], "configuration": { "cleanUpCycle":3000, "timeOut":300000, "proxy":"org.openqa.grid.selenium.proxy.DefaultRemoteProxy", "url":"http://127.0.0.1:4492/wd/hub", "host":"127.0.0.1", "port":4492, "register": true, "registerCycle": 5000, "hubPort":4444, "hubHost":"127.0.0.1", "hubProtocol": "http" } } Samsung Galaxy S9: { "capabilities": [ { "deviceName":"xxxxxxx", "version":"8.0.0", "platformName":"Android", "automationName": "Appium", "udid":"xxxxxxx" } ], "configuration": { "cleanUpCycle":3000, "timeOut":300000, "proxy":"org.openqa.grid.selenium.proxy.DefaultRemoteProxy", "url":"http://127.0.0.1:8201/wd/hub", "host":"127.0.0.1", "port":8201, "register": true, "registerCycle": 5000, "hubPort":4444, "hubHost":"127.0.0.1", "hubProtocol": "http" } } I start the nodes by executing the following commands in 4 separate terminal tabs: 1)java -jar selenium-server-standalone-3.141.59.jar -role hub 2)appium -p 4723 --nodeconfig= /LG_K11.json 3)appium -p 4492 --nodeconfig= /Samsung_Tab_S4.json 4)appium -p 8201 --nodeconfig= /Samsung_Galaxy_S9.json Then in IntelliJ I run this code to initialise the nodes: I only change the ports, udid and deviceName capabilities and I run the initialisation methods in separate threads and wait for all of them to finish. initDevice(String udid, int port){ DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability("platformName", "Android"); capabilities.setCapability("deviceName",udid ); capabilities.setCapability("appPackage", “xxxxxxxxx”); capabilities.setCapability("appActivity","MainActivity"); capabilities.setCapability("platformName","Android"); capabilities.setCapability("udid",udid); capabilities.setCapability("noReset", true); try { String appiumServerURL = String.format("http://127.0.0.1:%d/wd/hub", port); driver = new AndroidDriver(new URL(appiumServerURL), desiredCapabilities); } catch (MalformedURLException e) { e.printStackTrace(); } } And after initialising, when I try to execute any command, such as findElement, I get this crash on one of the devices: org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. Original error: Android bootstrap socket crashed: Error: This socket has been ended by the other party Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03' System info: host: ‘xxxxxx’, ip: ‘xxxxxxxxxx’, os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.14.3', java.version: '1.8.0_191' Driver info: io.appium.java_client.android.AndroidDriver Capabilities {appActivity: MainActivity, appPackage: xxxxxxxxxx, databaseEnabled: false, desired: {appActivity: MainActivity, appPackage: xxxxxxxx, deviceName: xxxxxx, noReset: true, platformName: android, udid: xxxxxxxx}, deviceManufacturer: samsung, deviceModel: SM-G960F, deviceName: xxxxxxx, deviceScreenSize: 1440x2960, deviceUDID: xxxxxxx, javascriptEnabled: true, locationContextEnabled: false, networkConnectionEnabled: true, noReset: true, platform: LINUX, platformName: Android, platformVersion: 8.0.0, takesScreenshot: true, udid: xxxxxxxxxx, warnings: {}, webStorageEnabled: false} Session ID: xxxxxxxx *** Element info: {Using=xpath, value=//android.widget.ImageView[@content-desc="More options"]} at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187) at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122) at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49) at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158) at io.appium.java_client.remote.AppiumCommandExecutor.execute(AppiumCommandExecutor.java:239) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552) at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:42) at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1) at io.appium.java_client.android.AndroidDriver.execute(AndroidDriver.java:1) at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:323) at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:62) at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1) at io.appium.java_client.android.AndroidDriver.findElement(AndroidDriver.java:1) at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:428) at io.appium.java_client.DefaultGenericMobileDriver.findElementByXPath(DefaultGenericMobileDriver.java:152) at io.appium.java_client.AppiumDriver.findElementByXPath(AppiumDriver.java:1) at io.appium.java_client.android.AndroidDriver.findElementByXPath(AndroidDriver.java:1) at org.openqa.selenium.By$ByXPath.findElement(By.java:353) at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:315) at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:58) at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1) at io.appium.java_client.android.AndroidDriver.findElement(AndroidDriver.java:1) at org.openqa.selenium.support.ui.ExpectedConditions$7.apply(ExpectedConditions.java:205) at org.openqa.selenium.support.ui.ExpectedConditions$7.apply(ExpectedConditions.java:201) at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:249) at xxxxxxxxx.BaseScreen.waitAndFind(BaseScreen.java:77) at xxxxxxxxx.screens.BaseScreen.waitAndFind(BaseScreen.java:73) at xxxxxxxxx.screens.MainScreen.getBroadcastOptionsButton(MainScreen.java:23) at xxxxxxxxx.tests.PositiveFlows.userClicksBroadcastOptionsMenu(PositiveFlows.java:400) at xxxxxxxxx.tests.PositiveFlows.tc5(PositiveFlows.java:316) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.junit.runner.JUnitCore.run(JUnitCore.java:160) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. Original error: Android bootstrap socket crashed: Error: This socket has been ended by the other party Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03' System info: host: xxxxxxx, ip: xxxxxxxx, os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.14.3', java.version: '1.8.0_191' Driver info: io.appium.java_client.android.AndroidDriver Capabilities {appActivity: MainActivity, appPackage: xxxxxxx, databaseEnabled: false, desired: {appActivity: MainActivity, appPackage: xxxxxxx, deviceName: xxxxxxx, noReset: true, platformName: android, udid: xxxxxxx}, deviceManufacturer: samsung, deviceModel: SM-G960F, deviceName: xxxxxxx, deviceScreenSize: 1440x2960, deviceUDID: xxxxxxx, javascriptEnabled: true, locationContextEnabled: false, networkConnectionEnabled: true, noReset: true, platform: LINUX, platformName: Android, platformVersion: 8.0.0, takesScreenshot: true, udid: xxxxxxx, warnings: {}, webStorageEnabled: false} Session ID: xxxxxxx at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187) at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122) at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49) at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158) at io.appium.java_client.remote.AppiumCommandExecutor.execute(AppiumCommandExecutor.java:239) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552) at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:46) at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1) at io.appium.java_client.android.AndroidDriver.execute(AndroidDriver.java:1) at org.openqa.selenium.remote.RemoteWebDriver.quit(RemoteWebDriver.java:452) at xxxxxxx.tests.PositiveFlows.tearDown(PositiveFlows.java:476) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:33) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.junit.runner.JUnitCore.run(JUnitCore.java:160) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) A: Solved it, the problem was that I needed to pass a bootstrap port, because they were conflicting. So added "-bp 1020x" to the commands. Before: appium -p 4723 --nodeconfig= /LG_K11.json After: appium -p 4723 -bp 10200 --nodeconfig= /LG_K11.json This link might help for people facing issues in the future: https://dpgraham.github.io/appium-docs/setup/parallel_tests/
{ "pile_set_name": "StackExchange" }
Q: textfield becomeFirstResponder gives EXC_BAD_ACCESS code I have two textfields; on tap of one I open a pickerView and on tap of next textfield I want to remove above opened picker from view and open keyboard but using [textfield becomeFirst Responder] in textFieldShouldBeginEditing textfield delegate method I get EXC_BAD_ACCESS code crash. The code is as such: - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField { if (textField == earningCodeTextField) { [self dismissKeyboard]; [self showPickerView]; return NO; } else if (textField == codeTextField) { [self hidePickerView]; [codeTextField becomeFirstResponder]; return YES; } return YES; } A: Calling [codeTextField becomeFirstResponder]; in the textFieldShouldBeginEditing: will call the be textFieldShouldBeginEditing: again and this might cause the error. You should not call [codeTextField becomeFirstResponder]; because it is already becoming the first responder.
{ "pile_set_name": "StackExchange" }
Q: Find the 2 distinct highest values in an array I want to know if there is a way to improve my code. It finds the two highest values in an array, and these numbers need to be distinct. I don't want to sort the values; I just want to find them. My idea is to create a new array if the length is even and compare the pair of values to find the minimum and maximum values. So, later, I find the second highest value. package doze; public class Elementos { public int maxValue(int array[], int arrayLength) { arrayLength = array.length; if ((arrayLength % 2) > 0) { arrayLength++; int aux[] = array; array = new int[arrayLength]; for (int i = 0; i < aux.length; i++) { array[i] = aux[i]; } array[(arrayLength - 1)] = aux[(arrayLength - 2)]; } int maxValue = array[0]; int minValue = array[0]; int i = 0; while (i != arrayLength) { if (array[i] > array[i + 1]) { if (array[i] > maxValue) { maxValue = array[i]; } if (array[i + 1] < minValue) { minValue = array[i + 1]; } } else { if (array[i + 1] > maxValue) { maxValue = array[i + 1]; } if (array[i] < minValue) { minValue = array[i]; } } i += 2; } int secondMaxValue = minValue; i = 0; while (i != arrayLength) { if ((array[i] > minValue) && (array[i] < maxValue)) { minValue = array[i]; secondMaxValue = minValue; } i += 1; } return maxValue; } } A: Here's a simple implementation which will return the max (first index in return array) and second distinct max (second index in return array) value as an array. If the list is size zero or there is no distinct max value, then Integer.MIN_VALUE is returned. /** * @param integer array * @return an array comprising the highest distinct value (index 0) and second highest distinct * value (index 1), or Integer.MIN_VALUE if there is no value. */ public int[] findTwoHighestDistinctValues(int[] array) { int max = Integer.MIN_VALUE; int secondMax = Integer.MIN_VALUE; for (int value:array) { if (value > max) { secondMax = max; max = value; } else if (value > secondMax && value < max) { secondMax = value; } } return new int[] { max, secondMax }; } A: I'd be somewhat surprised if the code is correct, but even if it is, it has a lot of pointless stuff - comparing in pairs, aux array, minValue. A much better way is to find the max value, and the max value that's smaller than the first max. The naive way is to iterate through the array twice, but it can actually be done by iterating only once and updating both variables. One important question (to the initial problem) is what to do if the array does not contain 2 different values. A: Aside from corner case testing like no two distinct max values. If you assume an array size of at least two, and this might be more valid C# than java but.... int max1 = Math.Max(array[0], array[1]); int max2 = Math.Min(array[0], array[1]); if(max1 == max2) max2 = Int.MinValue; //for loop 2...array length int curr = array[idx]; if(curr > max1) { max2 = max1; max1 = curr; } else if(curr > max2 && curr != max1) { max2 = curr; }
{ "pile_set_name": "StackExchange" }
Q: Virtual inheritance and empty vtable in base class There is this code: #include <iostream> class Base { int x; }; class Derived : virtual public Base { int y; }; int main() { std::cout << sizeof(Derived) << std::endl; // prints 12 return 0; } I have read that when some class is virtually inherited then there is created empty vtable for class Derived, so memory layout is as follows: Derived::ptr to empty vtable Derived::y Base::x and it is 12 bytes. The question is - what is purpose of this empty vtable if there are not any virtual methods and how is it used? A: Derived needs some way to know where the Base subobject is. With virtual inheritance, the relative location of the base class is not fixed with respect to the location of the derived class: it may be located anywhere in the full object. Consider a more typical example involving diamond inheritance. struct A { int a; }; struct B1 : virtual A { int b1; }; struct B2 : virtual A { int b2; }; struct C : B1, B2 { int c; }; Here, both B1 and B2 derive virtually from A, so in C, there is exactly one A subobject. Both B1 and B2 need to know how to find that A subobject (so that they can access the a member variable, or other members of A if we were to define them). This is what the vtable is used for in this case: both B1 and B2 will have a vtable that contains the offset of the A subobject. To demonstrate what a compiler might do to implement the above diamond inheritance example, consider the following class layouts and virtual tables, generated by the Visual C++ 11 Developer Preview. class A size(4): +--- 0 | a +--- class B1 size(12): +--- 0 | {vbptr} 4 | b1 +--- +--- (virtual base A) 8 | a +--- class B2 size(12): +--- 0 | {vbptr} 4 | b2 +--- +--- (virtual base A) 8 | a +--- class C size(24): +--- | +--- (base class B1) 0 | | {vbptr} 4 | | b1 | +--- | +--- (base class B2) 8 | | {vbptr} 12 | | b2 | +--- 16 | c +--- +--- (virtual base A) 20 | a +--- and the following vtables: B1::$vbtable@: 0 | 0 1 | 8 (B1d(B1+0)A) B2::$vbtable@: 0 | 0 1 | 8 (B2d(B2+0)A) C::$vbtable@B1@: 0 | 0 1 | 20 (Cd(B1+0)A) C::$vbtable@B2@: 0 | 0 1 | 12 (Cd(B2+0)A) Note that the offsets are relative to the address of the vtable, and note that for the two vtables generated for the B1 and B2 subobjects of C, the offsets are different. (Also note that this is entirely an implementation detail--other compilers may implement virtual functions and bases differently. This example demonstrates one way that they are implemented, and they are very commonly implemented this way.)
{ "pile_set_name": "StackExchange" }
Q: New notation : $f[0,0.1,0.2,0.3,0.4]$ I came across this question: Suppose $f(x)=x^3-x+\frac{1}{4}$, What's the value of $f [0,0.1,0.2,0.3,0.4]$? The problem is, I have no idea what is being asked, I'm unfamiliar with the notation "$f[0,0.1,0.2,0.3,0.4]$". A: This notation is used for divided differences, so perhaps that is what you are being asked to calculate. Giving a context for the question would help: divided differences arise in polynomial interpolation.
{ "pile_set_name": "StackExchange" }
Q: Can't make sqlite3 work on Ruby on Rails I just installed ruby on my windows 7 computer. I installed rails and sqlite3 with the gem. I then made my app work on local BUT I still seem to have problems with sqlite3. When I try this: rake db:create the only thing i get is an error: Please install the sqlite3 adapter: "gem install activerecord-sqlite3-adapter" (sqlite3 is not part of the bundle. Add it to the GemFile). I've been doing some digging here and there, and I could make this error go away adding this line to my GemFile: gem "sqlite3", group: :sqlite3 And i got a new error: no driver for sqlite3 found I tried the 'bundle' command and I have both sqlite3 and sqlite3-ruby, I reinstalled everything but the problem won't go away. This is my gemFile, I hope it helps: source 'https://rubygems.org' gem 'rails', '3.2.12' # Bundle edge Rails instead: # gem 'rails', :git => 'git://github.com/rails/rails.git' #I tried this too, but nothig changes #gem 'sqlite3-ruby', :require => 'sqlite3' gem 'sqlite3-ruby', '1.2.5', :require => 'sqlite3' gem "sqlite3", group: :sqlite3 # Gems used only for assets and not required # in production environments by default. group :assets do gem 'sass-rails', '~> 3.2.3' gem 'coffee-rails', '~> 3.2.1' # See https://github.com/sstephenson/execjs#readme for more supported runtimes # gem 'therubyracer', :platforms => :ruby gem 'uglifier', '>= 1.0.3' end gem 'jquery-rails' I really don't know what to do. It's kind of frustrating, it seems like something is not (obviously) properly working with sqlite3, because fixing one error leads to a new error. How can I possibly fix this problem ? A: To everybody who's going to have this problem. What I did to fix it was uninstall everything. I though that maybe since I had an updated version of everything, something might not be working properly, maybe some dependencies were wrongly addressed. So I reinstalled everything following this: Rails Installer Website Which will make you install everything you need to run your first RoR app. It might not be up to date but it works just fine. Sqlite3 works perfectly now and that was what I needed. I might try to update every single program later, right now I just need something that is actually working. Thanks to everybody else who tried to help.
{ "pile_set_name": "StackExchange" }
Q: What is the difference between XAMPP or WAMP Server & IIS? I want to know what's the main difference between XAMPP or WAMP Server & IIS Server? A: WAMP is an acronym for Windows (OS), Apache (web-server), MySQL (database), PHP (language). XAMPP and WampServer are both free packages of WAMP, with additional applications/tools, put together by different people. There are also other WAMPs such as UniformServer. And there are commercial WAMPs such as WampDeveloper (what I use). Their differences are in the format/structure of the package, the configurations, and the included management applications. IIS is a web-server application just like Apache is, except it's made by Microsoft and is Windows only (Apache runs on both Windows and Linux). IIS is also more geared towards using ASP.NET (vs. PHP) and "SQL Server" (vs. MySQL), though it can use PHP and MySQL too. A: WAMP: acronym for Windows Operating System, Apache(Web server), MySQL Database and PHP Language. XAMPP: acronym for X (any Operating System), Apache (Web server), MySQL Database, PHP Language and PERL. XAMPP and WampServer are both free packages of WAMP, with additional applications/tools, put together by different people. Their differences are in the format/structure of the package, the configurations, and the included management applications. In short: XAMPP supports more OSes and includes more features A: WAMP [ Windows, Apache, Mysql, Php] XAMPP [X-os, Apache, Mysql, Php , Perl ] (x-os : it can be used on any OS ) Both can be used to easily run and test websites and web applications locally. WAMP cannot be run parallel with XAMPP because with default installation XAMPP gets priority and it takes up ports. WAMP easy to setup configuration in. WAMPServer has a graphical user interface to switch on or off individual component softwares while it is running. WAMPServer provide an option to switch among many versions of Apache, many versions of PHP and many versions of MySQL all installed which provide more flexibility towards developing while XAMPPServer doesn't have such an option. If you want to use Perl with WAMP you can configure Perl with WAMPServer http://phpflow.com/perl/how-to-configure-perl-on-wamp/ but it is better to go with XAMPP. XAMPP is easy to use than WAMP. XAMPP is more powerful. XAMPP has a control panel from that you can start and stop individual components (such as MySQL,Apache etc.). XAMPP is more resource consuming than WAMP because of heavy amount of internal component softwares like Tomcat , FileZilla FTP server, Webalizer, Mercury Mail etc.So if you donot need high features better to go with WAMP. XAMPP also has SSL feature which WAMP doesn't.(Secure Sockets Layer (SSL) is a networking protocol that manages server authentication, client authentication and encrypted communication between servers and clients. ) IIS acronym for Internet Information Server also an extensible web server initiated as a research project for for Microsoft NT.IIS can be used for making Web applications, search engines, and Web-based applications that access databases such as SQL Server within Microsoft OSs. . IIS supports HTTP, HTTPS, FTP, FTPS, SMTP and NNTP.
{ "pile_set_name": "StackExchange" }
Q: Jquery validator is not un-highlighting "chosen" select box I am using Chosen with jquery valodation. you can see this example: http://jsfiddle.net/hfdBF/9/ if you click submit, you see that the validation is working for combo and input. if you put one letter in the input box you will get an alert that the letter un-highlighted, as it suppose to be. BUT, if you choose in the select box a value, it wont be alert as un-highlighted. do you have any idea how to get that to work? $(function() { var $form = $("#form1"); $(".chzn-select").chosen({no_results_text: "No results matched"}); $form.validate({ errorLabelContainer: $("#form1 div.error"), wrapper: 'div', }); var settings = $.data($form[0], 'validator').settings; settings.ignore += ':not(.chzn-done)'; settings.unhighlight= function(el){ alert(el.name + " hit unhighlight") } });​​ Thanks A: You don't need to do the validation manually. You can bind a function to the change event handler that will check if the specific select is valid. This will also clear the error if the select is valid. $('.chzn-select').change(function () { $(this).valid(); });
{ "pile_set_name": "StackExchange" }
Q: gem installation error Whenever I try installing anything using gem, I get this error - murtaza@murtaza-dev:~$ sudo gem install rhc [sudo] password for murtaza: Invalid gemspec in [/var/lib/gems/1.8/specifications/commander-4.1.2.gemspec]: invalid date format in specification: "2012-02-17 00:00:00.000000000Z" Invalid gemspec in [/var/lib/gems/1.8/specifications/commander-4.1.2.gemspec]: invalid date format in specification: "2012-02-17 00:00:00.000000000Z" I am using rvm, but it seems it is pulling gems from the dir other than rvm. How do I remedy it? It is also using the ruby installation from rvm as per below - murtaza@murtaza-dev:~$ which ruby /home/murtaza/.rvm/rubies/ruby-1.9.2-p320/bin/ruby A: Seems like you are using the system ruby, which is the default for your RVM and means it uses system paths instead of RVM paths. RVM paths are used with rubies that are installed via RVM. That's probably why you are seeing these paths.
{ "pile_set_name": "StackExchange" }
Q: What is the color group name in the UI image? I am actually developer not a graphic designer. I want to know these color groups name. They look like ocean colors but there has to be an official graphic design name. What is the color group name for that? https://tr.pinterest.com/pin/565412928200221463/ And I don't know "color group name" is the true definition anyway. Thank you. A: In general not all ranges have names even the ones that do are very diffuse. But as of a rule of thumbs there are characterizations for colors. So colors have a temperature and you can differentiate between warm or cool colors. In this case you can find a bunch of cool gradients* by doing a image search on google. But as you can see there are quite many cool color ranges. We can also call colors saturated or unsaturated, muddy or clear and so on. One problem is that we as humans can not really distinguish color names, so while its possible to give hundreds or even thousands of names to colors. People wont actually agree with each others on these points. So for example while you and i would agree there is such colors as pastels, we do not agree where pastels begin and where they cease to be pastel colored. * In this case it does not really help that we call cold things cool as well as awesome, or swell. So a warm gradient might be awesome and somebody would call that cool. That is people for you.
{ "pile_set_name": "StackExchange" }
Q: Rails 3, Haml, Javascript - how to put javascript's variable into a partial I have image upload, where I check, how big part of image is already uploaded - I do it this way: jQuery - displaying progress bar --- uploader.bind('FilesAdded', function(up, files) { $.each(files, function(i, file) { $('#filelist').append('#{escape_javascript(render(:partial => "form", :locals => {:file_id => file.id}))}'); }); up.refresh(); uploader.start(); }); uploader.bind('UploadProgress', function(up, file) { $('#'+file.id).find('strong').html('<span>' + file.percent + "%</span>"); $('#'+file.id).find('.bar').css('width',file.percent+"%"); }); form.html.haml --- #form_data %div{:id => file_id, :style => "width:330px;"} ... And I am getting the error undefined local variable or method `file' for #<#<Class:0x0000010161c0b8>:0x0000012a3b1f20> Originally, I had the project in the ERB and on the place, where is now rendering of the partial file was the content of this file - but now I converted the project to HAML and the code for displaying "progress bar" moved the code to the partial file, but now I am getting this error... Could anyone help me, please, how to fix this problem? Thank you A: It looks like you're trying to include javascript in your HAML file. If so, you should use the :javascript HAML filter http://haml-lang.com/docs/yardoc/file.HAML_REFERENCE.html#javascript-filter in your partial. :javascript uploader.bind('FilesAdded', function(up, files) { $.each(files, function(i, file) { $('#filelist').append('#{escape_javascript(render(:partial => "form", :locals => {:file_id => file.id}))}'); }); ...
{ "pile_set_name": "StackExchange" }
Q: Animation in Cocos2d android not working I have been trying to animate a sprite with different frames with no luck. Nothing happens. I have 12 Images (loading1.png to loading12.png). How can I animate it? This is my code CCAnimation animation = CCAnimation.animation("frameanimation", 2.0f); for(int i = 0; i < 12; i++){ animation.addFrame(CCSpriteFrameCache.sharedSpriteFrameCache().spriteFrameByName("gfx/loading/loading" + (i + 1) + ".png")); } CCAction action = CCAnimate.action(2.0f, animation, true); this.runAction(action); A: Use your images (loading1.png to loading12.png) to make a texture using TexturePacker, which will generate the texture file and a data(plist) file. Then follow the following steps: CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile(plistFile); CCSpriteBatchNode* batchNode = CCSpriteBatchNode::create(pngTextureFile); this->addChild(batchNode); CCSprite* sprite = CCSprite::createWithSpriteFrameName("first_frame_name"); CCArray* frames = new CCArray; frames->initWithCapacity(frameCount); for (int i = 1; i < frameCount; i++) { CCString* frameName = CCString::createWithFormat("1-%d.png",i); frames->addObject(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(frameName->getCString())); } CCAnimation* animation = new CCAnimation; bool isLoaded = animation->initWithSpriteFrames(frames); sprite->runAction(CCAnimate::create(animation)); batchNode->addChild(sprite);
{ "pile_set_name": "StackExchange" }
Q: jQuery's .each() looping I have this script where it loops through an array and its supposed to check if each of the values within the array is an email with this function: function isEmail(email) { var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; return regex.test(email); } Supposed to look through array: $.each(arrayEmail,function(i){ var checkEmail = isEmail(arrayEmail[i]); if(checkEmail != false){ alert(arrayEmail[i]); var message = $('#sendMsg textarea.emailMsg').val(); $.ajax({ type:'post', url:'ajax_inviteMsg.php', data: 'to='+$.trim(arrayEmail[i])+'&message='+message, success: function(data){ alert(data); } }); } }); The alert(arrayEmail[i]); after checking if email if false or not only displays first value, which tells me that it only iterates through the if statement one, however, I've tested the emails and should be working doesn't get passed through that if statement. If the alert right after the each function, it iterates through the values corretly. Again, the emails are true and should be iterating through the if statement as true. I just want to know what I'm doing wrong that it only passes the if statement once if there's multiple values in the array. Thanks EDIT I also have this before the each function <div>[email protected], [email protected]</div> var emails = $('div').text(); var arrayEmail = emails.split(','); A: After you split text of div element your array becomes this: element0 = "[email protected]" element1 = " [email protected]" 2nd element has leading space and fails to match regular expression. Try with this div: [email protected],[email protected] without space and you will understand. On the end trim string before validating it.
{ "pile_set_name": "StackExchange" }
Q: How to create simple restful api for login and signup using node.js mongodb express.js How to create restful api using node.js, express.js and mongo db. I need how to write the schema for login and sign up pages and how to compare the data with mongodb using nodejs express js. I am beginner to nodejs please help me with some examples. A: //the simple example of login// router.post('/users/login', function (req, res) { var users = req.app; var email = req.body.email; var password = req.body.password; if (email.length > 0 && password.length > 0) { users.findOne({email: email, password: password}, function (err, user) { if (err) { res.json({status: 0, message: err}); } if (!user) { res.json({status: 0, msg: "not found"}); } res.json({status: 1, id: user._id, message: " success"}); }) } else { res.json({status: 0, msg: "Invalid Fields"}); } }); //and if you have to create schema var db_schema = new Schema({ email: {type: String, required: true, unique: true}, password: {type: String, required: true, unique: true}, }); // define this in your db.js var login_db = mongoose.model('your_db_name', db_schema); return function (req, res, next) { req.app = login_db; next(); };
{ "pile_set_name": "StackExchange" }
Q: Angular 2 Material transclusion, selectors and attribute directives I'm currently looking at the github and docs for the angular material 2. I'm trying to buid my own components for my app following how these material components have been structured. I'm wondering about the reasons that some selections within the component contain multiple selectors. For example, I'm looking at the mat-card on github and more importantly, mat-card-header. <ng-content select="[mat-card-avatar], [matCardAvatar]"></ng-content> <div class="mat-card-header-text"> <ng-content select="mat-card-title, mat-card-subtitle, [mat-card-title], [mat-card-subtitle], [matCardTitle], [matCardSubtitle]"></ng-content> </div> <ng-content></ng-content> The above is the html for mat-card-header which can be seen here: mat-card-header. And here is the directive in the typescript: @Directive({ selector: `mat-card-title, [mat-card-title], [matCardTitle]`, host: { 'class': 'mat-card-title' } }) export class MatCardTitle {} What is the benefit or reason of having these 3 selectors. mat-card-title, [mat-card-title], [matCardTitle]? A: The benefit is a robust component library for the adopters of your package. In the mat-card-title example this allow users to use the directive in a way that best fits their use case. Such as... <mat-card-title>My Title</mat-card-title> <div class="mat-card-title">My Title</div> <div class="matCardTitle">My Title</div> <div mat-card-title>My Title</div>
{ "pile_set_name": "StackExchange" }
Q: The comment /* */ don't work when a string include "*/" The comment of Code 1 works well in Android Studio. After I insert the chars "*/" to the string s, the comment of Code 2 cause error, how can I fix it? Thanks! Code 1 /* String s=""; */ Code 2 /* String s="*/"; */ A: The only possibility to use a multi-line comment is to change your code to an equivalent code that doesn't include the */ in the string. For example: Splitting */ in two strings /* String s = "*" + "/"; */ Or using a constant public static final String END_COMMENT = "*/"; /* String s = END_COMMENT; */ Or writing as unicode chars /* String s = "\U002A\U002F"; */ All this solutions are useful if you have many lines to comment. If you have only one you can use the single line comment as follow: //String s = "*/";
{ "pile_set_name": "StackExchange" }
Q: Shortcut for plucking two attributes from an ActiveRecord object? Is there a shorter way to do the following ( @user.employees.map { |e| { id: e.id, name: e.name } } # => [{ id: 1, name: 'Pete' }, { id: 2, name: 'Fred' }] User has_many employees. Both classes inherit from ActiveRecord::Base. Two things I don't like about the above It loads employees into memory before mapping, It's verbose (subjective I guess). Is there a better way? A: UPDATE: see @jamesharker's solution: from ActiveRecord >= 4, pluck accepts multiple arguments: @user.employees.pluck(:id, :name) PREVIOUS ANSWER: for a single column in rails >= 3.2, you can do : @user.employees.pluck(:name) ... but as you have to pluck two attributes, you can do : @user.employees.select([:id, :name]).map {|e| {id: e.id, name: e.name} } # or map &:attributes, maybe if you really need lower-level operation, just look at the source of #pluck, that uses select_all A: In ActiveRecord >= 4 pluck accepts multiple arguments so this example would become: @user.employees.pluck(:id, :name) A: If you are stuck with Rails 3 you can add this .pluck_all extension : http://meltingice.net/2013/06/11/pluck-multiple-columns-rails/
{ "pile_set_name": "StackExchange" }
Q: How to strip comments from Javascript using PHP I want to remove the comments from these kind of scripts: var stName = "MyName"; //I WANT THIS COMMENT TO BE REMOVED var stLink = "http://domain.com/mydomain"; var stCountry = "United State of America"; What is (the best) ways of accomplish this using PHP? A: The best way is to use an actual parser or write at least a lexer yourself. The problem with Regex is that it gets enormously complex if you take everything into account that you have to. For example, Cagatay Ulubay's suggested Regex'es /\/\/[^\n]?/ and /\/\*(.*)\*\// will match comments, but they will also match a lot more, like var a = '/* the contents of this string will be matches */'; var b = '// and here you will even get a syntax error, because the entire rest of the line is removed'; var c = 'and actually, the regex that matches multiline comments will span across lines, removing everything between the first "/*" and here: */'; /* this comment, however, will not be matched. */ While it is rather unlikely that strings contain such sequences, the problem is real with inline regex: var regex = /^something.*/; // You see the fake "*/" here? The current scope matters a lot, and you can't possibly know the current scope unless you parse the script from the beginning, character for character. So you essentially need to build a lexer. You need to split the code into three different sections: Normal code, which you need to output again, and where the start of a comment could be just one character away. Comments, which you discard. Literals, which you also need to output, but where a comment cannot start. Now the only literals I can think of are strings (single- and double-quoted), inline regex and template strings (backticks), but those might not be all. And of course you also have to take escape sequences inside those literals into account, because you might encounter an inline regex like /^file:\/\/\/*.+/ in which a single-character based lexer would only see the regex /^file:\/ and incorrectly parse the following /*.+ as the start of a multiline comment. Therefore upon encountering the second /, you have to look back and check if the last character you passed was a \. The same goes for all kinds of quotes for strings.
{ "pile_set_name": "StackExchange" }