text
stringlengths
64
81.1k
meta
dict
Q: Java: How to call upon a method in a main class where the method is in another class which extends an abstract class I have been asked to create a main method that allows me to create a wolf object, parrot object and rhino object, I have created classes for each of these animals and they extend the abstract class animal which contains an abstract method makeNoise(). I have implemented this abstract method within my rhino, parrot and wolf classes and the method contains a System.out.println function and the noise associated with each of these animals. For example my parrot class(which extends animal) contains a method makeNoise() which prints out "squawk". I have been asked to demonstrate that I can call upon this makeNoise method for each of my animal objects in the main class, how do I go about doing this? public class Main() { Wolf myWolf = new Wolf(); //I want my wolf to make a noise here Parrot myParrot = new Parrot(); //I want my parrot to make a noise here Rhino myRhino = new Rhino(); //I want my rhino to make a noise here } A: Your code is not even valid Java, you're mixing class and method semantics (and, most likely, the concepts behind them). Your class will need a main method to make your class executable from the outside. public class Main { Wolf myWolf = new Wolf(); Parrot myParrot = new Parrot(); Rhino myRhino = new Rhino(); public static void main(String[] args) { myWolf.makeNoise(); myParrot.makeNoise(); myRhino.makeNoise(); } }
{ "pile_set_name": "StackExchange" }
Q: Let's burn the [mouseless] tag While scrolling through tags aimlessly (yes i'm that bored) i came across the mouseless tag. This tag has no wiki, and has only been used 5 times... All by the same user. I say we burn it. A: It has been done. Didn't seem to be adding any value.
{ "pile_set_name": "StackExchange" }
Q: Not working, clickable div containing image I'm trying to make a div containing an image clickable. I have tried all the techniques on Hyperlinking an image using CSS (and acknowledge that it shouldn't really be done in css), and also looked elsewhere for any clues. At first I thought it was because I hadn't set the size of the div to that of the image, but I still cannot get this to work. Any ideas would be appreciated. the page where I'm trying this out is here: http://..., i.e., attempting to make the lighthouse graphic clickable (using any technique). A: You just have to change the padding-left for margin-left on the div with id="pagetext" in the style attribute, and everything shall work. <div id="pagetext" class="animated bounceInDown" style="width: 50%; margin-left: 25%; padding-top: 10px; text-align: center;"> <div class="line"></div> <p style="line-height: 20px; margin-top: 10px; margin-bottom: 0px; text-align: justify;"></p> <br> <br> <p style="line-height: 20px; margin-top: 10px; margin-bottom: 0px; text-align: justify;"></p> <br> <br> <p style="line-height: 20px; margin-top: 10px; margin-bottom: 0px; text-align: justify;"></p> <br> <br> <p style="line-height: 20px; margin-top: 10px; margin-bottom: 10px; text-align: justify;"></p> <div class="line"></div></div>
{ "pile_set_name": "StackExchange" }
Q: Wrong proof: If $0$ is the only eigenvalue of a linear operator, is the operator nilpotent I am making the following claim: If $0$ is the only eigenvalue of a linear operator $T$, then $T$ is nilpotent Proof: Since $0$ is the only eigen value, the charecteristic polynomial is of the form $p(x)=x^n$. Then $T^n=0$. Doubt: But this answer suggests that we need to assume that the underlying field is algebraically closed. I cannot understand what am I doing wrong. Any idea? A: It's hard to give an answer without more or less saying what was said in the other answer. The matrix $\begin{pmatrix} 0&1\\ -1&0\\ \end{pmatrix}$ has no real eigenvalues. To see this, it's characteristic polynomial is $x^2+1$, which has no real roots. Thus every real eigenvalue is vacuously $0$, but the matrix is not nilpotent. In this case there are complex eigenvalues which are nonzero, but there are no real eigenvectors corresponding to these. However, if we were in an algebraically closed field such as $\mathbb{C}$, and $T$ had no eigenvalues, then since the characteristic polynomial splits into linear factors, i.e. is of the form $\Pi(x-\alpha_i)$, each of the $\alpha_i$ is an eigenvalue, so if they are all $0$, then the characteristic polynomial, as you say, must be $x^n$ so by Cayley-Hamilton, $T^n=0$.
{ "pile_set_name": "StackExchange" }
Q: Is it better to get values from array or declaring them each time? Example 1: $a = 'value1'; $b = 'value2'; $c = 'value3'; $x = 'value1'; $y = 'value2'; $z = 'value3'; Example 2: $var = array('value1', 'value2', 'value3'); $a = var[0]; $b = var[1]; $c = var[2]; $x = var[0]; $y = var[1]; $z = var[2]; Which example has less server resource usage? Which example is faster? A: In your neither has any impact on speed as it is trivial. If we talk about memory usage, then array uses more as it stores the same variables + reffence links (again, trivial but that is how it works). But there as other factors that you need to consider: 1.Readability - if you use array approach you code will be very dificult to trace especially in bigger functions. 2.Operations - if you use array array approach your operations with variables will be limited as things like += will break the array refference and store the values directly in variable. 3.Relations with other devs - if you use the array approach anyone else that has to work with your code will be spilling curses your way ;)
{ "pile_set_name": "StackExchange" }
Q: Symfony won't show the form submission errors when the template changed Would anyone know the solution for the issue below? Note: Symfony footer information bar (profiler) has the errors so system catches them. Template below belogs to FOSUserBundle. When I use this (original) edit page, I can see the form validation errors in the page: <form action="{{ path('fos_user_profile_edit') }}" {{ form_enctype(form) }} method="POST" class="fos_user_profile_edit"> {{ form_widget(form) }} <div> <input type="submit" value="{{ 'profile.edit.submit'|trans }}" /> </div> </form> When I use this (modified) one, I cannot see the form validation errors in the page: <form action="{{ path('fos_user_profile_edit') }}" {{ form_enctype(form) }} method="POST" class="fos_user_profile_edit"> <div>{{ form_errors(form) }}</div> <table> <tr> <td>Username</td> <td>{{ form_widget(form.username) }}</td> </tr> <tr> <td>Email</td> <td>{{ form_widget(form.email) }}</td> </tr> <tr> <td>Current Password</td> <td>{{ form_widget(form.current_password) }}</td> </tr> </table> {{ form_widget(form._token) }} <input type="submit" value="{{ 'profile.edit.submit'|trans }}" /> </form> A: You can try setting error_bubbling in your form. According to the documentation: If true, any errors for this field will be passed to the parent field or form. For example, if set to true on a normal field, any errors for that field will be attached to the main form, not to the specific field. so if error_bubbling is set to false (by default) you should display error messages for specific fields like: <tr> <td>Username</td> <td>{{ form_widget(form.username) }}</td> <td>{{ form_errors(form.username) }}</td> </tr>
{ "pile_set_name": "StackExchange" }
Q: Get thumbnail images of websites? I tried this code to get thumbnail images fo websites using Websites Screenshot DLL but the images are not displayed inside my itemscontrol and I get no errors. public void ImagesActivities() { //sep s = new sep(); var images = new ObservableCollection<sep>(); var wcf = new ServiceReferenceSites.SiteEnPlusServiceClient(); foreach (var item in wcf.GetAll()) { sep s = new sep(); s.title = item.title; s.thumbnail = (System.Drawing.Image)GetThumbImage(item.urlsite); images.Add(s); } _activityList.ItemsSource = images; } private Bitmap GetThumbImage(string s) { WebsitesScreenshot.WebsitesScreenshot _Obj; _Obj = new WebsitesScreenshot.WebsitesScreenshot(); WebsitesScreenshot.WebsitesScreenshot.Result _Result; _Result = _Obj.CaptureWebpage(s); if (_Result == WebsitesScreenshot. WebsitesScreenshot.Result.Captured) { _Obj.ImageWidth = 200; _Obj.ImageHeight = 100; _Obj.ImageFormat = WebsitesScreenshot. WebsitesScreenshot.ImageFormats.PNG; return _Obj.GetImage(); } else return null; } and this is the code of my itemscontrol: <ItemsControl x:Name="_activityList" HorizontalAlignment="Right" Margin="0,10,10,10" Width="760"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <UniformGrid Columns="5" IsItemsHost="True"/> <!--<StackPanel Orientation="Horizontal" IsItemsHost="True"/>--> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <Grid> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <Button Grid.Row="0" Margin="10,20,0,0" BorderThickness="0" Height="100" Width="200"> <Button.Background> <ImageBrush ImageSource="{Binding thumbnail}" /> </Button.Background> </Button> <TextBlock Grid.Row="1" x:Name="nom" Margin="10,0,0,0" TextAlignment="Center" Text="{Binding title}" VerticalAlignment="Center"/> </Grid> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> This is my sep class public class sep { public string title { get; set; } public System.Drawing.Image thumbnail { get; set; } } Can anyone please help me. A: Essentially you have been drawing nulls. The older style of bitmaps do not really travel that well into WPF. You can change this code... sep s = new sep(); s.title = item.title; s.thumbnail = (System.Drawing.Image)GetThumbImage(item.urlsite); to this... Sep sep = new Sep(); sep.Title = "title"; var bmp = GetThumbImage("xxx"); using (MemoryStream memory = new MemoryStream()) { bmp.Save(memory, ImageFormat.Png); memory.Position = 0; BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.StreamSource = memory; bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.EndInit(); sep.ThumbnailImage = bitmapImage; } This code runs an ad-hoc conversion on the Bitmap so that it can be used as a WPF ImageSource. The 'sep' class is declared with an ImageSource like this... public class Sep : INotifyPropertyChanged { private string _title; public string Title { [DebuggerStepThrough] get { return _title; } [DebuggerStepThrough] set { if (value != _title) { _title = value; OnPropertyChanged("Title"); } } } private ImageSource _thumbnailImage; public ImageSource ThumbnailImage { [DebuggerStepThrough] get { return _thumbnailImage; } [DebuggerStepThrough] set { if (value != _thumbnailImage) { _thumbnailImage = value; OnPropertyChanged("ThumbnailImage"); } } } #region INotifyPropertyChanged Implementation public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string name) { var handler = System.Threading.Interlocked.CompareExchange(ref PropertyChanged, null, null); if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } #endregion } In the longer run, you can consider refactoring the conversion into an IValueConverter.
{ "pile_set_name": "StackExchange" }
Q: Subseries with indexes powers of 2 Let $a_n\geq 0$ be a non-increasing sequence, $\alpha , q >0 $, and assume: $$\sum_{k=1}^\infty \frac{(k^\alpha a_k)^q}{k} \leq 1 $$ Then $$\sum_{j=0}^\infty (2^{j\alpha} a_{2^j})^q \leq c_{\alpha,q}$$ Where $c_{\alpha,q}$ depends only on $\alpha$ and $q$. If the last expression was divided by $2^j$, then this would be obvious, but how do I "get rid" of the denominator? I'm thinking Cauchy-Schwarz but didn't get very far with it. I don't know how Cauchy-Schwarz can produce a bound dependent on $\alpha$ and $q$. Any help would be appreciated. A: Notice that $$\tag{(1)}\sum_{k=1}^{+\infty}k^{\alpha q-1}\alpha_k^q=\sum_{l=0}^{+\infty} \sum_{k=2^l}^{2^{l+1}-1}k^{\alpha q-1}\alpha_k^q$$ Since $(a_k)_{k\geqslant 1}$ is non-increasing, $$\sum_{k=2^l}^{2^{l+1}-1}k^{\alpha q-1}\alpha_k^q\geqslant 2^l2^{l(\alpha q-1)}a_{2^{l+1}-1}\geqslant 2^{l\alpha q}a_{2^{l+1}},$$ we obtain by (1) and the assumption, $$\sum_{l=0}^{+\infty}2^{l\alpha q}a_{2^{l+1}}=2^{\alpha q}\sum_{j=1}^{+\infty}2^{j\alpha q}a_{2^j}\leqslant 1,$$ and the conclusion follows.
{ "pile_set_name": "StackExchange" }
Q: Let $F$ be a PRF, is the following $G(x)=F_{0…0}(x)∥F_{0…1}(x)|| ... ||F_{1…1}(x)$ a PRG? This exercise comes from Coursera's "Cryptography" course. Let $F$ be a PRF, is the following $G(x)=F_{0…0}(x)∥F_{0…1}(x)|| ... ||F_{1…1}(x)$ a PRG? $F$ is a PRF with $n$ bit key, input, and output length. I know the answer is “NO it isn't!”, but I can't understand why. Is that because on any input $x$, the keys for every $F$ in the concatenation sequence are fixed, which implies that the $F$ functions are not randomly chosen over $2^{-n}$? Could this be a possible answer? A: @fkraiem's answer is basically correct, but it only says that $G$ does not match the "syntax" of a PRG. But this is not entirely satisfactory for understanding what's really wrong with $G$ as a PRG. In addition, $G$ may not be pseudorandom. For example, it could be the case that $F_{00\cdots 0}(x) = 0$ for every $x$, i.e., the all-zeros key is a "weak" key for $F$. This would not contradict the fact that $F$ is a PRF, and this can be proved formally. But now notice that the first bit of $G(x)$ is zero for every seed $x$, which means that $G$ is clearly not a pseudorandom generator.
{ "pile_set_name": "StackExchange" }
Q: Is it OK to manually change a ReactJS component's key? I am using uncontrolled form input components in a project, and sometimes I need to clear the value on one input / a group of inputs. I've found that one easy way to do this is to manually update the component's key attribute. It works, but is it bad practice? Should I be concerned about performance / memory issues when I manually change keys? A: React uses keys to find "the same" element when diffing with the virtual DOM. Changing the key works because it tricks React into seeing your input as a new element. At a large scale, this will affect your performance, because React will be creating & destroying DOM elements, rather than only changing the altered attributes. At small scale, you probably won't see any noticeable performance hits. If you're clearing the value, it seems to me you may not truly have an uncontrolled input on your hands. After all, you are "controlling" it, to some degree. However, if this is your only reason for touching the input's value, I can see why leaving it "uncontrolled" would be appealing. I haven't tested this, but I think you should be able to set the value to an empty string programmatically by giving the element a ref and accessing the DOM element that way... my assumption is that since it is uncontrolled, React doesn't pay attention to the value attribute when diffing/rendering.
{ "pile_set_name": "StackExchange" }
Q: How can I set a session variable that is available in multiple batches? I have a large database script migrating multiple databases of the same structure to one destination database. This destination database is more generic so it is able to store the data from the different source databases. I use a variable to keep track of the current Entity being migrated so I know what ID to insert in the destination table. At this moment the migration performance is really bad. To be able to profile the script better I'd like to split up the script by placing 'go' after each table migration but this destroys the variable. Is there a way to declare a variable that is accessible for the whole connection/session? Just like a temp #table is? A: Query: DECLARE @UserID TINYINT = 1 , @LocaleID INT = 123456789 , @ApplicationID BIGINT = 123456789123456789 , @UserName VARCHAR(10) = 'User1' , @context VARBINARY(128) SELECT @context = CAST(@UserID AS BINARY(1)) + CAST(@LocaleID AS BINARY(4)) + CAST(@ApplicationID AS BINARY(8)) + CAST(@UserName AS BINARY(10)) SET CONTEXT_INFO @context GO SELECT UserID = CAST(SUBSTRING(ci, 1, 1) AS TINYINT) , LocaleID = CAST(SUBSTRING(ci, 2, 4) AS INT) , ApplicationID = CAST(SUBSTRING(ci, 6, 8) AS BIGINT) , UserName = CAST(SUBSTRING(ci, 14, 10) AS VARCHAR) FROM (SELECT ci = CONTEXT_INFO()) t Result: UserID LocaleID ApplicationID UserName ----------- ----------- ------------------ ------------------------------ 1 123456789 123456789123456789 User1 Additional info: MSDN - CONTEXT_INFO A: With SQL Server 2016 you can use sp_set_session_context: EXEC [sys].[sp_set_session_context] @key = 'SecurityObjectUserID' ,@value = @SecurityObjectUserID ,@read_only = 1; to set a variable, and the following to read it: SELECT @SecurityObjectUserID = CONVERT(BIGINT,SESSION_CONTEXT(N'SecurityObjectUserID')); Note, we can mark a variable to be read_only. In this way, other routines are not able to change it.
{ "pile_set_name": "StackExchange" }
Q: MX records of a domain - why are they editable from a hosting panel? I have a domain, registered at company A. In the domain manager panel at this company I can edit DNS records of my domain, including MX records. That's understandable. I changed them. But, the website which uses this domain is at company B. This comapany also has DNS records manager! It looks like it overwrites whatever I set at company A. How is that possible? A: toomanyairmiles is correct. once you delegate the name servers all of the dns config is going to go with it. if you're trying to lock down exactly whats happening when you do dns queries either get familiar with some command line tools or use some online dns tools such as the ones at unlocktheinbox.com. heres a link to the dns tools on their site: http://www.unlocktheinbox.com/dnslookup/mx/
{ "pile_set_name": "StackExchange" }
Q: Class of functions that the Fourier inversion holds The following is from Stein and Shakarchi's Complex Analysis: For each $a>0$ we denote by ${\mathcal F}_a$ the class of all functions $f$ that satisfy the following two conditions: The function $f$ is holomorphic in the horizontal strip $$ S_a=\{z\in{\Bbb C}:|Im(z)|<a\} $$ There exists a constant $A>0$ such that $$ |f(x+iy)|\leq\frac{A}{1+x^2}\quad\text{for all}\quad x\in{\Bbb R}, |y|<a. $$ Denote by ${\mathcal F}$ the class of all functions that belong to ${\mathcal F}_a$ for some $a$. The the Fourier inversion holds in this class. Here are my questions: Is there a name for this class? Does it have anything to do with the Schwartz space on which the Fourier transform is a linear isomorphism? A: For the sake of an answer, this is done on MO.
{ "pile_set_name": "StackExchange" }
Q: Bootstrap typeahead I am using bootstrap typeahead for auto-complete functionality. I need typeahead to return the result when the input gets active (on mouse-click or tab to the input), not wait for the user to type 1st character. More like a typedown. <input id="input01" class="input-medium" type="text" data-provide="typeahead" placeholder="TypeAhead…" autocomplete="off"> $(document).ready(function($) { // Workaround for bug in mouse item selection $.fn.typeahead.Constructor.prototype.blur = function() { var that = this; setTimeout(function () { that.hide(); }, 250); }; $('#input01').typeahead({ source: function(query, process) { return ["hello","world", "awesome"]; } }); }); A: Bootstrp combobox worked perfectly
{ "pile_set_name": "StackExchange" }
Q: wxPython button changes text on panel I'm trying to get a button press change the text on the panel but from a different function. Ex: status=wx.StaticText(panel,label="Yes",pos=(95,5),size=(50,20)) change=wx.Button(panel,label="Change",pos=(115,45),size=(50,20)) self.Bind(wx.EVT_BUTTON, self.changed, change) def changed(self,event): have it change the label to "no". Thanks A: Use self.status.SetLabel: import wx class MyFrame(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, title = title, size = (200, -1)) self.state = 'Yes' self.panel = wx.Panel(self) self.status = wx.StaticText(self.panel, label = self.state, pos = (95, 5), size = (50, 20)) self.button = wx.Button(self.panel, label = 'Change', pos = (115, 45), size = (50, 20)) self.Bind(wx.EVT_BUTTON, self.changed, self.button) def changed(self, event): self.state = 'Yes' if self.state == 'No' else 'No' self.status.SetLabel(self.state) app = wx.App(False) frame = MyFrame(None, "Hello") frame.Show() app.MainLoop()
{ "pile_set_name": "StackExchange" }
Q: WCF sending JSON, object in method always null I want to send JSON data to my WCF Service, but in the Service there is my object always null. I have read so many articles but I can't solve my problem. [WebInvoke(UriTemplate = "/POST/PersonPost", Method = "POST",BodyStyle=WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] public Person InsertPerson(Person per) { Debug.WriteLine("InsertPerson"); if (per == null) { return new Person("2", "null"); } Debug.WriteLine("POST:[PersonId = {0} PersonName = {1}]", per.Id, per.Name); return new Person("1", "InsertPerson"); } [DataContract] public class Person { public Person(string id, string name) { this.id = id; this.name = name; } [DataMember] public string Id { get; set; } [DataMember] public string Name { get; set; } public override string ToString() { var json = JsonConvert.SerializeObject(this); return json.ToString(); } } and here my jQuery: var person = {}; person.Id = "abc123"; person.Name = "aaaa"; var per = {}; per.per = person; var param = JSON.stringify(per); //param = "{"per":{"Id":"abc123","Name":"aaaa"}}" $.support.cors = true; $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", data: param, dataType: "json", processData: false, crossDomain: true, url: "http://localhost:59291/Person/POST/PersonPost", success: function (data) { alert("Post erfolgreich: "); }, error: function (xhr, ajaxOptions, thrownError) { alert("Fehler Post: Status " + xhr.status + " AntwortText " + xhr.responseText); } }); What is there wrong? Why is my parameter per in the insertPerson method always null. A: sorry my english, this work for me: var LstPerson = new Array(); var person = {}; person.Id = 1 person.name = 'abc' LstPerson.push(person) var param = JSON.stringify(LstPerson); send only [{"id": "1", "name": "abc"}] from JS, and WCF REST definition: [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)] public Person InsertPerson(List<Person> per)
{ "pile_set_name": "StackExchange" }
Q: WordPress вывод постов состоящих в двух категориях На главной странице сайта свой уникальный дизайн. Для его функциональности на главной нужно вывести популярные или важные(featured) посты из каждой категории, лежащей в родителе, который я указываю. Хочу заранее сказать что я ищу совет, а не решение. На какие функции стоит обратить внимание? Как это сделать иначе? Что не так? И т.д. Дам пример: - Родитель 1 - Потомок1 - Потомок2 - Потомок3 ... - Featured То есть нужно что бы посты, выведенные на главной одновременно состояли в 'Родитель 1' и Featured и выводились не более 6-ти штук на категорию. Это еще не все. Так же я предполагаю создать приоритет. Под каждым постом в featured будет указан приоритет(от 1-6) и в зависимости от этого будет выбираться очередность выводимых в блоке постов. Это будет реализовано через дополнительные поля (get_post_meta). На данный момент код простой: $prt=get_categories(array('hide_empty'=>0,'child_of'=>12,'orderby'=> 'id','title_li'=>'')); ... $query = new WP_Query(array('cat'=>$tid,'showposts'=>'6')); Вся его задача вытащить все категории из родителя, после чего следующая строчка вытащит из каждой по 6 постов. Дело в том что 6 последних постов и сортировки по приоритетам у них нет. Я боюсь что нужно будет писать очень большой и громоздкой код с проверками на посты и дополнительными запросами для такой задачи, может вы знаете примеры попроще? Может можно/нужно составить вовсе чистый SQL запрос где это можно сделать? A: Еcли я правильно понял: foreach ($cat_ids as $cat_id) { $query = new WP_Query(array( 'category__and' => array($cat_id, $feature_id), 'showposts' => '6', 'orderby' => 'meta_value_num', 'meta_key' => 'priority' )); // Дальше Loop по сценарию } В ролях: $cat_ids - массив с ID подкатегорий категории "Родитель 1"; $feature_id - ID категории "Featured"; 'priority' - ключ дополнительного поля приоритета поста.
{ "pile_set_name": "StackExchange" }
Q: ¿Por qué recibo el error ":RecursionError: maximum recursion depth exceeded"? from typing import List, Tuple, Dict, Union class CatalogueException(Exception): pass class StockException(Exception): pass class Product(): def __init__(self,_code,_name,_price): self._code=_code self._name=_name self._price=_price def __hash__(self): return hash(self._code) def __str__(self): return 'Code: {}\nName: {}\nPrice: {}'.format(self._code,self._name,self._price) class Catalogue(): catalogo=[] def add_product(self,p): catalogo=[] if p in catalogo: print("el producto") catalogo.append(p) def remove_product(self,p): catalogo.remove(p) def __str__(self): return('{}'.format(catalogo)) catalogo=Catalogue() new_spanner = Product("S78", "Adjustable spanner", 35.99) new_hammer = Product("A45", 'Bush hammer', 15.5) catalogo.add_product(new_spanner) catalogo.add_product(new_hammer) print(catalogo) Lo que se intenta es que imprima los dos productos añadidos al catalogo y quede de la manera: Code: A45 Name: Bush hammer Price: 15.5 Code: S78 Name: Adjustable spanner Price: 35.99 Pero al ejecutar sale el error: :RecursionError: maximum recursion depth exceeded He probado a reescribir la funcion str de diferentes maneras pero me sale el mismo error A: El problema está en la línea return('{}'.format(catalogo)) pero viene de antes, implementas mal la clase. Declaras un atributo de clase que luego no usas class Catalogue(): catalogo=[] ^^^^^^^^^^ para empezar no debe ser un atributo de clase sino de instancia, dado que cada objeto catálogo tendrá sus productos y no todos los catálogos los mismos productos (atributo de clase). Además de ello, jamás llegas a usarlo realmente, ésto se debe a que no lo referencias desde los métodos con instancia.catalogo (self.catalogo) o Catalogue.catalogo (cls.catalogo). Mírate ésta pregunta para entender la diferencia entre ambos tipos de atributos: Diferencia entre atributos de instancia y atributos de clase En los métodos de instancia usas realmente la variable global catalogo class Catalogue(): def remove_product(self,p): catalogo.remove(p) #^^^^^^^ # esto def __str__(self): return('{}'.format(catalogo)) #^^^^^^^^ # y ésto catalogo=Catalogue() #^^^^^^^^ # son ésto ésta es la razón de que termines con una recursión infinita: print(producto) llama a producto.__str__. Cuándo se evalúa return('{}'.format(catalogo)) str.format llama a producto.__str__ de nuevo. Y así hasta el infinito y más allá, bueno hasta que llegas a 1000 llamadas recursivas que es el límite por defecto que tiene Python para proteger al propio intérprete de un desbordamiento de pila. En el método add_product realmente no haces nada Sí haces realmente, pero no hay efectos fuera del mismo. Aunque catalogo es una variable global como se ha explicado, al hacer catalogo = [] (reasignación) se crea automáticamente una variable local al método que solapa la global, luego añades el producto a la lista, pero como buena variable local, en cuanto el método retorna el GC manda a la lista a mejor vida. Esa lista jamás podrá ser accedida desde fuera del método. En definitiva, debes usar un atributo de instancia y no de clase, el código podría quedar así, con anotaciones de tipo incluidas: from typing import List, Union class CatalogueException(Exception): pass class StockException(Exception): pass class Product: def __init__(self, code: str, name: str, price: Union[float, int]): self._code: str = code self._name: str = name self._price: Union[float, int] = price def __hash__(self) -> int: return hash(self._code) def __str__(self) -> str: return f'Code: {self._code}\nName: {self._name}\nPrice: {self._price}' class Catalogue: def __init__(self) -> None: self._products: List[Product] = [] def add_product(self, product: Product) -> None: self._products.append(product) def remove_product(self, product: Product) -> None: self._products.remove(product) def __str__(self) -> str: prods = "\n\n".join(str(prod) for prod in self._products) return f"{'-' * 34} CATÁLOGO {'-' * 34}\n{prods}\n{'-' * 78}" if __name__ == "__main__": catalogo = Catalogue() new_spanner = Product("S78", "Adjustable spanner", 35.99) new_hammer = Product("A45", 'Bush hammer', 15.5) catalogo.add_product(new_spanner) catalogo.add_product(new_hammer) print(catalogo) Es recomendable que no uses catalogo como nombre del atributo de la clase Catalogo, es confuso. products es un mejor nombre para la lista. El uso de _nombre es una convención para marcar atributos/métodos "privados". Es correcto su uso, pero no tiene sentido en el nombre de los argumentos en este caso.
{ "pile_set_name": "StackExchange" }
Q: Peaks, Valleys, and Slopes I have peaks and valleys and slopes Whose mountains and beats are such tropes,   And the prime, you will find,   Is a step back in time; The end, you will find, is a hoax. What am I? Hints: It's not "music." It's not "rhymes" or anything to do with poetry. It's not "waves," but is the closest guess so far (a square is a rectangle). It's not a "desert," especially since the mountains and beats portion of the limerick isn't fully satisfied. It's not "the ocean," and is, in fact, the wrong direction to take the "waves" hint. Some words are more literal than they first appear. "Tropes" has a double meaning here. A: I think it might be a RHYME. I have peaks and valleys and slopes Whose mountains and beats are such tropes, These two lines rhyme; the first is a reference to the rhythm of a poem or verse, and the second could be the same. And the prime, you will find, Is a step back in time; "Prime" with the first letter removed (a step back?) is "rime", a homophone of "rhyme". The end, you will find, is a hoax. The last line of the limerick doesn't actually rhyme with the first two - it's a hoax limerick! A: Is it a: Sinusoidal wave? -updated thanks to ace I have peaks and valleys and slopes These waves have all of these things - peaks/troughs. Whose mountains and beats are such tropes, Constructive / destructive interference of two longitudinal sound waves causes the phenomena known as beats. And the prime, you will find, Is a step back in time; The derivation of the wave is the same wave phase-shifted (or, how it would have appeared at a certain time beforehand) The end, you will find, is a hoax. Because there is no finite end to a longitudinal wave - thanks @Mark N
{ "pile_set_name": "StackExchange" }
Q: Cannot find module '@google-cloud/storage' I am using the GCP console on my browser. I have created a function as following: function listFiles(bucketName) { // [START storage_list_files] // Imports the Google Cloud client library const Storage = require('@google-cloud/storage'); // Creates a client const storage = new Storage(); storage .bucket(bucketName) .getFiles() .then(results => { const files = results[0]; console.log('Files:'); files.forEach(file => { console.log(file.name); }); }) .catch(err => { console.error('ERROR:', err); }); // [END storage_list_files] } exports.helloWorld = function helloWorld (req, res) { if (req.body.message === undefined) { // This is an error case, as "message" is required res.status(400).send('No message defined!'); } else { // Everything is ok console.log(req.body.lat); console.log(req.body.lon); listFiles("drive-test-demo"); res.status(200).end(); } } Literally all I am trying to do right now is list the files inside a bucket, if a certain HTTPS trigger comes through. my package.json file is as follows: { "name": "sample-http", "version": "0.0.1", "dependencies": { "@google-cloud/storage": "1.5.1" } } and I am getting the error "Cannot find module '@google-cloud/storage'" Most queries I have seen thus far have been resolved by using npm install, but I don't know how to do that considering that my index.js and package.json files are stored in a zip file inside a gcloud bucket. Any advice on how to solve this would be much apreciated. A: Open console, change dir to you functions project and type: npm install --save @google-cloud/storage That's all!
{ "pile_set_name": "StackExchange" }
Q: Laravel 4 Controller Templating / Blade - Correct method? I've been reading through the Laravel 4 documentation and have been making a demo application to help with learning. I couldn't find much documentation on the templating of views with blade and controllers. Which is the correct method or does it come down to personal preference? E.g. 1 Controllers/HomeController.php protected $layout = 'layouts.main'; public function showWelcome() { $this->layout->title = "Page Title"; $this->layout->content = View::make('welcome'); } Views/layouts/main.blade.php <html> <head> <title>{{ $title }}</title> </head> <body> {{ $content }} </body> </html> Views/welcome.blade.php <p>Welcome.</p> E.g. 2 Controllers/HomeController.php protected $layout = 'layouts.main'; public function showWelcome() { $this->layout->content = View::make('welcome'); } Views/layouts/main.blade.php <html> <head> <title>@yield('title')</title> </head> <body> @yield('content') </body> </html> Views/welcome.blade.php @section('title', 'Welcome') @section('content') // content @stop What is the best convention and/or advantages of the the above? A: I don't store any layout information in the controller, I store it in the view via @extends('layouts.master') When I need to return a view in the controller I use: return \View::make('examples.foo')->with('foo', $bar); I prefer this approach as the view determines what layout to use and not the controller - which is subject to re-factoring.
{ "pile_set_name": "StackExchange" }
Q: How to validate in jQuery only if all fields are blank Using jQuery validation, if I have many fields on a page, and only require ONE of them to be filled, how do I raise an error only if they are all blank. That is, the user can fill one or more fields, but if all of them are blank, there will be an error. I want to know if there is a way of doing this with jQuery validation. A: Something along these lines should work. var valid=0; $("#myform input[type=text]").each(function(){ if($(this).val() != "") valid+=1; }); if(valid){ console.log(valid + " inputs have been filled"); } else { console.log("error: you must fill in at least one field"); } See a working example here on jsFiddle
{ "pile_set_name": "StackExchange" }
Q: How to read/restore big data file (SEGY format) with C/C++? I am working on a project which needs to deal with large seismic data of SEGY format (from several GB to TB). This data represents the 3D underground structure. Data structure is like: 1st tract, 2,3,5,3,5,....,6 2nd tract, 5,6,5,3,2,....,3 3rd tract, 7,4,5,3,1,....,8 ... What I want to ask is, in order to read and deal with the data fast, do I have to convert the data into another form? Or it's better to read from the original SEGY file? And is there any existing C package to do that? A: If you need to access it multiple times and if you need to access it randomly and if you need to access it fast then load it to a database once. Do not reinvent the wheel. A: When dealing of data of that size, you may not want to convert it into another form unless you have to - though some software does do just that. I found a list of free geophysics software on Wikipedia that look promising; many are open source and read/write SEGY files. Since you are a newbie to programming, you may want to consider if the Python library segpy suits your needs rather than a C/C++ option.
{ "pile_set_name": "StackExchange" }
Q: How can I compile to Java 6 on Fedora 17 using OpenJDK I want to compile to Java 6 using OpenJDK on Fedora 17. Fedora 17 has OpenJDK7, not OpenJDK6. I am fine to target compile to Java 6 from Java 7 using -target 1.6 -source 1.6 but to do it right (avoid warning: [options] bootstrap class path not set in conjunction with -source 1.6), I also need -bootclasspath pointing to a Java 6 rt.jar file. But OpenJDK7 doesn't provide this Java 6 rt.jar file. How can I correctly compile for Java 6 on FC17? A: To install Openjdk 1.6 from Fedora 16 use this command: yum install java-1.6.0-openjdk --releasever=16 --nogpgcheck (--nogpgcheck because yum complains of not having the key for Fedora 16, maybe there are better ways to solve this) But this shows, that java-1.7.0-openjdk obsoletes java-1.6.0-openjdk and skips installation. And it shows that the package xorg-x11-fonts-Type1 is needed. So I did yum install xorg-x11-fonts-Type1 and then I used the openjdk package which yum downloaded but refused to install because of the obsoletes warning rpm --nodeps -ihv /var/cache/yum/x86_64/16/updates/packages/java-1.6.0-openjdk-1.6.0.0-68.1.11.5.fc16.x86_64.rpm (--nodeps for overriding the obsoletes warning) Now I have both java 1.6 and java 1.7 on my system. Java 1.7 is my default. And Java 1.6 is in /usr/lib/jvm/jre-1.6.0-openjdk.x86_64/bin/java. PS: There won't be any conflicts when you install both 1.7 and 1.6. The reason for removing 1.6 from Fedora 17 was, that OpenJDK6 will no longer get security updates after November 2012.
{ "pile_set_name": "StackExchange" }
Q: Matching up HomeGroup users created in different versions of Windows In our household, we have 2 laptops and a desktop, all currently on Windows 8.1. The desktop has been upgraded in stages from Windows 7. Laptop 1 was bought with Windows 8 and has now been upgraded. Laptop 2 is new and came with Windows 8.1. We've been trying to set up a HomeGroup such that we have one user on laptop 1, one on laptop 2 and both can log into the desktop, with each user able to edit their files on their laptop and desktop, while the other user has read-only access. And we now have that situation ... except ... because the user on laptop 1 was created in Windows 8 but the same user on the desktop was created in 8.1, they have different names in Windows Explorer (say, firstuser and first_000). Likewise, the other use was created on laptop 2 in Windows 8.1 and on the desktop in Windows 7 (so let's say secon_000 and seconduser). This is ultimately confusing. Now if we expand the HomeGroup, we get four users (firstuser, first_000, seconduser and secon_000) and each has a single computer inside it. What I'd like to see is firstuser => laptop1, desktop and seconduser => laptop2, desktop. An acceptable alternative is first_000 => laptop1, desktop and secon_000 => laptop2, desktop. But what I don't want to have to do is delete firstuser and seconduser and rebuild them. Is there a better way? A: Figured this out in the end. You have to go to your Microsoft account settings online. Log in and click on Edit Account Name. Change the name, save it. Then restart both computers. In future, it will log in using that alias, no matter what your underlying username is. This is the name that shows up in Homegroups in future.
{ "pile_set_name": "StackExchange" }
Q: log CPU register changes in ARM Linux I would like to know how to monitor multiple registers changes for a application in ARM linux. I know I have to debug it, but how I can automatically log all register changes in ARM linux? I know that with watch command in gdb I can do that, but is it possible to make a small c code which only run an application like a debugger, and record its register changes? Simply put, I would like to monitor CPU registers changes in ARM linux. So if I run a application, I'd like to monitor all of its register changes. Let's say I want to monitor R14. I would like to log all of the changes and the values in the R14 register, when the application is running. A: One way to go would be using gdb to single-step into your program, recording the output of info all-registers between each step. Automating this should not be a big problem IMO. However, your programs running time would be much longer.
{ "pile_set_name": "StackExchange" }
Q: How to best pitch my side project to my boss? Our company develops and markets a series of software products. I'm a software developer. I've been working on a side project for the last month and a half outside of working hours. This is a product in the same niche with everything in my company's portfolio and is strongly related to our line of business. The idea is not exactly original - it has been coined by a high-ranking employee at one of our internal hackathons as a sample project idea. Moreover I've received numerous inquiries for this functionality by our existing customers while handling their support requests. I'm ready with the MVP and I've scheduled a meeting with my manager. My current goal is to convince management that this idea is worth pursuing and ultimately have the company adopt my side project as a full-scale product of their own. I have three related questions: What is the best way to approach my manager about this? What benefits can I expect if they do, indeed, decide to adopt my project? Would it be reasonable to ask for a pay raise or a single time bonus? What's the best course of action if they decide that they are not interested in the project? Should I ask for permission to release this to the marketplace on my own? If that's not feasible should I ask to make the project open-source and release it for free? In general what to do with this project if it gets turned down? A: I've been working on a side project for the last month and a half outside of working hours. This is a product in the same niche with everything in my company's portfolio and is strongly related to our line of business. The idea is not exactly original - it has been coined by a high-ranking employee at one of our internal hackathons as a sample project idea. Moreover I've received numerous inquiries for this functionality by our existing customers while handling their support requests. Unasked, you've volunteered your own time to develope an idea suggested by others. I'm ready with the MVP, and I've scheduled a meeting with my manager ... Might have been an idea to ask your questions and be ready first. What is the best way to approach my manager about this? Develop your plan first, and have everything ready; unless you're just looking for some feedback. You don't want to present a half-baked idea. What benefits can I expect if they do, indeed, decide to adopt my project? Lavish vacations on the Riveira, and steak for lunch with the owner. Seriously, it's rare for ideas to be adopted; if it was such a good idea and needed the company ought to have been working on it already. We don't know what your idea is or whom you work for, we could only guess how it would be received and compensated - think positive is good, but you want the positive response from your management not us (inflating your hopes and dreams). See the 'Riveira Link' above, no guess for that question. Would it be reasonable to ask for a pay raise or a single time bonus? Yes. A raise probably lasts for as long as you stay and may or may not lower your next raise. A one-time payment may or may not cover the hours spent nor will you be compensated if it sells a million copies for ten bucks a piece. You can ask for Stock too. You ought to have checked what they thought before investing your time and effort - if that were the case you'd have some idea what they'd think and know what you stand to gain. You're basically saying: "Here, I made this; what do you think ...'. What's the best course of action if they decide that they are not interested in the project? You can ask what it would take to become accepted. Should I ask for permission to release this to the marketplace on my own? If that's not feasible should I ask to make the project open-source and release it for free? You could, but if they think it's their idea to be developed when and where they choose, and by whom they select to do it, you're risking some ill will. In general what to do with this project if it gets turned down? Shelve it. You should have asked first. You might have wanted to have worked on your own ideas on your own time and kept everything for yourself. You're betting they're gonna like it, and that you'll recoup some modest reward. You've done the work, scheduled the appointment and at the 11th hour you ask: "What do you think?". Smile, and good luck with that. You would have likely made more developing for yourself. They're going to wonder if you've incorporated any of their proprietary technology into your project, they'll probably ask to see it.
{ "pile_set_name": "StackExchange" }
Q: gets.chomp method excercise in learn to program book I am doing excercise 5.6 out of "Learn to Program" for a class. I have the following: puts 'What\'s your first name?' first = gets.chomp puts 'What\'s your middle name?' middle = gets.chomp puts 'What\'s your last name?' last = gets.chomp puts 'Hello, Nice to meet you first middle last' And I have tried the following: puts 'What is your first name?' first = gets.chomp puts 'What is your middle name?' middle = gets.chomp puts 'What is your last name?' last = gets.chomp puts 'Hello, Nice to meet you #{first} #{middle} #{last}' When I get the last "puts" it won't get the first, middle and last name that I wrote in. It says, "Hello, nice to meet you first, middle, last....Instead of Joe John Smith for example. What am I doing wrong? Thank you so much for your help! I really appreciate it! A: When using interpolation, use double quotes " instead of single quotes ' A: Strings within single quotes ' do not replace variables with their values. Try using double quotes " like so: puts "Hello, Nice to meet you #{first} #{middle} #{last}" Single qoutes are nice if you want the string as you typed it, double quotes are useful when you want to replace variable names with their values.
{ "pile_set_name": "StackExchange" }
Q: What is the history of the homomorphism concept? What is the history of the homomorphism concept and who coined the term? I seem to be thinking it arose in abstract algebra and groups/rings/fields, but at what time and by whom? People like Galois and Cauchy pioneered these fields but I understand the concept of function itself wasn't even that precise until Dedekind who was much later than them. A: From Gallian's Contemporary abstract algebra: The term "homomorphism" comes from the Greek words homo,"like", and morphe,"form". The concept of group homomorphism was introduced by Camille Jordan in $1870$, in his influenced book "Traite des substitutions" Addition: The Treatise embodied the substance of most of Jordan’s publications on groups up to that time (he wrote over 30 articles on groups during the period 1860—1880) and directed attention to a large number of difficult problems, introducing many fundamental concepts. For example, he made explicit the notions of isomorphism and homomorphism for (substitution) groups Although this book and this might help!
{ "pile_set_name": "StackExchange" }
Q: Does django grok YML ? django not loading fixtures YML file (yml is not a known serialization) I have successfully created my first django project. I have two apps in my project foo and foobar. I have created a folder named 'fixtures' in each of the app folders. I have NOT specified a fixtures directory in my settings.yml, so (according to the docs), django should be looking in my {app}/fixtures folder. In the {app}/fixtures folder, I have several YML files. I have split the initial data for the various modules into separate YML files, making sure there are no cross file dependencies (i.e. all related models are in the same YML file and ancestors occur in the file before models that use them). However, when I run./manage.py syncdb after the db objects were successfully created, there was the following message: No fixtures found I then tried to manually load the fixtures by using the loaddata command: ./manage.py loaddata 0100_foobar.yml Problem installing fixture '0100_foobar': yml is not a known serialization Is the documentation given in the link above wrong?, or do I need to install a module in order for django to grok YML? BTW, the YML files parse correctly and have been checked for correctness (i used them successfully in another project) - so that is not the problem [Edit] I have installed PyYaml and renamed my fixtures files as per Manoj's instructions. I am able to get a little further down the line, but I am still encountering problems (BTW, I am using PyYaml 3.0.9). Here is the Model in my project ORM (i.e. {app}/model.py): class Currency(models.Model): short_name = models.CharField(max_length=3, db_index=True, unique=True, null=False) # ISO Code long_name = models.CharField(max_length=64, db_index=True, unique=True, null=False) spot_settle = models.IntegerField(null=False, default=0) rounding = models.IntegerField(null=False, default=2) Here is the YAML file I am importing: Currency: currency_aud : { short_name: AUD , long_name: Australia - Dollars , spot_settle: 0, rounding: 2 } currency_cad : { short_name: CAD , long_name: Canada - Dollars , spot_settle: 0, rounding: 2 } currency_eur : { short_name: EUR , long_name: Euro Member Countries - Euro , spot_settle: 0, rounding: 2 } currency_gbp : { short_name: GBP , long_name: United Kingdom - Pounds , spot_settle: 0, rounding: 2 } currency_jpy : { short_name: JPY , long_name: Japan - Yen , spot_settle: 0, rounding: 2 } currency_usd : { short_name: USD , long_name: United States Of America - Dollars , spot_settle: 0, rounding: 2 } currency_zar : { short_name: ZAR , long_name: South Africa - Rand, spot_settle: 0, rounding: 2 } currency_hkd : { short_name: HKD , long_name: Hong Kong Dollar, spot_settle: 0, rounding: 2 } currency_nzd : { short_name: NZD , long_name: New Zealand Dollar, spot_settle: 0, rounding: 2 } currency_sgd : { short_name: SGD , long_name: Singapore Dollar, spot_settle: 0, rounding: 2 } currency_dkk : { short_name: DKK , long_name: Danish Krone, spot_settle: 0, rounding: 2 } currency_sek : { short_name: SEK , long_name: Swedish Krona, spot_settle: 0, rounding: 2 } currency_chf : { short_name: CHF , long_name: Swiss Franc, spot_settle: 0, rounding: 2 } Here is the stack trace when I run ./manage.py loaddata myapp/fixtures/currencies.yaml me@somebox:~/work/demo/myproj$ ./manage.py loaddata reference/fixtures/0100_currency.yaml Installing yaml fixture 'reference/fixtures/0100_currency' from absolute path. Problem installing fixture 'reference/fixtures/0100_currency.yaml': Traceback (most recent call last): File "/usr/local/lib/python2.6/dist-packages/django/core/management/commands/loaddata.py", line 165, in handle for obj in objects: File "/usr/local/lib/python2.6/dist-packages/django/core/serializers/pyyaml.py", line 57, in Deserializer for obj in PythonDeserializer(yaml.load(stream), **options): File "/usr/local/lib/python2.6/dist-packages/django/core/serializers/python.py", line 84, in Deserializer Model = _get_model(d["model"]) TypeError: string indices must be integers, not str A: I tried to reproduce your problem in one of my projects. Apparently loaddata expects the extension of the file to match the serialization format. In your case you should rename your file to 0100_foobar.yaml (note the new extension). Local tests showed my hypothesis was correct. PS: YAML serialization requires the PyYAML library. If you already haven't, install PyYAML. Update I copied the OP's model to one of my projects. When I tried to load the sample YAML given by the OP as-is, I got the same error. After that I added some data using the admin app and used django.core.serializers.serialize to dump the data in YAML format. from django.core.serializers import serialize from app.models import Currency print serializers.serialize("yaml", Currency.objects.all()) The result I got looked significantly different from what the OP posted. See below. I added three instances for the model and they are showing up. - fields: {long_name: Australia - Dollars, rounding: 2, short_name: AUD, spot_settle: 0} model: app.currency pk: 1 - fields: {long_name: Canada - Dollars, rounding: 2, short_name: CAD, spot_settle: 0} model: app.currency pk: 2 - fields: {long_name: Euro Member Countries - Euro, rounding: 2, short_name: EUR, spot_settle: 0} model: app.currency pk: 3 I was able to load this data back without any trouble. Given the above, I suspect that there is something wrong with the OP's YAML file. @skyeagle, can you try dumping the existing data and then try loading the dump back?
{ "pile_set_name": "StackExchange" }
Q: HELP. Cancel Site Collection Backup Job I attempted to backup a site collection through the GUI (Backup & Restore -> Site Collection Backup). When I pulled the size it was only 499MB or 0.49GB. However, my backup is now 50GB. How can I cancel the job? I do not see it running in the active jobs. I don't see anywhere to pause/cancel this. A: Go the central admin > Monitoring > Check Job status on this page look for the backup job(Site Collection Backup ). If it is still running, stop/ delete it. Another way is on the server go to service console and stop the SharePoint Timer Service and start it.
{ "pile_set_name": "StackExchange" }
Q: PoisonPill causes dead letters with persistent actor I am testing a persistent actor (that stores an entity) with test kit: val testActor = system.actorOf((IMPersistentActor.props("id1"))) testActor ! AddElementCommand(refVal) // expectMsg(AddElementResponse(Success(refVal))) // no dead letters if I uncomment this testActor ! PoisonPill which gives: Message [app.server.persistence.IMPersistentActor$AddElementCommand] from Actor[akka://IMPersistentActorTest/system/testActor-1#182376248] to Actor[akka://IMPersistentActorTest/user/$a#-899768724] was not delivered. I thought that AddElementCommand(refVal) should arrive before PoisonPill and should be processed. How can this behaviour be explained ? Why do I get this dead letter ? Interestingly however, if I uncomment expectMsg(AddElementResponse(Success(refVal))) then I get no dead letters and the test passes. Why is that ? Here is the full code : class IMPersistentActorTest extends TestKit(ActorSystem("IMPersistentActorTest")) with WordSpecLike with Matchers with BeforeAndAfterAll with ImplicitSender { override def afterAll: Unit = { TestKit.shutdownActorSystem(system) } "Actor" should { val el = Line(title = Some("bla")) val refVal: RefVal[Line] = RefVal.makeWithNewUUID[Line](el) "add an item to the list and preserve it after restart" in { // val testActor = system.actorOf(Props(new IMPersistentActor("sc-000001") with RestartableActor)) val testActor = system.actorOf((IMPersistentActor.props("id1"))) testActor ! AddElementCommand(refVal) val state: State = IMPersistentActor.addEntity(IMPersistentActor.initState, refVal) testActor ! PoisonPill val testActor2: ActorRef = system.actorOf((IMPersistentActor.props("id1"))) testActor2 ! GetElementsRequest expectMsg(GetElementsResponse(state)) } } } class IMPersistentActor(id: String) extends PersistentActor with ActorLogging { private var state: State =initState override def persistenceId: String = id override def receiveCommand: Receive = { case AddElementCommand(item) => persist(EntityAdded(item)) { evt => state = applyEvent(evt) sender() ! AddElementResponse(Success(item)) } case GetElementsRequest => sender() ! GetElementsResponse(state) } override def receiveRecover: Receive = { case evt: Event => state = applyEvent(evt) case RecoveryCompleted => log.info("Recovery completed!") } private def applyEvent(event: Event): State = event match { case EntityAdded(refVal: (RefValDyn)) => addEntity(state, refVal) } } object IMPersistentActor { type State = Map[RefDyn, RefValDyn] def initState:State=Map.empty def addEntity(s: State, refVal: RefValDyn): State = s + (refVal.r -> refVal) def props(id: String): Props = Props(new IMPersistentActor(id)) // protocol case class AddElementCommand(entity: RefValDyn) case class AddElementResponse(entity: Try[RefValDyn]) case object GetElementsRequest case class GetElementsResponse(items: State) // events sealed trait Event case class EntityAdded(entity: RefValDyn) extends Event } trait IMPersistentActorComm[T] A: You should take a look at this part of the documentation. The short version is that persistence is handled asynchronously, so the PoisonPill message is received before the message telling the actor that the event has been persisted.
{ "pile_set_name": "StackExchange" }
Q: Auto-generating code to create an object with an unknown class I'm coding a script in Python that reads from a custom text and generates Objective-C code from it. The structure of the text is as follows: <XClassName> { property_name_1 { var_name_1: var_value_1 var_name_2: var_value_2 property_name_2 { var_name_3: var_value_3 } property_name_2 { var_name_3: var_value_4 } } property_name_3 { } } Resulting in Objective-C code like this: XClassName* object = [[XClassName alloc] init]; object.propertyName1 = [[[object.propertyName1 class] alloc] init]; object.propertyName1.varName1 = varValue1; object.propertyName1.varName2 = varValue2; object.propertyName2Array = [NSMutableArray array]; { PropertyName2Class propertyName2 = [[PropertyName2Class alloc] init]; propertyName2.varName3 = varValue3; [object.propertyName2Array addObject:propertyName2]; } { PropertyName2Class propertyName2 = [[PropertyName2Class alloc] init]; propertyName2.varName3 = varValue4; [object.propertyName2Array addObject:propertyName2]; } object.propertyName3 = [[[object.propertyName3 class] alloc] init]; This is fine except that PropertyName2Class is not known during the script runtime. Right now I have to manually look for the class name for the elements expected for the object's arrays but this defeats the purpose of having a script automate it. Is there a way to create an object dynamically without knowing its class name and assigning values to its properties? Something like: id classObject = ...; // How to instantiate a dynamic unknown class? classObject.property1 = 1; classObject.property2 = @"Hello World!"; Any ideas? A: If you know the class you want to instantiate exists, for example if it is passed in as a variable, then that's relatively easy. You can do: - (id)createInstanceOfClass: (NSString *)className { Class aClass = NSClassFromString(className); id instance = nil if(nil != aClass) { instance = [[aClass alloc] init]; } return instance; } If it doesn't already exist, you can create an instance of it inside the run time, but that's a little trickier (and quite a bit dodgier too). Update I'd avoid trying to use a class with the properties that you need that already exists unless you're certain what it's implementation does. A safer solution would be to build a class up from scratch and specify what the implementation is. Try reading: http://www.mikeash.com/pyblog/friday-qa-2010-11-6-creating-classes-at-runtime-in-objective-c.html (Not for the faint hearted!) Also see the Objective-C runtime reference: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40008048 A: I'd use the NSMutableDictionary for that: NSMutableDictionary *object = [NSMutableDictionary dictionary]; [object setValue:[NSNumber numberWithInt:1] forKey:@"property1"]; [object setValue:@"Hello World!" forKey:@"property2"]; NSMutableDictionary *subObject = [NSMutableDictionary dictionary]; [subObject setValue:@"Hello sub!" forKey:@"property1"]; [object setValue:subObject forKey:@"property3"];
{ "pile_set_name": "StackExchange" }
Q: Exporting Items from List into Single .csv File R I have a list which contains vectors that I would like to export as a single .csv file containing all vectors as named colums. For instance, if I have, simply, four vectors containing ten items from hypothetical cluster analyses of four models containing a variable number data points created by veglist=list.files(pattern="TXT") #create list of files veg=lapply(veglist,read.csv,header=T,row.names=1) #read list of files vegbc=lapply(veg,vegdist,method="bray") #create dissimilarity matrix from each file av=lapply(vegbc,agnes,method="average") #do clustering analysis with each dissimilarity mat av2=lapply(av,cutree,k=2) #cut the hierarchical analysis at 2 groups level when I type in fix(av2) I would see: list(c(1,1,1,1,1,1,2,2,2,2,2,2),c(1,1,1,1,1,2,2,2,2,2),c(1,1,1,2,1,2,2,2,2,2),c(1,1,1,1,2,1,2,2,2,2,2,2,2)) If I type in av2 I see [[1]] [1] 1 1 1 1 1 1 2 2 2 2 2 2 [[2]] [1] 1 1 1 1 1 2 2 2 2 2 [[3]] [1] 1 1 1 2 1 2 2 2 2 2 [[4]] [1] 1 1 1 1 2 1 2 2 2 2 2 2 2 I have tried following this example How to read every .csv file in R and export them into single large file. This did not work. I think the underlying problem is that my vectors are not the same size. What I want to do is output the vectors into a single table that looks something like: a b c d 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 Where a,b,c,d are in place of my actual names. Preferably it would look prettier than this, but I could work with it. I apologize for the very long question, but I was trying to provide enough of an example to go by. I am also sorry if this has a very easy answer, but I am not yet good with R. Thanks in advance. A: You would first need to extend each vector to the length of the maximum length-ed vector and then you could cbind them together so that write.csv would send them out as "columns": > maxlength <- max(sapply(l, length)) > mat <- cbind(sapply(l, `length<-`, maxlength)) > mat [,1] [,2] [,3] [,4] [1,] 1 1 1 1 [2,] 1 1 1 1 [3,] 1 1 1 1 [4,] 1 1 2 1 [5,] 1 1 1 2 [6,] 1 2 2 1 [7,] 2 2 2 2 [8,] 2 2 2 2 [9,] 2 2 2 2 [10,] 2 2 2 2 [11,] 2 NA NA 2 [12,] 2 NA NA 2 [13,] NA NA NA 2 > write.csv(mat, file="mycsv.csv") Which looks like this in a text editor (and would get imported into Excel properly.): "","V1","V2","V3","V4" "1",1,1,1,1 "2",1,1,1,1 "3",1,1,1,1 "4",1,1,2,1 "5",1,1,1,2 "6",1,2,2,1 "7",2,2,2,2 "8",2,2,2,2 "9",2,2,2,2 "10",2,2,2,2 "11",2,NA,NA,2 "12",2,NA,NA,2 "13",NA,NA,NA,2
{ "pile_set_name": "StackExchange" }
Q: Call either system's Python or virtualenv's Python in a Python script Suppose you write a Python shell script. It will probably start with something like this: #!/usr/bin/python The problem is, if you often work with virtualenv this call is just plain wrong. You actually would like this script to call virtualenv's python binary, if it is in this environment and /usr/bin/python/ otherwise. Just like your shell would decide, when you write python as a shell command. How would you write your #! line to fulfil this requirement? A: Use #!/usr/bin/env python instead. The env command looks up binaries in the current PATH; activating your virtual environment adds your virtualenv bin/ directory to the path and env will find your python binary there instead of the global python.
{ "pile_set_name": "StackExchange" }
Q: Query PostgreSQL db in C# in database agnostic way (ie without Npgsql) Is there a way to query a PostgreSQL db in C# in a database agnostic way ie without Npgsql. I want use built in .NET libraries and a connection-string that contains the DB IP, Username, Password and any other info that the connection-string might require. A: You can use ODBC and construct the connection within your app. The Postgres driver has to be installed on the machine running the program. Your app would then only be using the generic ODBC classes. Below is a simple example. using System.Data.Odbc; string connectString = "Driver={PostgreSQL UNICODE};Port=5432;Server=localhost;Database=myDBname;Uid=myusername;Pwd=mypassword;"; OdbcConnection connection = new OdbcConnection(connectString); connection.Open(); string sql = "select version()"; OdbcCommand cmd = new OdbcCommand(sql, connection); OdbcDataReader dr = cmd.ExecuteReader(); dr.Read(); string dbVersion = dr.GetString(0);
{ "pile_set_name": "StackExchange" }
Q: Karate - Having multiple 'When's in single scenario I have a scenario where there are multiple steps/ REST operations needs to be run to complete one process. Each REST operation needs to have authorization username and password. I have provided this in Background session. This is how my present feature looks like. Feature: Adding to cart Background: * url 'https://soa-mp-rmsk-someurl.com' * header agent_uid = 'AUTO_TST' * configure ssl = true * header Authorization = call read('classpath:Project/JSFiles/auth.js') { username: 'ABC', password: '123' } * configure logPrettyResponse = true * configure logPrettyRequest = true Scenario: Find available mobiles Given path '/v1/available-mobiles' When method get Then status 200 * def mobile = response.iPhoneXSMax # Add a mobile to cart Given path '/v1/mobiles/'+mobile+'/add And request {name: 'iPhoneXSMax'} When method put Then status 200 Now this throws error saying that "faultstring": "Authentication challenge issued". I can group them into different scenarios so that they call header authorization every time which results in successful run; I have tried this as well. Works for me. But i don't think its a good practice to group these steps in different scenarios as they literally makes a single scenario. How can i overcome this error? Or should i go and distribute them in different scenarios? https://automationpanda.com/2018/02/03/are-gherkin-scenarios-with-multiple-when-then-pairs-okay/ EDIT-1 This is how i tried to add configure headers for Authorization details; I was not able to fully understand this, could you please help? headers.js function fn() { var username = karate.get('username'); var password = karate.get('password'); if (username && password) { return { Authorization: username + password }; } else { return {}; } } And i called it in feature background like this; but didn't worked. * configure headers = read('classpath:headers.js') * def username = 'ABC' * def password = '123' A: I think you have completely missed that for header based auth - Karate has a global kind of a hook - which is what most teams use. Refer the docs for configure headers.
{ "pile_set_name": "StackExchange" }
Q: Sub-Module child routes not working ("Error: Cannot match any routes.") I'm using Angular 6.0.3. I have a sub-module called "Admin" with three components. Admin's root component ("AdminComponent") route works fine (path: ""), but I can't seem to trigger any of the others. Why can't Angular find my routes? routes.ts import { Routes } from "@angular/router"; import { SplashComponent } from "./splash/splash.component"; import { LoginComponent } from "./login/login.component"; import { WatchComponent } from "./watch/watch.component"; import { AdminComponent } from "./admin/admin/admin.component"; import { HomeComponent as AdminHomeComponent } from "./admin/home/home.component"; import { AddSongComponent } from "./admin/add-song/add-song.component"; import { AdminGuard } from "./auth/admin.guard"; export const appRoutes: Routes = [ { path: "", children: [ { path: "", component: SplashComponent, pathMatch: "full" }, { path: "login", component: LoginComponent, pathMatch: "full" }, { path: "watch", component: WatchComponent, pathMatch: "full" }, { path: "admin", component: AdminComponent, pathMatch: "full", canActivate: [AdminGuard], children: [ { path: "", component: AdminHomeComponent, pathMatch: "full", outlet: "admin" }, { path: "add-song", component: AddSongComponent, pathMatch: "full", outlet: "admin" } ] } ] } ]; admin/admin/admin.component.html <router-outlet name='admin'></router-outlet> admin/home/home.component.html <div> <a mat-raised-button [routerLink]="['add-song']">Add new song</a> </div> note: I've also tried [routerLink]="[{ outlets: { admin: ['add-song'] } }], still route not found. A: I would recommend you to look at Lazy-loading feature while loading sub modules, which is the correct way to load when you have many modules. In your case you have admin module as a sub module, so here is the routing Configuration, RouterModule.forRoot([ { path: '', redirectTo: 'splash', pathMatch: 'full' }, { path: 'splash', component: SplashComponent }, { path: 'admin', loadChildren: './admin/admin.module#AdminModule' }, { path: '**', component: NotFoundComponent } ], { enableTracing: true })] and the Admin.module routing is as follows, RouterModule.forChild([ { path: '', component: AdminComponent, children: [ { path: '', component: AdminHomeComponent } , { path: 'add-song', component: AddSongComponent}] } ]) ] WORKING STACKBLITZ DEMO ROUTES: Splash https://nested-routes-angular-lazyloading.stackblitz.io/splash Admin https://nested-routes-angular-lazyloading.stackblitz.io/admin Admin-AddSong https://nested-routes-angular-lazyloading.stackblitz.io/admin/add-song
{ "pile_set_name": "StackExchange" }
Q: Kotlin - any substitute for companion object inside of another object (not class)? I would like in my Kotlin Android app to have singleton object with some static definitions of it's inner states. As I understand, object in Kotlin is for singleton, so I am trying this kind of approach: object MySingleton { public const val _DEF_DEFINITION_NO_ONE: Byte = 1; public const val _DEF_DEFINITION_NO_TWO: Byte = 2; (...) } This is fine, but the problem is, to being able use these definitions, now I must create Object's instance first. Just wondering if I am able in Kotlin to create this kind of construction and have access to these definitions without creating MySingleton instance? Answer would be companion object working similar as static in other languages, but it's not allowed inside objects, only inside of classes. Of course I can leave this as is or make these definitions global, but would like to know is it possible to do in a way I described? Or maybe should I design this in another yet way? A: There are two ways to work with static data in Kotlin: An object object ASingleton { val CONSTANT_PROPERTY: Int = 1; } If you need a single instance class, which has only one state for each property, use a singleton. Note: There can only be one instance of this class and it is created for you by the compiler. A class with a companion object class ClassWithCompanionObject{ val someProperty: Int = 0; // instance bound companion object { val CONSTANT_PROPERTY: Int = 1; } } If you need some static properties, and the rest should have a state which is bound to a certain instance, go with the class with companion object. Usage: println(ASingleton.CONSTANT_PROPERTY) println(ClassWithCompanionObject.CONSTANT_PROPERTY) A: As you said, MySingleton is an object and thus a singleton. There's no need to create an instance of it (not even possible). You simply access it's constants in a static way like this: MySingleton._DEF_DEFINITION_NO_ONE. If you want to use the constants without prefixing the object name, just import them with the fully-qualified name and use it as follows: import package.MySingleton._DEF_DEFINITION_NO_ONE //... println(_DEF_DEFINITION_NO_ONE)
{ "pile_set_name": "StackExchange" }
Q: Android GSON: Parsing several different objects from the same response I'm working on porting an iPhone app that relies heavily on JSON to Android. One of the responses that has to be parsed is used to build the main screen. The JSON response for this contains 3 different objects, namely Icons, Header and Player. These are all contained within the object Home. Icons and Player both contain an Array of items, the Header is just a single item. Now I'm still a beginner when it comes to JSON, and I'm not quite sure how I should parse this response. Therefore I would like to know if I have the right idea before working myself into problems. My idea is to create 4 different classes, one for Home, icons, Header and Player. Home would contain an array of both Icons and Player, and an object of Header. But I'm not sure if this is the correct way to do this. The JSON response in questions is as followed: (Removed some objects due to the size of the response) { "Home": { "Icon": [ { "ScreenID": 533, "ScreenIndex": 1, "IconName": "mainIcon_news", "Title": "News", "FK_ModuleID": 6, "FormID": 567, "ModName": "News", "MediaType": "", "New_Icon": 0 }, { "ScreenID": 528, "ScreenIndex": 2, "IconName": "mainIcon_music", "Title": "Music", "FK_ModuleID": 3, "FormID": 562, "ModName": "Media", "MediaType": "Music", "New_Icon": 0 } ], "Header": [ { "ModHomeRotationID": 183, "image_url": "*****/Media/68/1216_5.jpg", "flg_RotationEnabled": false, "flg_RotateOnlyOnReturn": true, "flg_RotationRandomize": false, "flg_RotationDelayMS": 5000, "flg_RotationDelayFadeMS": 3000, "HomeRotationIndex": null } ], "Player": [ { "MediaID": 1219, "Track_Name": "***", "song_url": "*****/Media/68/1219.mp3", "song_remote_url": null, "FileSize": 4700502 }, { "MediaID": 1220, "Track_Name": "**** ", "song_url": "*****/Media/68/1220.mp3", "song_remote_url": null, "FileSize": 4350222 } ] } } Could someone tell me if I'm in the right direction, and if not, what I should be doing instead? I should mention, I'm using GSON to parse the JSON responses at the moment. Thanks in advance A: Yes you are right you need to create Four classes and need to initialize the values inside that class name.. Validate your Json using JSONLint : Then try this sample Parsing JSON using GSON and One More
{ "pile_set_name": "StackExchange" }
Q: Do bitwise/logical operator math questions belong on Stack Overflow or Math.StackExchange? Bitwise operations are mathematical in nature but are largely relevant in programming. I have a question pertaining to bitwise operators but am not sure which site to post it on. My question: How can I determine what values of edx make energy equal to eax in the equation energy = (eax XOR 0x01010101) XOR edx where eax = (edx XOR energy) XOR 0x01010101? Plugging in random numbers and checking results is unfavorable. I need a clear cut solution. All variables are 4 byte unsigned integers represented in hex. A: As Adrian points out: Math.SE seems okay, but Computer Science SE should be fine too. The [boolean-algebra] tag at Math.SE would be a suitable destination, according to my understanding of this question on their Meta (your question would fall under "'algebra of logic', i.e. basic calculus with truth values"). The evidence is less clear-cut when it comes to CS.SE, but a quick look at their own [boolean-algebra] tag suggests it would be fine to post it there as well. If I were to recommend just one site, I'd say Math.SE.
{ "pile_set_name": "StackExchange" }
Q: Caching variables in isolated storage, portable class library way I'm trying to figure out how I can read and write params that gets stored in the applications isolated storage. Right now im building a windows phone app, but since I want a win8 app to I figured I could do it in portable class library project, and found this awesome PCLStorage. My Cache class looks atm like this for storing params: public async static Task<string> GetParam(string name) { IFolder rootfolder = FileSystem.Current.LocalStorage; IFolder folder = await rootfolder.GetFolderAsync("isostore"); IFile file = await folder.GetFileAsync(name); return await file.ReadAllTextAsync(); } public async static void SaveParam(string name, string param) { IFolder rootfolder = FileSystem.Current.LocalStorage; IFolder folder = await rootfolder.CreateFolderAsync("isostore", CreationCollisionOption.OpenIfExists); IFile file = await folder.CreateFileAsync(name, CreationCollisionOption.ReplaceExisting); await file.WriteAllTextAsync(param); } The write part is okey, it overrides if there is any. Its the reading part that is the problem. IFile and IFolder does not have any .Exists functions (???) so what does it return if I call Get before Save? A: I think in your case in the GetParam method you should be calling CreateFolderAsync and CreateFileAsync with the CreationCollisionOption.OpenIfExists parameter. Then you shouldn't need to worry about creating them separately beforehand or catching exceptions that they do/don't exist.
{ "pile_set_name": "StackExchange" }
Q: ASP.NET MVC 5 - Send contents of div to Controller method I have this HTML code with a div whose contents I want to pass to the controller. The div basically contains some span items of the label-primary class (link). I want to be able to get the names of the labels in this div in the controller. My idea was, as soon as the submit button is clicked, get the list of items that are inside the label-container div and pass their names to the controller as the List<string> OwnerTerminals value. How do I do that? HTML + JS code: @using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { ... <div id="register-terminal-panel" class="panel panel-default" style="max-width: 450px;"> <div class="panel-heading" style="color:#003F8B"> Add terminals to client </div> <div class="panel-body"> <div id="label-container"></div> <div class="input-group input-group pull-right"> <span class="input-group-addon"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> </span> <input id="register-terminals-search" type="text" class="form-control" placeholder="Search terminals" aria-describedby="search-addon" onkeyup="searchTerminals()"> </div> </div> <ul id="register-terminal-list-container" class="list-group"> @foreach (Point p in terminals) { <li id="[email protected]"><a href="javascript:void(0)" class="list-group-item" onclick="createLabel('@p.Name')">@p.Name</a></li> } </ul> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" class="btn btn-default" value="Register" /> </div> </div> } <script> function closeLabel(item) { item.parentElement.remove(); var listItem = '\n<li id="list-item-' + item.parentElement.id + '"><a href="javascript:void(0)" class="list-group-item" onclick="createLabel(\'' + item.parentElement.id + '\')">' + item.parentElement.id + '</a>'; $('#register-terminal-list-container').append(listItem); sortUnorderedList("register-terminal-list-container"); }; function createLabel(name) { var label = '<span id="' + name + '" class="label label-primary terminal-label"><span class="glyphicon glyphicon-remove" onclick="closeLabel(this)" id="terminal-label-close-btn"></span> ' + name + '</span>\n' $('#label-container').append(label); $('#list-item-' + name).remove(); }; </script> Model: public class RegisterViewModel { ... public List<string> OwnerTerminals { get; set; } } A: Modify answer regard to comment for doing it using post It is possible to do it without using ajax, mainly by using a hidden input with proper name to achieve it. so add a hidden input when creating the label to achieve it function createLabel(name) { var label = '<span id="' + name + '" class="label label-primary terminal-label"><span class="glyphicon glyphicon-remove" onclick="closeLabel(this)" id="terminal-label-close-btn"></span> ' + name + '</span>\n' label = label + '<input type="hidden" value="' + name + '" name="OwnerTerminals" />'; $('#label-container').append(label); $('#list-item-' + name).remove(); }; if the model is object, there may need some object name prefix to the input name - i.e ModelName.OwnerTerminals more info about model binding, please reference other article such as this one: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/ Original Answer There is two part get all the names you can get name via javascript like (I have made a jsfiddle which assume how your view would look like here https://jsfiddle.net/alantsai/p076235t/): $(function() { $("#btnGetName").click(function() { var nameList = []; $("#label-container > span").each(function() { nameList.push($(this).text()); }); alert(nameList); }) }) post it to controller you probably need to modify the post object according to your view model, but if simply the OwnerTerminals, then should be something like: $.post("postUrl", {OwnerTerminals : nameList});
{ "pile_set_name": "StackExchange" }
Q: What's the (still negative) opposite of "arrogant" The answer is not the word humble nor any derivation thereof. Arrogant being negative epithet has a positive counterpart of humble but I'm looking for the negative opposite, instead. Arrogant conduct is assuming that ones success is the result of ones excellence and failing to consider that it might be subject to advantageous circumstances. The opposite of that would be failing to see that any of the progress is due to ones skills nor competence. And that's a negative concept as well. I can express it by overly humble or excessively timid/self-critical but I want a single word term for precisely that, rather than a description of the property. Insecure won't do because that's a different concept - I'm talking about someone who too often assumes that the success is due to fortunate circumstances. A: Removing any words I would consider positive from this list of antonyms of arrogant I found on Merriam Webster: Near Antonyms of arrogant: cowering, cringing, mousy (or mousey), overmodest, sheepish, shrinking, shy, subdued, timid, meek, submissive, unassertive, yielding It's hard to pick one without knowing the context in which you are using it. A: The term that first came to mind was self-deprecating: tending or serving to disparage or undervalue oneself, but it doesn’t have a negative connotation. You could make it negative by adding “excessively” or “annoyingly”, but without an example of how you want to use the word you’re looking for, it’s difficult to say whether it fits. Being self-deprecating if you are a celebrity or have a lot of power can be a positive quality. Self-deprecating humor (in general) can be seen as a positive thing unless it is excessive. Self-effacing: having or showing a tendency to make oneself modestly or shyly inconspicuous, is a related word. I don’t think it fits though because it is more about avoiding attention than being self-critical.
{ "pile_set_name": "StackExchange" }
Q: How to read part of a html coded article from database like MySQL? I am trying to write a blog system. The main page is consist of part of the content of blog entries. The problem is how could I make sure the excerpt is truncated correctly, since the blog entries is stored in HTML code. Thanks. A: Your best bet would be to use strip_tags() to remove the HTML from it and show only the first 300 or so characters using substr. Otherwise you'd have to parse the HTML to break it at an appropriate place so as not to break the rest of your layout.
{ "pile_set_name": "StackExchange" }
Q: Acumatica - sitemap item does not show in modern UI I just added a Sales Commissions report to sitemap and it shows in classic UI but not in modern UI. When I search for it in modern UI, result returns nothing. How my sitemap node looks like in project.xml: <SiteMapNode> <data-set> <relations format-version="3" relations-version="20160101" main-table="SiteMap"> <link from="MUIScreen (NodeID)" to="SiteMap (NodeID)" /> <link from="MUIWorkspace (WorkspaceID)" to="MUIScreen (WorkspaceID)" type="FromMaster" linkname="workspaceToScreen" split-location="yes" updateable="True" /> <link from="MUISubcategory (SubcategoryID)" to="MUIScreen (SubcategoryID)" type="FromMaster" updateable="True" /> <link from="MUITile (ScreenID)" to="SiteMap (ScreenID)" /> <link from="MUIWorkspace (WorkspaceID)" to="MUITile (WorkspaceID)" type="FromMaster" linkname="workspaceToTile" split-location="yes" updateable="True" /> <link from="MUIArea (AreaID)" to="MUIWorkspace (AreaID)" type="FromMaster" updateable="True" /> <link from="MUIPinnedScreen (NodeID, WorkspaceID)" to="MUIScreen (NodeID, WorkspaceID)" type="WeakIfEmpty" isEmpty="Username" /> <link from="MUIFavoriteWorkspace (WorkspaceID)" to="MUIWorkspace (WorkspaceID)" type="WeakIfEmpty" isEmpty="Username" /> </relations> <layout> <table name="SiteMap"> <table name="MUIScreen" uplink="(NodeID) = (NodeID)"> <table name="MUIPinnedScreen" uplink="(NodeID, WorkspaceID) = (NodeID, WorkspaceID)" /> </table> <table name="MUITile" uplink="(ScreenID) = (ScreenID)" /> </table> <table name="MUIWorkspace"> <table name="MUIFavoriteWorkspace" uplink="(WorkspaceID) = (WorkspaceID)" /> </table> <table name="MUISubcategory" /> <table name="MUIArea" /> </layout> <data> <SiteMap> <row Position="1.5" Title="Sales Commissions" Url="~/Frames/ReportLauncher.aspx?ID=SO646000.rpx" Expanded="0" IsFolder="0" ScreenID="SO646000" NodeID="972cf181-504a-4df7-88d1-c4cb1a0c93d4" ParentID="85e0f6b3-8ae8-43aa-ad7b-ea4d4d5f381e" /> </SiteMap> </data> </data-set> </SiteMapNode> And a screenshot of my site map directory: https://drive.google.com/open?id=1wp2xWqdx-0lbGE7xfDuD6bhtLrK1-I7i Any ideas what might be happening? I tried recreating site map entry several times and still nothing. A: You have to add it to the work space after adding to the sitemap. Just because you add it to the sitemap does not automatically add it to the new UI. The help articles should help to walk you through editing the new UI. Here is an article that might help: To Add a Link to a Workspace More help... Customizing the Modern User Interface Workspaces in the Modern UI Edit: If you already added the sitemap to your customization and later add the entry to a workspace, you need to update the sitemap entry in your customization project by reloading from the database (option under sitemap).
{ "pile_set_name": "StackExchange" }
Q: Extras values after calling main method This program works fine if i enter the correct value (int value). However, when I enter in a character or any other wrong value it displays the wrong input message and calls the main method again. The only problem is after calling the main method and inputting the correct input it prints out extra data why is that? import javax.swing.JOptionPane; public class TestPolyVal { public static void main(String[] args){ int xValue = 0; String value = JOptionPane.showInputDialog(null, "What is the value of X"); try{ xValue = Integer.parseInt(value);} catch (NumberFormatException e){ JOptionPane.showMessageDialog(null,"Wrong input. Please input only integer values."); TestPolyVal.main(args); } int[] intArray = new int[20] ; for (int i = 0; i < 20; i ++){ intArray[i] = 2;} System.out.println(calculateBruteForce(intArray,xValue)); System.out.println("0"); System.out.println(calculateHorner(intArray,xValue));} static int calculateBruteForce(int[] a, int b){ int sum = 0 ; for (int i = 0; i < 20; i ++){ sum +=a[i]*powerCalc(b,i);} return sum;} static int powerCalc(int c, int d){ int powerValue = c; if (d==0){ powerValue = 1;} else if (d==1){ powerValue = c;} else if (d>1){ for (int i = 1; i<d;i++){ powerValue = powerValue*c;}} return powerValue;} static int calculateHorner(int[] e, int f){ int acc = e[e.length-1]; for(int i = e.length-2; i >= 0; i--){ acc = (acc * f)+ e[i];} return acc;} } A: You are getting extra printouts because the first main execution will continue after the second main invocation is done. This can be fixed by adding a return; after the new call to main: catch (NumberFormatException e){ JOptionPane.showMessageDialog(null,"Wrong input. Please input only integer values."); TestPolyVal.main(args); return; }
{ "pile_set_name": "StackExchange" }
Q: How to make a plus minus toggle with angular I'm trying to make a plus / minus toggle with angular. As a basic function, it would let the user enter in two numbers on either side of the toggle as inputs and then, depending upon which toggle was selected, either adds the numbers or subtracts them. I'm trying to put this in a directive so you could call it multiple times (so if you wanted to add, subtract or do combination of the two for multiple numbers, you could). I've gotten it to switch what is displayed, but I can't figure out how to get it to do the proper math. Here is what I have so far: On plunker: http://plnkr.co/edit/PW990KXShDEYN9welhPe?p=preview The html: <input type="number" size="2" ng-model="values.firstValue" ng-pattern="onlyNumbers" required> <plus-minus-toggle></plus-minus-toggle> <input type="number" size="2" ng-model="values.secondValue" ng-pattern="onlyNumbers"> <plus-minus-toggle></plus-minus-toggle> <input type="number" size="2" ng-model="values.thirdValue" ng-pattern="onlyNumbers"> <button ng-click="doMath()">Calculate</button> {{result}} The directive: angular.module('diceAngularApp') .directive('plusMinusToggle', function() { return { restrict: 'E', scope:true, template: '<button ng-click="custom=!custom"><span ng-show="custom">+</span><span ng-hide="custom">-</span></button>', replace: true }; }); And the controller: angular.module('diceAngularApp') .controller('DiceController', function ($scope, $rootScope, $log) { $scope.custom = true; $rootScope.onlyNumbers = /^\d+$/; $scope.values = {firstValue: 5, secondValue: 2, thirdValue: 3}; $scope.doMath = function() { $scope.result = $scope.values.firstValue + $scope.values.secondValue + $scope.values.thirdValue; }; }); A: Here is an example on plunker that isolates the scope of the directive and provides a two-way binding with the parent controller: http://plnkr.co/edit/V7iIQUdSj4tNcRQCn16n?p=preview The basic idea is to make the directive "re-usable" by isolating its scope: app.directive('plusMinusToggle', function() { function plusOperation(a, b) { return a + b; } function minusOperation(a, b) { return a - b; } return { restrict: 'E', scope: { operation: '=' }, template: '<button ng-click="isPlus=!isPlus"><span ng-show="isPlus">+</span><span ng-hide="isPlus">-</span></button>', controller: function($scope) { $scope.isPlus = true; $scope.operation = plusOperation; $scope.$watch('isPlus', function(isPlus) { if (isPlus) { $scope.operation = plusOperation; } else { $scope.operation = minusOperation; } }); }, replace: true }; }); So in your controller you would have two variables that can be used for the two-way bind: app.controller('MainCtrl', function ($scope, $rootScope, $log) { $scope.op1 = angular.noop; $scope.op2 = angular.noop; }) And in your view is where you make that two-way bind happen: <plus-minus-toggle operation="op1"></plus-minus-toggle> <plus-minus-toggle operation="op2"></plus-minus-toggle> Back in the MainCtrl you can make use of those operations which will be changed based on the directive's isolated scope: $scope.doMath = function() { $scope.result = $scope.op2($scope.op1($scope.values.firstValue, $scope.values.secondValue), $scope.values.thirdValue); }; You can read more about it in the Isolating the Scope of a Directive section of the angular guide.
{ "pile_set_name": "StackExchange" }
Q: Csvhelper Ingore is removing only header column name but no the actual data I loaded a csv file in my database with a DbId column not in the file. I want to export it back to the original format. My csvhelper mapping is in MyCsvClass with Map(m => m.DbId).Ignore(); Header is fine, but output data is still showing values of DbId column: https://dotnetfiddle.net/XP2Vvq using CsvHelper.Configuration; using System; using System.IO; namespace Test { class Program { static void Main(string[] args) { var record = new { DbId = 1, Data1 = "aaa", Data2 = "bbb" }; using (var sw = new StreamWriter(@"c:/temp/testt.csv")) { using (var csvWriter = new CsvHelper.CsvWriter(sw)) { csvWriter.Configuration.RegisterClassMap<MyCsvClassMap>(); csvWriter.WriteHeader<MyCsvClass>(); csvWriter.NextRecord(); csvWriter.WriteRecord(record); } } } } public class MyCsvClassMap : ClassMap<MyCsvClass> { public MyCsvClassMap() { AutoMap(); Map(m => m.DbId).Ignore(); } } public class MyCsvClass { public int DbId { get; set; } public string Data1 { get; set; } public string Data2 { get; set; } } } Output is Data1, Data2 1, "aaa", "bbb" when I expect Data1, Data2 "aaa", "bbb" A: The issue with your code is that you create an instance of anonymous type var record = new { DbId = 1, Data1 = "aaa", Data2 = "bbb" }; instead of var record = new MyCsvClass { DbId = 1, Data1 = "aaa", Data2 = "bbb" }; The header is fine, because you pass the correct class to type parameter of the generic method. csvWriter.WriteHeader<MyCsvClass>(); Edit To export DB entities to CSV you don't need any intermediate class. You can write entities directly to CSV and ClassMap<T> helps you control what values and how get serialized to CSV. If your entity class is MyDbEntity, then just register custom mapping ClassMap<MyDbEntity> where you auto-map all fields ignoring some fields as you did in your MyCsvClassMap.
{ "pile_set_name": "StackExchange" }
Q: Promises in Series are not getting executed in sequence I have written the code based on the Parse example provided in Parse.com to execute the promises in Series. But, seems like sequential processing is not working fine. The below code calls a cloud function namely 'sampleCloudFuction' multiple times but in sequential order through Series of Promises. After executing the loop, app will make a call to another js function which will load the remaining items (excluding the processed items). This is the Loop which make multiple calls to the cloud function: var seriesPromise = new Parse.Promise.as(); $.each(items, function (i) { .. .. count++; if (count >= 25 || (i + 1) >= selectedItemsLength) { .. .. //Series Promise: The code to be executed in sequence being placed within the //then() the existing promise seriesPromise = seriesPromise.then(function () { Parse.Cloud.run('sampleCloudFuction', itemsArray, function () { console.log("success callback in JS"); var tempPromise = Parse.Promise.as(); return tempPromise; }, function (error) { alert("Error " + error.code + "::"); console.log("error callback in JS") }); }); count = 0; } }); .. .. seriesPromise.then(function () { //Fetch the approval state of the disabled button alert("load remaining items"); }); The below function is to be called after executing the loop. But, this is being called well in before receiving the callbacks for all earlier requests. seriesPromise.then(function () { //Fetch the approval state of the disabled button alert("load remaining items"); }); A: Parse.Cloud.run('sampleCloudFuction', itemsArray, function () { console.log("success callback in JS"); var tempPromise = Parse.Promise.as(); return tempPromise; }) That doesn't work. You cannot return from a callback - the value will just vanish. However, the docs state that every asynchronous method in the Parse JavaScript SDK returns a Promise - you don't even need to try to construct it on your own! So, why is the sequential processing not working correctly? Because it requires that the then callback does return the value of the next step - which can be an asynchronous, not yet resolved promise. Then, the new seriesPromise will wait for that step before executing the next. Yet you were not returning anything from that callback - so the then just resolved the seriesPromise immediately with undefined. Return the promise that .run() yields: var seriesPromise = new Parse.Promise.as(); $.each(items, function (i) { … // Series Promise: The code to be executed in sequence being placed within the // then() the existing promise seriesPromise = seriesPromise.then(function() { return Parse.Cloud.run('sampleCloudFuction', itemsArray); // ^^^^^^ }); … }); seriesPromise.then(function () { //Fetch the approval state of the disabled button alert("load remaining items"); }, function (error) { alert("Error " + error.code + "::"); console.log("error callback in JS"); });
{ "pile_set_name": "StackExchange" }
Q: Unable to draw a triangle by using opengl es 2.0 in android java I am making an app by referring the tutorial of developer.android.com of android of topic Displaying graphics using OpenGL ES 2.0. I have used the code given in the website but the problem is that instead of displaying a triangle my app first shows blank screen and then crashes showing "Unfortunately,Graphics has stopped working" Graphics is the name of my app. I want to know where my code is creating problem. My code is. MainActivity.java:- package com.example.graphics; import android.opengl.GLSurfaceView; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends ActionBarActivity { private GLSurfaceView gv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); gv=new MyGLSurfaceView(this); setContentView(gv); } } MyGLSurfaceView.java:- package com.example.graphics; import android.content.Context; import android.opengl.GLSurfaceView; class MyGLSurfaceView extends GLSurfaceView{ public MyGLSurfaceView(Context context) { super(context); setRenderer(new MyGLRenderer()); setEGLContextClientVersion(2); setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); } } Triangle.java:- package com.example.graphics; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import android.opengl.GLES20; public class Triangle { private FloatBuffer mFloatBuffer; int COORDS_PER_VERTEX=3; float color[] = { 0.63671875f, 0.76953125f, 0.22265625f, 1.0f }; float[] coords={ 0.0f,0.5f,0.0f ,-0.5f,-0.5f,0.0f, 0.5f,-0.5f,0.0f }; private final String vertexShaderCode = "attribute vec4 vPosition;" + "void main() {" + " gl_Position = vPosition;" + "}"; private final String fragmentShaderCode = "precision mediump float;" + "uniform vec4 vColor;" + "void main() {" + " gl_FragColor = vColor;" + "}"; int mPositionHandle,mColorHandle; int mProgram; MyGLRenderer g=new MyGLRenderer(); private int vertexStride=COORDS_PER_VERTEX*4; private int vertexCount=coords.length/COORDS_PER_VERTEX; public Triangle() { // TODO Auto-generated constructor stub int vertexShader=g.loadShader(GLES20.GL_VERTEX_SHADER,vertexShaderCode); int fragmentShader=g.loadShader(GLES20.GL_FRAGMENT_SHADER,fragmentShaderCode); mProgram=GLES20.glCreateProgram(); GLES20.glAttachShader(mProgram, vertexShader); GLES20.glAttachShader(mProgram, fragmentShader); GLES20.glLinkProgram(mProgram); ByteBuffer bb=ByteBuffer.allocateDirect(coords.length*4); bb.order(ByteOrder.nativeOrder()); mFloatBuffer=bb.asFloatBuffer(); mFloatBuffer.put(coords); mFloatBuffer.position(0); } public void draw() { GLES20.glUseProgram(mProgram); mPositionHandle=GLES20.glGetAttribLocation(mProgram, "vPosition"); GLES20.glEnableVertexAttribArray(mPositionHandle); GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX, GLES20.GL_FLOAT, false, vertexStride, mFloatBuffer); mColorHandle=GLES20.glGetUniformLocation(mProgram, "vColor"); GLES20.glUniform4fv(mColorHandle, 0, color,1); GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount); GLES20.glDisableVertexAttribArray(mPositionHandle); } } MyGLRenderer.java:- package com.example.graphics; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import android.opengl.GLES20; import android.opengl.GLSurfaceView; class MyGLRenderer implements GLSurfaceView.Renderer{ Triangle mTri; @Override public void onSurfaceCreated(GL10 arg0, EGLConfig arg1) { // TODO Auto-generated method stub mTri=new Triangle(); } public void onDrawFrame(GL10 arg0) { // TODO Auto-generated method stub GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT|GLES20.GL_DEPTH_BUFFER_BIT); mTri.draw(); } @Override public void onSurfaceChanged(GL10 arg0, int arg1, int arg2) { // TODO Auto-generated method stub } public int loadShader(int type,String shaderSource) { int shader=GLES20.glCreateShader(type); GLES20.glShaderSource(shader, shaderSource); GLES20.glCompileShader(shader); return shader; } } and finally mu manifest is:- GraphicsManifest.xml:- <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.graphics" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="20" /> <uses-feature android:glEsVersion="0x00020000" android:required="true" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Tell me where i am doing wrong. And why my App crashes. A: There are at least a couple of problems in this code. The big one is right at the start: public MyGLSurfaceView(Context context) { super(context); setRenderer(new MyGLRenderer()); setEGLContextClientVersion(2); setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); } This is the wrong order of calls. setEGLContexClientVersion() needs to be called before setRenderer(). setRenderer() initiates picking the config and creating the context, which both depend on the API version. The correct order is: public MyGLSurfaceView(Context context) { super(context); setEGLContextClientVersion(2); setRenderer(new MyGLRenderer()); setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); } Another problem is with this call: GLES20.glUniform4fv(mColorHandle, 0, color,1); The second argument is count, which is the number of vectors to set. Since the value passed for this argument is 0, this will do nothing at all. On the other hand, the last argument is an offset into the vector passed as the 3rd argument, which should be 0 in this case. The correct call is: GLES20.glUniform4fv(mColorHandle, 1, color, 0); I didn't study all of the code in detail, but these were the issues that jumped out immediately.
{ "pile_set_name": "StackExchange" }
Q: How to get data from selected row, Datatables ok, finally i made though to get id show in datatables but not visible on grid. i want to get the id, throught jquery selector or any other good way if possible. Here is the Output HTML <table class="table table-bordered table-condensed table-hover table-striped dataTable no-footer" id="ManageForms" role="grid" aria-describedby="ManageForms_info" style="width: 1618px;"> <thead> <tr role="row"><th class="ui-state-default sorting" tabindex="0" aria-controls="ManageForms" rowspan="1" colspan="1" style="width: 351px;" aria-label="Form Name: activate to sort column ascending">Form Name</th><th class="ui-state-default sorting" tabindex="0" aria-controls="ManageForms" rowspan="1" colspan="1" style="width: 324px;" aria-label="Form Path: activate to sort column ascending">Form Path</th><th class="ui-state-default sorting" tabindex="0" aria-controls="ManageForms" rowspan="1" colspan="1" style="width: 535px;" aria-label="Form CI Path: activate to sort column ascending">Form CI Path</th><th class="ui-state-default sorting" tabindex="0" aria-controls="ManageForms" rowspan="1" colspan="1" style="width: 258px;" aria-label="Actions: activate to sort column ascending">Actions</th></tr> </thead> <tbody><tr role="row" class="odd" data-id="1"><td>Dashboard</td><td>#</td><td>admin/dashboard/System</td><td><a class="editBtnFunc" data-toggle="modal" href="#editBtnModal"><i class="fa fa-pencil fa-fw fa-2x" style="color: #666666"></i></a><a id="deleteBtn" href="#"><i class="fa fa-times fa-fw fa-2x" style="color: #ff0000"></i></a></td></tr><tr role="row" class="even" data-id="2"><td>Dashboard</td><td>#</td><td>admin/dashboard/Users</td><td><a class="editBtnFunc" data-toggle="modal" href="#editBtnModal"><i class="fa fa-pencil fa-fw fa-2x" style="color: #666666"></i></a><a id="deleteBtn" href="#"><i class="fa fa-times fa-fw fa-2x" style="color: #ff0000"></i></a></td></tr></tbody> </table> Just need to get the data-id from the tr. i tried this.closest('tr') but got error. any suggestions.. Here is the script. <script> $(document).ready(function() { var oTable = $('#ManageForms').dataTable({ "aoColumns": [ /* ID */ { "bVisible": false, "bSortable": false }, /* Form Name */ null, /* Form Path */ null, /* Form CI Path */ null, /* Actions */ null ], "bServerSide":true, "bProcessing":true, "bJQueryUI": true, "sPaginationType": "full_numbers", //"bFilter":true, //"sServerMethod": "POST", "sAjaxSource": "{{base_url()}}admin/configurations/listForms_DT/", "iDisplayLength": 2, "aLengthMenu": [[2, 25, 50, -1], [2, 25, 50, "All"]], /*"sEcho": 1, "columns":[ {data:"FormName"}, {data:"FormPath"}, {data:"FormCIPath"}, { "data": null, "defaultContent": "<a href='#editBtnModal' class='editBtnFunc' ><i style='color: #666666' class='fa fa-pencil fa-fw fa-2x'></i></a><a href='#' id='deleteBtn'><i style='color: #ff0000' class='fa fa-times fa-fw fa-2x'></i></a>", "targets": -1 } ],*/ 'fnServerData' : function(sSource, aoData, fnCallback){ $.ajax ({ 'dataType': 'json', 'type' : 'POST', 'url' : sSource, 'data' : aoData, 'success' : fnCallback }); //end of ajax }, 'fnRowCallback': function(nRow, aData, iDisplayIndex, iDisplayIndexFull) { $(nRow).attr("data-id",aData[0]); return nRow; } }); //Edit Button on Modal Window $('#ManageForms').on('click', '.editBtnFunc', function(e){ e.preventDefault(); var FormID = $(this).find('data-item').value(); console.log(FormID); }); //Edit Button } ); </script> A: I hope this will work for you: $(this).closest('tr').attr('data-id');
{ "pile_set_name": "StackExchange" }
Q: Progressive Web App - can it show a map using an offline Mapsforge .map file? Showing an offline map using 1 Mapsforge OSM map file is only possible in a HTML5 webapp using commercial tools like Mapbox. There are simply no free tools to do so, as you can read in this post. Is it possible to show an offline Mapsforge OSM map in an Progressive Web App? That would really be great. Why an offline Mapsforge file? It is a free and good OSM map. It is available as 1 file per (great) area, so not a huge bunch of small files in a x/y/z folder. A: After scanning solutions, I think there is a better alternative for accessing offline OSM maps via mapsforge. The solution is for caching OSM map requests. Using that approach you don't need to pre-load the mapsforge data. You just browse the area. An alternative is to start a 'seed' in order to pre-fetch lower levels of OSM data. Caching map requests are possible in a number of ways. As a first introduction, I refer to a recommendation for storing data offline: For URL addressable resources, use the Cache API (part of Service Worker). For all other data, use IndexedDB (with a Promises wrapper).
{ "pile_set_name": "StackExchange" }
Q: PHP Class Referring PDO Object I am creating 2 Class and from 1 class I am referring the other class a PDO Object. But when I refer any string of that class, but not when PDO Object. Any ideas? Here is my code class Connection { private $dbcc; public function Fn_Db_Conn() { $this->dbcc = new PDO( "mysql:host=localhost;dbname=db1;", "root","pass1"); return $this->dbcc; } } class Registration { private $Username; private $dbc; public function Registration($Un) { $this->Username = $Un; $this->dbc = new Connection; $this->dbc->Fn_Db_Conn(); } public function Fn_User_Exist() { $Qry = "SELECT * FROM CMT_Users WHERE Username=@Username"; $Result = $this->dbc->prepare($Qry); $Result->bindParam("@Username",$this->Username); $Result->execute(); print $Result->rowCount(); } } A: class Connection { private $_dbcc; public function getConnection() { return $this->_dbcc; } public function __construct() { $this->_dbcc = new PDO( "mysql:host=localhost;dbname=db1;", "root","pass1"); } } class Registration { private $_username; private $_dbc; public function __construct($un) { $this->_username = $un; $this->_dbc = new Connection(); } public function Fn_User_Exist() { $qry = "SELECT * FROM CMT_Users WHERE Username=@Username"; $result = $this->_dbc->getConnection()->prepare($qry); $result->bindParam("@Username",$this->_username); $result->execute(); print $result->rowCount(); } } I have also modified the Connection class to create the PDO object in the constructor and added a getConnection method for accessing the PDO object. You should use the __construct keyword for constructor, naming the constructor as the class name is the old syntax and make the code more difficult to edit. Last point, it depends on people but I prefer to prepend protected and private properties or methods by an underscore _, this way we can identify easily if the method/property is accessible outside of the class or not. You should aboid using variable like Result because PHP is case sensitive so Result is not equal to result, so better to avoid typo to keep the variable name in lower case(appart when you want to do camelCase).
{ "pile_set_name": "StackExchange" }
Q: Laravel и архитектура для Rest API Доброго времени суток! Пишу сервис на Laravel, в котором использую только API запросы. Возникли некоторые вопросы, так как ранее использовал Laravel только с шаблонизатором. Стандарт ответа сервера Есть 3 варианта возврата данных: Простой успешный ответ {"id": 33, "queue_number": 15, "user_name": "Alex"} Успешный ответ с пагинацией или простым списком {"count": 100, "page": 10, "data": [[JSON object]...]} Ошибка(и) {"errors": [["code": 1, message: "Undefined field(s)", fields: ["uid", "timestammp"]]]} У меня всего 12 видов ошибок. Я создал базовый класс BaseRestException и наследую от него каждый вид ошибки. Так вот, вопросы. Где на верхних уровнях отлавливать BaseRestException и приводить к третьему из описанных выше варианту возврата данных? Если я создаю для роута свой Request-класс и валидацию данных провожу внутри этого класса. Как в случае ошибок валидации мне вернуть ошибку в моем варианте возврата ошибок? A: На Ларавел есть единая точка прихода Исключений App\Exceptions\Handler.php. В этом классе можно делать с исключениями что угодно. Официальная документация: https://laravel.com/docs/7.x/errors#the-exception-handler Вопрос похожий на Ваш с хорошим ответом и примером реализации: https://stackoverflow.com/questions/51065170/laravel-api-how-to-properly-handle-errors По поводу валидации, откройте базовый FormRequest там можно покопаться и найти методы отвечающие за валидацию. Примеры с обработкой валидации и кастомного ответа: https://laracasts.com/discuss/channels/laravel/how-make-a-custom-formrequest-error-response-in-laravel-55?page=1 https://stackoverflow.com/questions/35097371/laravel-validation-error-customise-format-of-the-response
{ "pile_set_name": "StackExchange" }
Q: HTML Form - Fill input with value if nothing is entered I'm creating a basic subscribe form for a system that requires both email address and last name (SugarCRM in case anyone is interested). I need to populate the last name input value with something (anything, it doesn't matter) only if the visitor doesn't put their own last name in. As the subscribe action is hosted (Mail Chimp) I don't have access to it to pre-validate, unless this can happen before it's passed on. I'm wading into deeper PHP waters than I'm comfortable with! Is this possible with jQuery? So basically I'm getting around the required last name by filling the value with something. A: Check the lastname on submit of the form, if it doesn't have value, put "foo" in it: $('#formId').submit(function() { // attach submit handler to the form. var $lastName = $('#lastName'); // get the last name element. if (!$lastName.val()) // if it doesn't have value. $lastName.val('foo'); // put foo as a value. });​ You should replace formId and lastName to the actual ids of the form and last name element.
{ "pile_set_name": "StackExchange" }
Q: How do I convert an Exodus CSV private key export to JSON for Mist? I have a csv file that was exported from the EXODUS app with the following columns: ADDRESS PATH BALANCE PRIVKEY Is there a way to get this into json format standard so that I can import it in Ethereum Wallet? A: The full process, if you want to move from Exodus to Mist using just the "Developer -> Assets -> Ethereum -> Export Private Keys" menu is this: Take the private key in the PRIVKEY section and put it in a file on your desktop. Let's call it privatekey. Use geth to import the account. If you're on macOS: $ geth import account privatekey Geth will prompt you to create a password for the account and import it. Your new account is locked with a password. Please give a password. Do not forget this password. Passphrase: Repeat passphrase: Address: {39bd6536020d2b25006257064dd339d2a748f664} You could try to replicate the JSON format, but I don't recommend it. I pulled the instructions from this wiki article and verified that they work with both the latest versions of Mist and Exodus.
{ "pile_set_name": "StackExchange" }
Q: How to rescale ColorData in a non-linear fashion? I want to use Rescale on a ColorData, like this: ColorData[{"TemperatureMap", {-100, 10}}] However, I still want the value 0 to get plotted with the white color of the scheme. Any idea how to force Mma to do so? I tried "specific discrete values" {{x1, x2, ...}} but it's not working. A: What you need is a nonlinear function to map to, one that is close to zero for values near x=-100, reaches 1/2 at x=0, and 1 at x=10. This works, Plot[Exp[x Log[2]/10]/2, {x, -100, 10}, PlotRange -> All] So applying this to a ColorFunction cf = ColorData["TemperatureMap"][Exp[# Log[2]/10]/2] & BarLegend[{cf, {-100, 10}}] Using a 3-point Interpolating function J.M. suggested using a 3-point interpolation function, which at first I was unable to get to work. Here is a naive attempt, and remember that the function must stay between 0 and 1. Plot[Interpolation[{{-100, 0}, {0, .5}, {10, 1}}][x], {x, -100, 10}] Then I read the rest of his comment, about supplying derivatives. Still thinking about the exponential function above, I assumed the derivative should start at some small value and be monotonically increasing. Plot[Interpolation[{{{-100}, 0, .001}, {{0}, 1/2, 1}, {{10}, 1, 2}}][ x], {x, -100, 10}] which would clearly make an awful color map since more than one value would correspond to a single color. Here are derivative values that seem to work fun = Interpolation[{{{-100}, 0, 0}, {{0}, 1/2, .015}, {{10}, 1, .015}}]; {Plot[fun[x], {x, -100, 10}], BarLegend[{ColorData["TemperatureMap"][fun[#]] &, {-100, 10}}]} You could use Manipulate to get just the right color function as well, Manipulate[ fun = Interpolation[{{{-100}, 0, d1}, {{0}, 1/2, d2}, {{10}, 1, d3}}]; {Plot[fun[x], {x, -100, 10}, ImageSize -> 300], BarLegend[{ColorData["TemperatureMap"][fun[#]] &, {-100, 10}}]}, {d1, 0, .02}, {d2, 0, .02}, {d3, 0, .02}] Gonna take this time to mention this post which allows you to create a completely custom color function interactively. A: It can be done by applying ColorData["TemperatureMap"] to a piecewise function that rescales the intervals -100 to 0 and 0 to 10 separately. cf[u_] = ColorData["TemperatureMap"] @ Piecewise[ {{Rescale[u, {-100, 0}, {0., .5}], -100 < u < 0}, {Rescale[u, {0, 10}, {.5, 1.}], 0 <= u <= 10}}]; DensityPlot[x, {x, -100, 10}, {y, 0, 1}, ColorFunction -> cf, ColorFunctionScaling -> False] Update Since ColorData["TemperatureMap"] @ Piecewise[ {{Rescale[u, {-100, 0}, {0., .5}], -100 < u < 0}, {Rescale[u, {0, 10}, {.5, 1.}], 0 <= u <= 10}}] returns a color blend, cf can be written more directly as cf[u_] = Blend[ "TemperatureMap", Piecewise[{{0.5 + 0.005 u, -100 < u < 0}, {0.5 + 0.05 u, 0 <= u <= 10}}]]; Further, as J.M. suggests in his comment, an interpolating function can be used. cf[u_] = (ColorData["TemperatureMap"] @* Interpolation[{{-100, 0.}, {0, .5}, {10, 1.}}, InterpolationOrder -> 1])[u]; or cf[u_] = Blend[ "TemperatureMap", Interpolation[{{-100, 0.}, {0, .5}, {10, 1.}}, InterpolationOrder -> 1][u]];
{ "pile_set_name": "StackExchange" }
Q: node.js, cannot get returned result from inner function I have done this function, using geocoder module, to get the city from a couple of lat/long: // Get city from lat/long pair function getCityFromCoordinates(lat, long){ return geocoder.reverseGeocode(lat,long, function ( err, data ) { var city = "-"; if(err){ city = err.message; } else { if(data["results"].length == 0){ city = "not found"; } else { city = ""; var first_item = data["results"][0]; var address_components = first_item["address_components"]; for (var i=0; i<address_components.length;i++){ var current = address_components[i]; var types = current["types"]; for (var j=0;j<types.length;j++){ var type = types[j]; if((type == "locality") && (city == "")){ city = current["long_name"]; } } } } } console.log("City:" + city); return city; }); } When I call this function from another place, it correctly retrieve the city (I see this in the log) but it does not return the value. I'm sure this is linked to the geocoder.reserverGeocode function being embedded withing my function but I do not manage to fix this. A: geocoder.reverseGeocode is async, which means that you can't return the result from inside the callback. Try something like this: function getCityFromCoordinates(lat, long, cb){ return geocoder.reverseGeocode(lat,long, function ( err, data ) { var city = "-"; if(err){ return cb(err.message); } else { if(data["results"].length == 0){ return cb("not found"); } else { city = ""; var first_item = data["results"][0]; var address_components = first_item["address_components"]; for (var i=0; i<address_components.length;i++){ var current = address_components[i]; var types = current["types"]; for (var j=0;j<types.length;j++){ var type = types[j]; if((type == "locality") && (city == "")){ city = current["long_name"]; } } } } } console.log("City:" + city); cb(null, city); }); } Now you can use it like this in your code: getCityFromCoordinates(lat, long, function(err, city) { if (err) { console.log('error: '+err); } else { console.log('result: '+city); } });
{ "pile_set_name": "StackExchange" }
Q: Return specific HTTP Error Code from Grails Command Object validation Given a setup of a REST endpoint, which saves a User for example, is it possible to use a Command Object's validate() to get specific HTTP error codes, which can just be returned to the Controller for handling the response? I want to avoid the situation where the Controller action will have to handle lots of if blocks, to check for a specific error message, and do a lookup/convert it into a HTTP error code. For example, I'd like the custom validator to somehow tell the controller to return a 404, if it fails to find a matching user in the database. The below is not what I have tried. Instead, it is just a proof of concept of the ideal structure I'd like to use for validating REST parameters. Perhaps this is completely wrong, or that there is a better approach. If there is, that would also be welcome. e.g.: User.groovy ... class User { String username static constraints = { username unique:true } } UserController.groovy ... class UserController extends RestfulController { def update(UserCommand userCmd) { /* * Not actually working code, but proof of concept of what * I'm trying to achieve */ render status: userCmd.validate() } class UserCommand { Long id String username static constraints = { importFrom User /* * I also get that you can't return Error codes via the * custom validator, but also just to illustrate what I'm * trying to achieve */ id validator: { User user = User.get(id) if(user == null) { return 404 } } } } } A: So your example doesn't make a lot of sense. If you're saving a user and it can't be found, that's good, no? And if you're updating a user, you'd probably call an update() action in your controller. That said, while that seems like a good idea, since it won't work, I'd suggest something more like the following: class UserController { def edit() { withUser { user -> [user:user] } } private def withUser(id="id", Closure c) { def user = User.get(params[id]) if(user) { c.call user } else { flash.message = "The user was not found." response.sendError 404 } } } You can adjust that to deal with your command object but I think that gives the general idea of being more DRY.
{ "pile_set_name": "StackExchange" }
Q: Change object state when using get Hi I was reading on the microsoft website when I found this, can someone please explain why this is bad programming, because I see it in the way of doing more in less lines of coding. Ps I am still a novice in classes... It is a bad programming style to change the state of the object by using the get accessor. For example, the following accessor produces the side effect of changing the state of the object every time that the number field is accessed. private int number; public int Number { get { return number++; // Don't do this } } A: Certainly... Get is read by most developers as a read only action, and people reading your code will not expect a Get property to be modifying any data. It's a convention, but when you think about it, one that makes sense - it helps us all to understand one another's code. In the example you cite, one approach would be to make this into two calls - a get, followed by a set to increment the variable... Another would be to implement a method to increment the variable and return the result. A: As given in your example, lets assume a situation. You are developing an API in which you are providing the size of the collection(Number) you have restricted to use by the user, but you are allowing the user to see how many contents/items are there in the collection. Now one has to get the counts at three different places- and in that case you are increasing the number every time he gets it, that is absolutely wrong. Hope you got the point, why its a bad programming style.
{ "pile_set_name": "StackExchange" }
Q: Testing express middleware and catch error I'm trying to assert an error which is thrown async in an express middleware: The middleware to test: const request = require('request'); const middleware = function (options) { if (!options) { throw new Error('Options are missing.'); // gets catched } request(options.uri, (err, response) => { if(err) { throw err; } }); return function (req, res, next) {} } module.exports = middleware; The mocha test: describe('middleware', () => { describe('if async error is thrown', () => { it('should return an error', done => { try { middleware({ uri: 'http://unkown' }); } catch (err) { assert.equal('Error: getaddrinfo ENOTFOUND unkown unkown:80', err.toString()); return done(); } }); }); }) The problem is, that err doesn't get catched inside the test: Uncaught Error: getaddrinfo ENOTFOUND unkown unkown:80 at errnoException (dns.js:27:10) at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:78:26) I understand that it happens because the error is thrown async but I don't know how to work around it here. A: As you are working with asynchronous code, try-catch & throw can't help you as they deal only with synchronous code. A workaround const request = require('request'); const middleware = function(options) { // <--- outer scope var api_output = null; // Store the output of the HTTP request here if (!options) throw new Error('Options are missing.'); // Express shouldn't handle this error, hence we throw it (also this error is synchronous) return function(req, res, next) { // <--- inner scope if (!api_output) { // Check if the output of the HTTP request has already been saved (so as to avoid calling it repeatedly) request(options.uri, (error, response, body) => { // Perform the HTTP request if (error) return next(error); // Pass the error to express error-handler api_output = { // Save the output of the HTTP request in the outer scope response: response, body: body }; req.api_output = api_output; // Set the output of the HTTP request in the req so that next middleware can access it next(); // Call the next middleware }); } else { // If the output of the HTTP request is already saved req.api_output = api_output; // Set the output of the HTTP request in the req so that next middleware can access it next(); // Call the next middleware } }; } module.exports = middleware; What I've done is simply returned an express-middleware that calls the external API only if it has not already been called. If there is no error, then it stores the response of the external API in api_output and also pass it to the next express-middleware where you can use it. To understand how this works it is essential to know how JavaScript deals with scopes (look up closure). Instead of calling the 3rd party API every time the express-middleware gets executed, I have stored the output of that API in the outer scope of the express-middleware function the first time it is called. The advantage of doing this is that the output of the 3rd party API is private to the outer & inner scope and not accessible from anywhere else in the app. If there is any error, it is passed to the next callback (this triggers the express error-handler functions). See "Express error handling", to see how this works. Specifically this - If you pass anything to the next() function (except the string 'route'), Express regards the current request as being in error and will skip any remaining non-error handling routing and middleware functions. You can use the above function in this way while creating your routes: const router = require('express').Router(); router .get('/my-route', middleware({ uri: 'my-url' }), function(req, res, next) { // here you can access req.api_output.response & req.api_output.body // don't forget to call next once processing is complete }); Now, regarding testing In your mocha testing framework, you can call your API using request module in the same way that you have used it in your middleware function to call the external API. Then you can assert the output easily: Use try-catch with assertions to handle the Error from middleware function Use normal assertions to deal with errors from the express-middlewares Note that I have used the term "express-middleware" to refer only to middlewares like function(req, res, next) {}. And I've used the term "middleware" to refer to your function called middleware.
{ "pile_set_name": "StackExchange" }
Q: knitr chunk to parametrize a chapter master file I'm writing a book using a book.Rnw master file to compile the whole thing and a chapter.Rnw file to compile just a single chapter. I have to do this because it takes too long to compile the whole book when I'm working on one chapter, and knitr doesn't support the \includeonly{} facility of LaTeX because it writes all child documents to a single file, rather than separate files than can be \include{}ed. To keep the page and chapter/section numbers straight in the chapter, I use the following LaTeX in chapter.Rnw, but comment out those lines for other chapters, unless it is the last. \documentclass[11pt]{book} ... % Ch 1 \setcounter{chapter}{0} % one less than chapter number \setcounter{page}{0} % one less than book page number % Ch 2 \setcounter{chapter}{1} % one less than chapter number \setcounter{page}{18} % one less than book page number ... % Ch 7 \setcounter{chapter}{6} % one less than chapter number \setcounter{page}{236} % one less than book page number followed by a child chunk for the current chapter: \begin{document} <<ch7, child='ch07.Rnw'>>= @ ... \end{document} I'd like to parametrize the \setcounter{} calls with a chunk. Here is what I tried, before the \begin{document} but it doesn't work, probably because I don't quite know how to mix R and Latex output in a chunk: <<set-counters, results='asis', tidy=FALSE, echo=FALSE>>= .pages <- c(1, 19, 51, 101, 145, 201, 237) .chapter <- 7 \setcounter{chapter}{.chapter-1} % one less than chapter number \setcounter{page}{.pages[.chapter]-1} % one less than book page number @ I am getting the following error: > knit2pdf("chapter.Rnw", quiet=TRUE) Quitting from lines 124-128 (chapter.Rnw) Error in parse(text = x, srcfile = src) : <text>:3:1: unexpected input 2: .chapter <- 7 3: \ A: Thou have forgotten about a call to the cat function: cat("\\setcounter{chapter}{", .chapter-1, "}", sep="") cat("\\setcounter{page}{", .pages[.chapter]-1, "}", sep="") You may call these in a loop, together with cat("\\include{", filename[.chapter], "}", sep=""). This is how I typeset my R book (each chapter was compiled manually, and then the whole manuscript was generated via aggregation of the resulting .tex files).
{ "pile_set_name": "StackExchange" }
Q: SQL - Delete object with inner join I'm trying to delete an object from my store using SQL and an inner join Here is what I have: DELETE appointment_object FROM appointment_table appointment_object INNER JOIN sales_person_table sales_person_object ON appointment_object.made_by.personno = sales_person_object.personno WHERE sales_person_object.personno = 3; Here's my error: Error report - SQL Error: ORA-00903: invalid table name 00903. 00000 - "invalid table name" *Cause: *Action: all property names and table names are correct, though. I'm also getting some syntax highlighting between appointment_object FROM with the error: Expected WHERE, PARTITION Any ideas? A: Try rephrasing this using exists or in: DELETE FROM appointment_table WHERE EXISTS (SELECT 1 FROM sales_person_table sp WHERE a.made_by.personno = sp.personno AND sp.personno = 3 );
{ "pile_set_name": "StackExchange" }
Q: How do I know if requestLocationUpdate is active? I would like to set some property only if requestLocationUpdate() is actually running. How do I test if it is "on"? A: You can set the interval in which the requestLocationUpdates(PROVIDER, MIN_TIME_BTW_UPDATES, MIN_DIST_BTW_UPDATES, listener); according to your requirements by setting the minimum time and distance covering which, will cause the updates to function again. This repeatedly sends updates using the specified parameters to the LocationListener until you call removeUpdates(). If you set the values to 0 then there will be no delay between updates. If you want to actually go on and "test" if it's on just get the location into an object and see if its null.
{ "pile_set_name": "StackExchange" }
Q: Tkinter window does not update correctly when running I'm trying to make a Tkinter window show updated data but it only pops up after 13 seconds with just the last value. I want it to pop up and change the values on screen. Mind you, the big goal of this code is to take data from a database (which updates every 3 seconds) and show the data onscreen, while running continuously, so if the answer could include some pointers on the "after" or "update" functions it would be greatly appreciated! Here is what I have so far. from tkinter import * import time class GUI(Tk): def __init__(self, *args, **kwargs): Tk.__init__(self, *args, **kwargs) Tk.wm_title(self, "Main Window") self.container = Frame(self) self.container.pack(side=TOP, fill=BOTH, expand=TRUE) self.container.grid_rowconfigure(0, weight=1) self.container.grid_columnconfigure(0, weight=1) self.frames = {} self.frame = StartPage(self.container, self) self.frames[StartPage] = self.frame self.frame.grid(row=0, column=0, sticky=NSEW) self.show_frame(StartPage) def show_frame(self, controller): frame = self.frames[controller] frame.tkraise() class StartPage(Frame): def __init__(self, parent, controller): Frame.__init__(self, parent) self.label = Label(self, text="Current ID:\n") self.label.pack(padx=10, pady=10) self.data_label = Label(self) self.data_label.pack() self.update_data() def update_data(self): var1 = StringVar() for i in range(10): var1.set(str(i)) self.data_label.config(text=str(i)) time.sleep(1) main = GUI() main.mainloop() A: I can give you a partial answer. The reason you don't see any updates is that time.sleep() suspends the process and does not allow for tkinter to repaint the window. You don't use the label textvariable correctly. Specify it in the label and the label will change as you change the textvariable. You use both pack and grid at the same time which may cause problems. I have not used after() in a class before so I don't know how to work it, but this example should give you some pointers. I'm keeping console printouts in the code so I can see what it does. from tkinter import * import time class GUI(Tk): def __init__(self, *args, **kwargs): Tk.__init__(self, *args, **kwargs) Tk.wm_title(self, "Main Window") self.container = Frame(self) self.container.pack(side=TOP, fill=BOTH, expand=TRUE) self.frames = {} self.frame = StartPage(self.container, self) self.frames[StartPage] = self.frame self.frame.pack(side=TOP, fill=BOTH, expand=TRUE) self.show_frame(StartPage) def show_frame(self, controller): frame = self.frames[controller] frame.tkraise() frame.update_data() print('Done') class StartPage(Frame): def __init__(self, parent, controller): Frame.__init__(self, parent) self.parent = parent self.label = Label(self, text="Current ID:\n") self.label.pack(padx=10, pady=10) self.var1 = StringVar() self.data_label = Label(self, textvariable=self.var1) self.data_label.pack() self.update_idletasks() # Calls all pending idle tasks def update_data(self): if not self.var1.get(): self.var1.set('0') iteration = int(self.var1.get()) print('iteration', iteration) if iteration < 3: iteration = iteration + 1 self.var1.set(str(iteration)) self.update_idletasks() # Calls all pending idle tasks time.sleep(1) self.update_data() main = GUI() main.mainloop() You will have to research after() yourself as I can't help you there.
{ "pile_set_name": "StackExchange" }
Q: ANTLR and Android is there any guide how to use ANTLR on Android? I have found some ANTLR portation for Android but it looks like being without any tutorial or manual. Do you know where to find some? (and yes, I have been googling...) Thx A: After reading the README from this ANTLR port: AntlrJavaRuntime - Earlence Fernandes, The CRePE Project, VU Amsterdam ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The Runtime is available as an external library against which apps can link. It provides the necessary mechanisms to execute Lexer/Parser code generated by the ANTLR tool. The model is offline, in the sense that the parser/lexer is generated off the mobile phone on a desktop computer. The resulting files are transferred to an Android project which then uses this library. Building ~~~~~~~~ lunch the appropriate target make AntlrJavaRuntime verify that AntlrJavaRuntime.xml was placed in /system/etc/permissions and AntlrJavaRuntime.jar was placed in /system/framework after this, you can run a normal make It seems to me that the only difference is when you want to run your parser on an Android device (or -emulator) you must include the AntlrJavaRuntime in your Android project/app. So, writing the grammar, generating a parser and lexer from said grammar would be the same as on a "normal" machine. Here's a previous Q&A that shows how to write a simple expression parser: ANTLR: Is there a simple example? EDIT Also see this Q&A: android ANTLR make not working properly
{ "pile_set_name": "StackExchange" }
Q: Update a key value inside an array in Mongodb I'm having problems trying to update from mongoDB the "name" key inside gardens. { name: "Adky", email: "[email protected]", lastConected: "", gardens: [{ name: '', location_id: "43567", plants: [] }, { name: '', location_id: "234092", plants: [] }, { name:'', location_id: "22355", plants: [] }] } I tried collection .findOneAndUpdate({ _id: ObjectId(id) },{ "gardens.location_id": req.params.location_id }, { $set: { "gardens.$.name": updatedData.name } }, { returnOriginal: false } But This error comes up { "status": 500, "error": { "driver": true, "name": "MongoError" } } Don't really know what to do here.. I was thinking that the problem should be in the way I'm accessing into gardens. A: FindOneAndUpdate takes 3 parameters db.collection.findOneAndUpdate( <filter>, <update document or aggregation pipeline>, // Changed in MongoDB 4.2 { projection: <document>, sort: <document>, maxTimeMS: <number>, upsert: <boolean>, returnNewDocument: <boolean>, collation: <document>, arrayFilters: [ <filterdocument1>, ... ] } ) but you are passing 4 parameters, you can update your code collection .findOneAndUpdate({ _id: ObjectId(id), "gardens.location_id": req.params.location_id }, { $set: { "gardens.$.name": updatedData.name } }, { returnOriginal: false }) You can find your document using both _id and location_id.
{ "pile_set_name": "StackExchange" }
Q: Dynamically change image src using Jquery not working in IE and firefox I am implementing a captcha for a email. when click on linkEmail button email modal will open. there i have to set captcha image generated by a handler (CaptchaGenerator.ashx) on click of linkEmail button click. Here is the code for that. $(".linkEmail").click(function () { //Load captcha image $('.imgCaptcha').attr('src', '/Custom/AppCode/Utilities/CaptchaGenerator.ashx'); $('#emailModal').modal(); }); Above code is working fine in crome but not working in IE and firefox. Although i have tried followings there is no luck. HTML: <p id="captchacontainerp" class="captchacontainer"></p> ------------------------------------------------------------- $('#captchacontainerp').prepend($("<img id='imCaptcha' class='imgCaptcha' src='/Custom/AppCode/Utilities/CaptchaGenerator.ashx'></img>")); ------------------------------------------------------------- var img = $('<img id="imCaptcha" class="imgCaptcha">'); img.attr('src', '/Custom/AppCode/Utilities/CaptchaGenerator.ashx'); $('#captchacontainerp').empty(); img.appendTo('#captchacontainerp'); --------------------------------------------------------------- $('#captchacontainerp').empty(); $('#captchacontainerp').append($("<img id='imCaptcha' class='imgCaptcha' src='/Custom/AppCode/Utilities/CaptchaGenerator.ashx'></img>")); A: IE caching all GET request, so add a timestamp to your request URL e.g : $(".linkEmail").click(function () { //Load captcha image $('.imgCaptcha').attr('src', '/Custom/AppCode/Utilities/CaptchaGenerator.ashx?'+new Date().getTime()); $('#emailModal').modal(); });
{ "pile_set_name": "StackExchange" }
Q: How to get and set a global object in Java servlet context I wonder if anyone can advise: I have a scenario where a scheduled job being run by Quartz will update an arraylist of objects every hour. But I need this arraylist of objects to be visible to all sessions created by Tomcat. So what I'm thinking is that I write this object somewhere every hour from the Quartz job that runs so that each session can access it. Can anyone say how best this may be achieved? I was wondering about the object being written to servlet context from the Quartz job? The alternative is having each session populate the arraylist of objects from a database table. Thanks Mr Morgan. A: Yes, I would store the list in the ServletContext as an application-scoped attribute. Pulling the data from a database instead is probably less efficient, since you're only updating the list every hour. Creating a ServletContextListener might be necessary in order to give the Quartz task a reference to the ServletContext object. The ServletContext can only be retrieved from JavaEE-related classes like Servlets and Listeners. EDIT: In the ServletContextListener, when you create the job, you can pass the list into the job by adding it to a JobDataMap. public class MyServletContextListener implements ServletContextListener{ public void contextInitialized(ServletContextEvent event){ ArrayList list = new ArrayList(); //add to ServletContext event.getServletContext().setAttribute("list", list); JobDataMap map = new JobDataMap(); map.put("list", list); JobDetail job = new JobDetail(..., MyJob.class); job.setJobDataMap(map); //execute job } public void contextDestroyed(ServletContextEvent event){} } //Quartz job public class MyJob implements Job{ public void execute(JobExecutionContext context){ ArrayList list = (ArrayList)context.getMergedJobDataMap().get("list"); //... } }
{ "pile_set_name": "StackExchange" }
Q: How to reconcile the Didache's instruction with Apostolic succession? As it pertains primarily to Catholicism, Eastern Orthodoxy, and other large denominations that not only lay claim to an unbroken successive line, but who also put significant emphasis on it: The Didache instructs congregations to "elect" Bishops and Deacons "for themselves." Chap. XV. Elect therefore for yourselves Bishops and Deacons worthy of the Lord, men meek, and not lovers of money, and truthful, and approved; for they too minister to you the ministry of the Prophets and Teachers. http://www.catholicplanet.com/ebooks/didache.htm My initial understanding of this would be that these communities are in charge of [democratically?] naming their own clergy. That in itself isn't terribly contradictory sounding, but there's no mention of any formal process or Church approval -- let alone a consecration of the "elected" by the Church. The omission of such formality in what appears to be a very formal and detailed early "Church Handbook" seems to call into question the notion that a strict Apostolic Succession was present in the early Church. In the very least, one might wonder whether some congregations in the early Church did elect their own Bishops, without pre-approval or education by the Church, blurring the line of succession. How do we adequately square the Didache's instruction with Apostolic Succession? A: Henry Chadwick writes about this in his book The Early Church (Penguin, 1993), on page 50. First he explains that the role of the "bishop" (episkopos) evolved to be a primus among the elders (presbyters) in the late apostolic or early post-apostolic era. But it would take a while until the bishop received a more formal recognition as a separate tier of leadership. The writings of Ignatios of Antioch thus do not describe a common practice at his time, but something he recommends, and that gradually became accepted as a way to guarantee unity. The pressure from gnostic movements was the primary influencing factor. The episkopos thus remained a presbyter as well. The first thing that differentiated bishops from other elders, was the power to ordain. He would be the primary layer on of hands, when a new presbyter was ordained, though others might join in. But when a new episkopos was ordained, all of the other presbyters would lay hands on him, though "some variations in custom appears". At Alexandria we are told they did so, until the third century and there is no mention of visiting bishops; but in Rome by the time of Hippolytos (early 3d century presbyter) only the bishops who came from other churches laid hands on the one consecrated, the chief consecrator being chosen by the bishops themselves... The actual choice of the candidate rested with the whole congregation... Election by the people likewise played a large part in the ordination of presbyters and deacons. This of course is a secondary source, but from my reading of other books on Church History, the explanation is non-controversial.
{ "pile_set_name": "StackExchange" }
Q: cannot use Url.Action in the class file in my asp.net mvc3 web site, I use Url.Action in the view to generate url. @Url.Action("Profile", "Users", new { @Id = Model.UserId, name = Model.NickName }) now, in one of my helper class, I need to do the same. but get this error message, "The name 'Url' does not exist in the current context. is there another function I can use to generate url? A: @Url in your example is an instance of UrlHelper class. You can create an instance of it and use in any class like in the example below, but you need to have an access to the RequestContext (named context in my example) of the corresponding View. var urlHelper = new UrlHelper(context); string absUrl = urlHelper.Action("ActionName", "ControllerName", null, Request.Url.Scheme);
{ "pile_set_name": "StackExchange" }
Q: A continuous function $f:[0,\infty)\to \mathbb{R}$ such that $\lim\limits_{x\to \infty} \left(f(x)+\int_0^x f(t) dt \right)=0$ Let $f:[0,\infty)\to \mathbb{R}$ be a continuous function such that $\lim\limits_{x\to \infty} \left(f(x)+\int_0^x f(t) dt \right)=0$. Prove that $$\lim \limits_{x\to \infty} \int_0^x f(t)dt=0.$$ I don't understand the solution presented in my book. They start by saying that $$\lim_{x\to\infty}\int_0^x f(t) dt= \lim_{x\to \infty} \frac{e^x \cdot \int_0^x f(t)dt}{e^x}$$and then they apply L'Hospital's rule. Why is this allowed? We don't know the limit of the numerator, so we can't be sure that this is $\frac{\infty}{\infty}$. A: L'Hospital's rule can be applied here because it is sufficient that the denominator diverges to $\infty$. This (perhaps not so well-known case) is hidden as a remark in L'Hôpital's rule – General proof on Wikipedia: This means that if $|g(x)|$ diverges to infinity as $x$ approaches $c$ and both $f$ and $g$ satisfy the hypotheses of L'Hôpital's rule, then no additional assumption is needed about the limit of $f(x)$. Here we have (for $x \to \infty$) $$ f(x) = \frac{e^x \cdot \int_0^x f(t)dt}{e^x} \sim \frac{e^x \cdot \int_0^x f(t)dt + e^x f(x)}{e^x} = f(x)+\int_0^x f(t) dt $$ and the right-hand side converges to zero. L'Hospital's rule then implies that the left-hand side converges to zero as well.
{ "pile_set_name": "StackExchange" }
Q: ArrayList showing wrong values I have created a database which stores group details.I want to show that group details in a listview.But when i open my app i only see the the last values in the database.why this is happening??? Getting Value from database public ArrayList<GroupModel> getAllGroups() { SQLiteDatabase database = getWritableDatabase(); String query = "Select * From " + tableName; GroupModel groupModel; Cursor c = database.rawQuery(query, null); while (c.moveToNext()) { getGroupInfo = new ArrayList<GroupModel>(); groupModel = new GroupModel(c.getString(c.getColumnIndexOrThrow(groupName)), c.getString(c.getColumnIndexOrThrow(createdOn))); getGroupInfo.add(groupModel); } return getGroupInfo; } When i debugged my 1st iteration List value[0]="A","B" 2nd iteration List value[0]="p","q"; why this is happeninng, the desired outcome should be 1st iteration List value[0]="A","B" 2nd iteration List value[1]="p","q"; Model Class public class GroupModel { private String groupId, groupName, groupCreatedDate, contactId, contactName, contactNumber; public GroupModel() { } public GroupModel(String groupName, String groupCreatedDate) { this.groupName = groupName; this.groupCreatedDate = groupCreatedDate; } public GroupModel(String groupId, String contactId, String contactName, String contactNumber) { this.groupId = groupId; this.contactId = contactId; this.contactName = contactName; this.contactNumber = contactNumber; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getGroupName() { return groupName; } public void setGroupName(String groupName) { this.groupName = groupName; } public String getGroupCreatedDate() { return groupCreatedDate; } public void setGroupCreatedDate(String groupCreatedDate) { this.groupCreatedDate = groupCreatedDate; } public String getContactId() { return contactId; } public void setContactId(String contactId) { this.contactId = contactId; } public String getContactName() { return contactName; } public void setContactName(String contactName) { this.contactName = contactName; } public String getContactNumber() { return contactNumber; } public void setContactNumber(String contactNumber) { this.contactNumber = contactNumber; } } A: you are creating to much groupInfo object. Move its instantiation out the while loop getGroupInfo = new ArrayList<GroupModel>(); while (c.moveToNext()) { groupModel = new GroupModel(c.getString(c.getColumnIndexOrThrow(groupName)), c.getString(c.getColumnIndexOrThrow(createdOn))); getGroupInfo.add(groupModel); } A: There while (c.moveToNext()) { getGroupInfo = new ArrayList<GroupModel>(); groupModel = new GroupModel(c.getString(c.getColumnIndexOrThrow(groupName)), c.getString(c.getColumnIndexOrThrow(createdOn))); getGroupInfo.add(groupModel); } you initializing arrayList everytime. you have to initialize arrayList before and outside while loop.
{ "pile_set_name": "StackExchange" }
Q: Generating different shades of the same colour in R I want to generate different shades of a colour going from lighter tone to darker tone colfunc <- colorRampPalette(c("green", "red")) colfunc(10) plot(rep(1,10),col=colfunc(10),pch=19,cex=3) If I try to run this for a single colour colfunc <- colorRampPalette("green") colfunc(10) [1] "#00FF00" "#00FF00" "#00FF00" "#00FF00" "#00FF00" "#00FF00" [7] "#00FF00" "#00FF00" "#00FF00" "#00FF00" It returns me the same values. How can I generate different shades of a single colour say going from light green to darker green? A: fc <- colorRampPalette(c("green", "darkgreen")) plot(rep(1, 10),col = fc(10), pch = 19, cex = 3) Is it what you need?
{ "pile_set_name": "StackExchange" }
Q: how to use regex.Matches in c# how to use regex.Matches input string string strQuery = "BO_WEEKOFF_MASTER.year, week_off_day=case when "+ "BO_WEEKOFF_MASTER.week_off_day ='1' then 'Sunday' "+ "when BO_WEEKOFF_MASTER.week_off_day ='2' then 'Monday' "+ "when BO_WEEKOFF_MASTER.week_off_day ='3' then 'Tuesday' "+ "when BO_WEEKOFF_MASTER.week_off_day ='4' then 'Wednesday' "+ "when BO_WEEKOFF_MASTER.week_off_day ='5' then 'Thursday' "+ "when BO_WEEKOFF_MASTER.week_off_day ='6' then 'Friday' "+ "when BO_WEEKOFF_MASTER.week_off_day ='7' then 'Saturday' "+ "else '' end,"+ "BO_WEEKOFF_MASTER.year, week_off_day=case when "+ "BO_WEEKOFF_MASTER.week_off_day ='1' then 'Sunday' "+ "when BO_WEEKOFF_MASTER.week_off_day ='2' then 'Monday' "+ "when BO_WEEKOFF_MASTER.week_off_day ='3' then 'Tuesday' "+ "when BO_WEEKOFF_MASTER.week_off_day ='4' then 'Wednesday' "+ "when BO_WEEKOFF_MASTER.week_off_day ='5' then 'Thursday' "+ "when BO_WEEKOFF_MASTER.week_off_day ='6' then 'Friday' "+ "when BO_WEEKOFF_MASTER.week_off_day ='7' then 'Saturday' "+ "else '' end,"; my pattern is MatchCollection words = Regex.Matches(strQuery, @"(?i)?<firstMatch>.*,) (?<secondMatch>[^=]*)=case(?<thirdMatch>.*end\b)"); foreach (Match word in words) { strQuery = Regex.Replace(word , @"....", @" ... ", RegexOptions.IgnoreCase); } issue is its matching only once i need output like below BO_WEEKOFF_MASTER.year, case when BO_WEEKOFF_MASTER.week_off_day ='1' then 'Sunday' when BO_WEEKOFF_MASTER.week_off_day ='2' then 'Monday' when BO_WEEKOFF_MASTER.week_off_day ='3' then 'Tuesday' when BO_WEEKOFF_MASTER.week_off_day ='4' then 'Wednesday' when BO_WEEKOFF_MASTER.week_off_day ='5' then 'Thursday' when BO_WEEKOFF_MASTER.week_off_day ='6' then 'Friday' when BO_WEEKOFF_MASTER.week_off_day ='7' then 'Saturday' else '' end **" week_off_day"** , BO_WEEKOFF_MASTER.year, case when BO_WEEKOFF_MASTER.week_off_day ='1' then 'Sunday' when BO_WEEKOFF_MASTER.week_off_day ='2' then 'Monday' when BO_WEEKOFF_MASTER.week_off_day ='3' then 'Tuesday' when BO_WEEKOFF_MASTER.week_off_day ='4' then 'Wednesday' when BO_WEEKOFF_MASTER.week_off_day ='5' then 'Thursday' when BO_WEEKOFF_MASTER.week_off_day ='6' then 'Friday' when BO_WEEKOFF_MASTER.week_off_day ='7' then 'Saturday' else '' end **"week_off_day"**, where i made error, thank u A: You need to use capturing groups. Regex.Replace(word , @"(\w+)=(case.*?\bend\b)", @"$2 ""$1""", RegexOptions.IgnoreCase); DEMO
{ "pile_set_name": "StackExchange" }
Q: Convert unique_ptr to void* and back, do I need to free? In my code I use a library that has a function store_pointer accepting a void* and saving it in memory. There is then another function retrieve_pointer() that returns this void * to me, I don't have control over this library so I can't change how the function behaves. Now I need to pass a variable to this function and get the pointer back, I have the code set up as follows: struct Task { int mId; Task(int id ) :mId(id) { std::cout<<"Task::Constructor"<<std::endl; } ~Task() { std::cout<<"Task::Destructor"<<std::endl; } }; std::unique_ptr<Task> taskPtr(new Task(23)); store_pointer(&taskPtr); // do stuff that doesn't involve taskPtr Task *new_taskPtr = reinterpret_cast<Task *>(retrieve_pointer()); // do stuff with new_taskPtr pointer Right now this all works but I wonder if the *new_taskPtr pointer needs to be deleted or if the reinterpret_cast "restores" the pointer to a unique_ptr and so the memory will be deleted automatically when it goes out of scope/the program ends. A: std::unique_ptr<Task> taskPtr(new Task(23)); When this variable goes out of scope, the dynamic allocation will be deleted. There is no need to, and you mustn't delete it yourself unless you call release on the unique pointer, which is the only way to transfer the ownership out of a unique pointer (besides transferring ownership to another unique pointer). Any casts that you may do have no effect on this.
{ "pile_set_name": "StackExchange" }
Q: Getting: error C2668: 'sqrt' : ambiguous call to overloaded function Trying to build the source code below from an example given in a textbook. I'm using visual studio 2008. The compiler doesn't seem to know what to do with sieve: 1>------ Rebuild All started: Project: fig21.40, Configuration: Debug Win32 ------ 1>Deleting intermediate and output files for project 'fig21.40', configuration 'Debug|Win32' 1>Compiling... 1>fig21_40.cpp 1>c:\users\ocuk\documents\c++\chapter 21\fig21.40\fig21.40\fig21_40.cpp(27) : error C2668: 'sqrt' : ambiguous call to overloaded function 1> c:\program files (x86)\microsoft visual studio 9.0\vc\include\math.h(581): could be 'long double sqrt(long double)' 1> c:\program files (x86)\microsoft visual studio 9.0\vc\include\math.h(533): or 'float sqrt(float)' 1> c:\program files (x86)\microsoft visual studio 9.0\vc\include\math.h(128): or 'double sqrt(double)' 1> while trying to match the argument list '(const int)' 1>Build log was saved at "file://c:\Users\ocuk\Documents\C++\Chapter 21\fig21.40\fig21.40\Debug\BuildLog.htm" 1>fig21.40 - 1 error(s), 0 warning(s) ========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ========== code: //Fig. 21.40: fig21_40.cpp //Using a bitset to demonstrate the Sieve of Eratosthenses #include <iostream> using std::cin; using std::cout; using std::endl; #include <iomanip> using std::setw; #include <bitset> //bitset class definition #include <cmath> //sqrt prototype int main() { const int size=1024; int value; std::bitset<size> sieve; sieve.flip(); //perform Sieve of Eratosthenses int finalBit = sqrt( sieve.size() ) + 1; for(int i=2; i<finalBit; ++i) if(sieve.test(i)) for(int j=2*i; j<size; j+=i) sieve.reset(j); cout << "The prime numbers in the range 2 to 1023 are:\n"; //display prime numbers in range 2-1023 for(int k=2, counter=0; k<size; ++k) if(sieve.test(k)){ cout <<setw(5)<<k; if(++counter % 12 ==0) cout << '\n'; }//end outer if cout << endl; //get value from user to determine whether value is prime cout << "\nEnter a value from 1 to 1023(-1 to end): "; cin>>value; while(value != -1){ if(sieve[value]) cout << value << " is a prime number\n"; else cout << value << " is not a prime number\n"; cout << "\nEnter a value from 2 to 1023 (-1 to end): "; cin >> value; }//end while return 0; } A: I think that is because in newer versions of C++, sqrt is overloaded (argument can be double, float or long double) and you pass in an int. Just cast the argument to double to make it clear: int finalBit = sqrt( (double) (sieve.size()) ) + 1;
{ "pile_set_name": "StackExchange" }
Q: How to do dropdown on imageclick? This is my code: <img src="img/fastcall150.png" id="round" onclick="myFunction();" /> <img src="img/gesturecall150.png" id="round" onclick="myFunctio();" class="dropbtn" /> <div id="myDropdown" class="dropdown-content"> <a href="javascript:myFunc()"> Shake Gesture</a> </div> <script> /* When the user clicks on the button, toggle between hiding and showing the dropdown content */ function myFunctio() { document.getElementById("myDropdown").classList.toggle("show"); } // Close the dropdown if the user clicks outside of it window.onclick = function(event) { if (!event.target.matches('.dropbtn')) { var dropdowns = document.getElementsByClassName("dropdown-content"); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } } </script> This is CSS: .dropbtn { cursor: pointer; } .dropbtn:hover, .dropbtn:focus { background-color: #3e8e41; } .dropdown { position: relative;*/ display: inline-block;*/ } .dropdown-content { display: none; /* position: absolute;*/ text-align:center; background-color: #fff400; min-width: 160px; overflow: auto; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown a:hover {background-color: #dadada} .show {display:block;} This is What i tried ,if i give this code on button click Everything works perfectly.But when i was Tried this same on img click Drop down not appear properly . A: I fixed it, and remember, never set the same id for two or more elements, because an id is unique. If you want to add same style for many elements, than you set same classes to those elements. Good luck! $(document).ready(function(){ $('img').click(function(e){ e.stopPropagation(); $('#myDropdown').toggleClass('show'); }); window.onclick = function(event) { if (!event.target.matches('.dropbtn')) { var dropdowns = document.getElementsByClassName("dropdown-content"); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } } }); img.round { border-radius:50%; width:100px; height:100px; background-color:#ffcccc; display:block; outline:0; margin:25% auto; cursor: pointer; pointer-events: default; } .dropbtn { cursor: pointer; } .dropbtn:hover, .dropbtn:focus { background-color: #3e8e41; } .dropdown { position: relative;*/ display: inline-block;*/ } .dropdown-content { display: none; /* position: absolute;*/ text-align:center; background-color: #fff400; min-width: 160px; overflow: auto; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown a:hover {background-color: #dadada} .show {display:block;} <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <img src="img/fastcall150.png" class="round test" /> <img src="img/gesturecall150.png" class="dropbtn round" /> <div id="myDropdown" class="dropdown-content"> <a href="javascript:myFunc()"> Shake Gesture</a> </div>
{ "pile_set_name": "StackExchange" }
Q: SQL Server Management Studio 2005 and Source Control I have all my SQL stored in source control in the following structure Database Tables Stored Procs Views Static Data I'd like to tie my source control into SSMS, which seemingly supports source control, but SSMS wants to put all the scripts into one folder, which is a non-starter for me. Is it possible to get SSMS to work my existing structure? If not, is SSMS 2008 a bit more flexible in that respect? A: You could use a Visual Studio Database Project instead (included with VS 2005 Professional). It offers all of the nice project features of Visual Studio, including subfolders! But its not as easy to run sql scripts. You have to save the file, then right click and select Run Script. Your results will show up in the output window. Its not quite as easy as F5 in SSMS, and you don't get the tabular result option. There is a nice overview at http://blog.reamped.net/post/2008/05/Using-Database-Projects-for-Visual-Studio.aspx.
{ "pile_set_name": "StackExchange" }
Q: Sun CodeModel generic method Does anyone know to to generate the following generic method declaration using CodeModel: public <T> T getValue(Class<T> clazz){...} usage: ValueType value = getValue(ValueType.class); Seems not to be handled by the existing implmentation. I know I could handle the code as follows, but it requires a cast: public Object getValue(Class class){...} usage: ValueType value = (ValueType)getValue(ValueType.class); Obviously this is a bit messy because of the cast. A: Create the method with an Object return type, generify the method, then overwrite the return type. final JDefinedClass exampleClass = codeModel._class( "com.example.ExampleClass" ); final JMethod method = exampleClass.method( JMod.PUBLIC, Object.class, "getValue" ); final JTypeVar t = method.generify( "T" ); method.type( t ); method.param( codeModel.ref( Class.class ).narrow( t ), "type" ); method.body()._return(JExpr._null());
{ "pile_set_name": "StackExchange" }
Q: Appending and arc to svg element in d3.js I'm trying to append a svg and arc in it to html page. This is how I tried to do this: <script> var cityNames=["Челябинск","Область","Миасс","Копейск"]; var cityPercentage=["50%","30%","20%","10%"]; var width=300, height=300, radius=Math.min(width, height)/2; var p=Math.PI * 2; var cityDivision = d3.select("#cities") .append("svg") .attr("width", width) .attr("height", height) .attr("class","span4 cityDivision"); var group=cityDivision.append("g") .append("transform","translate(" + width / 2 + "," + height / 2 + ")"); var arc=d3.svg.arc() .innerRadius(radius-20) .outerRadius(radius) .starAngle(0) .endAngle(p); group.append("path") .attr("d",arc); </script> <div class="container"> <div class="row"> <div id="cities"> </div> <div class="span4" id="amount"> Численность </div> <div class="span4" id="LPU"> ЛПУ </div> </div> </div> But for some reason there is an svg element in div with only element in it. What's wrong? P.S. I use this tutorial A: The main problem is a simple typo -- starAngle instead of startAngle. Also, transform should be an attribute, not an element. Working demo here.
{ "pile_set_name": "StackExchange" }
Q: How can I prevent values from overlapping in a Python multiprocessing? I'm trying Python multiprocessing, and I want to use Lock to avoid overlapping variable 'es_id' values. According to theory and examples, when a process calls lock, 'es_id' can't overlap because another process can't access it, but, the results show that es_id often overlaps. How can the id values not overlap? Part of my code is: def saveDB(imgName, imgType, imgStar, imgPull, imgTag, lock): #lock=Lock() in main imgName=NameFormat(imgName) #name/subname > name:subname i=0 while i < len(imgName): lock.acquire() #since global es_id global es_id print "getIMG.pt:save information about %s"%(imgName[i]) cmd="curl -XPUT http://localhost:9200/kimhk/imgName/"+str(es_id)+" -d '{" +\ '"image_name":"'+imgName[i]+'", '+\ '"image_type":"'+imgType[i]+'", '+\ '"image_star":"'+imgStar[i]+'", '+\ '"image_pull":"'+imgPull[i]+'", '+\ '"image_Tag":"'+",".join(imgTag[i])+'"'+\ "}'" try: subprocess.call(cmd,shell=True) except subprocess.CalledProcessError as e: print e.output i+=1 es_id+=1 lock.release() ... #main if __name__ == "__main__": lock = Lock() exPg, proc_num=option() procs=[] pages=[ [] for i in range(proc_num)] i=1 #Use Multiprocessing to get HTML data quickly if proc_num >= exPg: #if page is less than proc_num, don't need to distribute the page to the process. while i<=exPg: page=i proc=Process(target=getExplore, args=(page,lock,)) procs.append(proc) proc.start() i+=1 else: while i<=exPg: #distribute the page to the process page=i index=(i-1)%proc_num #if proc_num=4 -> 0 1 2 3 pages[index].append(page) i+=1 i=0 while i<proc_num: proc=Process(target=getExplore, args=(pages[i],lock,))# procs.append(proc) proc.start() i+=1 for proc in procs: proc.join() execution result screen: result is the output of subprocess.call (cmd, shell = True). I use XPUT to add data to ElasticSearch, and es_id is the id of the data. I want these id to increase sequentially without overlap. (Because they will be overwritten by the previous data if they overlap) I know XPOST doesn't need to use a lock code because it automatically generates an ID, but I need to access all the data sequentially in the future (like reading one line of files). If you know how to access all the data sequentially after using XPOST, can you tell me? A: It looks like you are trying to access a global variable with a lock, but global variables are different instances between processes. What you need to use is a shared memory value. Here's a working example. It has been tested on Python 2.7 and 3.6: from __future__ import print_function import multiprocessing as mp def process(counter): # Increment the counter 3 times. # Hold the counter's lock for read/modify/write operations. # Keep holding it so the value doesn't change before printing, # and keep prints from multiple processes from trying to write # to a line at the same time. for _ in range(3): with counter.get_lock(): counter.value += 1 print(mp.current_process().name,counter.value) def main(): counter = mp.Value('i') # shared integer processes = [mp.Process(target=process,args=(counter,)) for i in range(3)] for p in processes: p.start() for p in processes: p.join() if __name__ == '__main__': main() Output: Process-2 1 Process-2 2 Process-1 3 Process-3 4 Process-2 5 Process-1 6 Process-3 7 Process-1 8 Process-3 9
{ "pile_set_name": "StackExchange" }
Q: How did the judge pay his barber? An Olympic judge rushes into the barbershop. "You need to help me!" he pleads. "I have to judge in 10 minutes, but I've been traveling so much I look just awful." The barber looks at him carefully. "Your hair is quite long. I'll need to cut it. And you'd look silly with a beard and such short hair. You're in luck, as I've just had a cancellation. Have a seat!" The barber does his work and goes to collect the payment. "Oh dear," said the judge. "I haven't any local currency to pay you with." Luckily, he and the barber were able to work out a deal. The judge, having fully paid the barber, leaves to go judge his match. On his lunch break, the barber was watching the Olympic games and sure enough there was the judge, attention gazed on the performers, looking for any mistakes he could find. Why was the judge looking for mistakes so intently? What was the deal between the barber and the judge? Clarifications: The judge is an honorable judge. There is no foul play. The judge and the barber will never interact again. The deal is fully concluded in a mutually acceptable way. Nothing illegal is transpiring. Currency is not involved in any way. A: Hmm, very open ended question. Only can come up with a fairly stupid guess: The barber shaved his shops name onto this judges head. Judge looked intently to ensure the back of his head was always to the TV viewers camera. A: As for the mistakes He was looking for mistakes in peoples haircuts and grooming. You never specify what type of mistakes the judge is looking for. And the payment He recommends the barber to the athletes A: The judge is judging a diving event. Competitive swimmers and divers shave their bodies to be more hydrodynamic. The judge lowers scores by looking more intently for mistakes, which makes contestants think they are performing poorly, and that they could do better getting shaved by the barber as a professional. By doing this equally to all competitors, the judge feels like his is keeping the integrity of the competition.
{ "pile_set_name": "StackExchange" }
Q: Three.js import Collada animation not working I've been trying to export a Collada animated model to three js. Here is the model: http://bayesianconspiracy.com/files/model.dae It is imported properly(I can see the model) but I can't get it to animate. I've been using the two Collada examples that come with Three js. I've tried just replacing the path with the path to my model but it doesn't work. I've also tried tweaking some stuff but to no avail. When the model is loaded I've checked the 'object.animations' object which seems to be loaded fine(can't tell for sure but there is lots of stuff in it). I've also tried the Three.js editor: http://threejs.org/editor/ which loads the model properly again but I can't play the animation : ( I am using Three JS r62 and Blender 2.68. Any help appreciated!! A: My first guess is that there are some errors in your file that disable animation. I have opened your model.dae file with blender andI have noticed at least 2 errors OMHO. They are in the following video : http://youtu.be/BGnVVpMNY4E . You therefore might work a bit more on your model and if you need a step by step tutorial to animate your collada model into a THREE.JS based webgl viewport, then you can check this tutorial : http://jiteshmulchandani.com/?p=122 As mentioned on this page: Get the latest plugin from http://opencollada.org/ and export the model using the following options checked : Normals Triangulate Enable export Sample animation Note : When exported using the Autodesk Collada format, it doesn’t play skeletal animations. The corresponding demo is right here : http://jiteshmulchandani.com/zombie-outbreak/ColladaModelTest.html (to control the model, use ASDW keys) Hope this helps
{ "pile_set_name": "StackExchange" }
Q: Unable to set autoCommitOffset to true using cloud kafka streams I am using spring-cloud-starter-stream-kafka - 1.3.3 and spring-cloud-stream with Spring Boot to connect to Kafka that comprise of typical Publisher Subscriber use case in which I want enable.auto.commit to be true. When service go up, I can see several Kafka properties (INFO logs) being printed on console that lists all applied properties. I see value of this property as false- enable.auto.commit= false, As shown belolw: auto.commit.interval.ms = 100 enable.auto.commit = false auto.offset.reset = earliest check.crcs = true client.id = consumer-2 connections.max.idle.ms = 540000 exclude.internal.topics = true fetch.max.bytes = 52428800 fetch.max.wait.ms = 500 fetch.min.bytes = 1 group.id = conn-dr-group heartbeat.interval.ms = 3000 I had read on Spring Doc that if we do not provide the property of auto commit, it is set true by default - https://docs.spring.io/autorepo/docs/spring-cloud-stream-binder-kafka-docs/1.1.0.M1/reference/htmlsingle/ However, The value still seems to appear false when I boot up the service. I tried providing following property in application.properties, but still it resolves to false. spring.cloud.stream.kafka.bindings.input.autoCommitOffset=true Does anyone know how can we get value of it true ? A: spring.cloud.stream.kafka.bindings.input.autoCommitOffset=true That is a different property; it tells the binder to commit the offset after the listener returns normally. This is more deterministic than having the client perform the commits on its own. The binder always resets enable.auto.commit; you can override it using the ...binder.configuration property, but it's not advised.
{ "pile_set_name": "StackExchange" }
Q: override css div display: none; Thanks for your time! The codes are very simple. I suppose it should display "This is CPU". But it didn't. Where am I wrong? Fiddle For people who cannot open Fiddle, here's the codes: HTML: <div id="tab1" class="active" ><p>This is CPU</p></div> <div id="tab2"><p>This is MEM</p></div> <div id="tab3"><p>This is Network IO Receive</p></div> <div id="tab4"><p>This is Network IO Send</p></div> CSS: #tab1, #tab2, #tab3, #tab4 { display: none; } .active { display: block; } By add !important it do works. But why if I changes all the ids to classes, it could work? e.g.: Fiddle A: The major thing to note here is the CSS priorities In this scenario the Rule provided using Id will have more priority over the class You need to use combination of your id and class to create a even more priority than just the id #tab1, #tab2, #tab3, #tab4 { display: none; } #tab1.active , #tab2.active , #tab3.active , #tab4.active { display: block; } You can also use partial selectors to reduce the code.. [id^=tab].active{ display: block; } Note : Do not use !important unless you have no other option left. In most of the cases the work can be done without using!importantat all.
{ "pile_set_name": "StackExchange" }
Q: Apache Camel message multiplexer integration pattern I am trying to determine the best way to combine message streams from two hornetq broker instances into a single stream for processing, using Apache Camel and Spring. This is essentially the opposite of the Camel reciepient list pattern; but instead of one to many I need many to one. One idea is to implement this functionality with the direct component: <?xml version="1.0" encoding="UTF-8"/> <beans xmlns="..." xmlns="..."> <!-- JMS Connection 1 --> <bean id="jndiTemplate1" class="org.springframework.jndi.JndiTemplate"> <property name="environment"> <props> ...Connection 1 Specific Information... </props> </property> </bean> <bean id="jmsTopicConnectionFactory1" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiTemplate"> <ref bean="jndiTemplate1"/> </property> <property name="jndiName"> <value>java:jms/RemoteConnectionFactory</value> </property> </bean> <bean id="jms1" class="org.apache.camel.component.jms.JmsComponent"> <property name="connectionFactory" ref="jmsTopicConnectionFactory1"/> </bean> <!-- JMS Connection 2 --> <bean id="jndiTemplate2" class="org.springframework.jndi.JndiTemplate"> <property name="environment"> <props> ...Connection 2 Specific Information... </props> </property> </bean> <bean id="jmsTopicConnectionFactory2" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiTemplate"> <ref bean="jndiTemplate2"/> </property> <property name="jndiName"> <value>java:jms/RemoteConnectionFactory</value> </property> </bean> <bean id="jms2" class="org.apache.camel.component.jms.JmsComponent"> <property name="connectionFactory" ref="jmsTopicConnectionFactory2"/> </bean> <!-- Camel route many to 1 using direct component --> <camelContext xmlns="http://camel.apache.org/schema/spring"> <route id="hornetQ_broker_1"> <from uri="jms1:topic:testTopic1"> <to uri="direct:process_message"> </route> <route id="hornetQ_broker_2"> <from uri="jms2:topic:testTopic2"> <to uri="direct:process_message"> </route> <route id="message_processor"> <from uri="direct:process_message"> <log message="message_processor received message"> </route> </camelContext> </beans> Question: Is the above approach recommended when a many->1 integration pattern is required? If multiple Apache Camel solutions exist, what are the key performance impacts of each approach? Runtime environment: HornetQ brokers are JBoss EAP6. Camel context deployed to FuseSource 4.4.1 Each entity exists on a seperate server/jvm. Notes: The hornetQ broker instances cannot be clustered. The hornetQ broker instances do not contain duplicate data. A: I think that your approach is valid for your scenario. However, maybe direct is not the component you need to use for this if you are running in different JVMs. There are different components for internal queues: Direct, Direct-VM, SEDA, VM, Disruptor... but I believe all of them are if you are running in the JVM (and some of the if you just running in the same CamelContext). For more info: How do the direct, event, seda and vm endpoints compare If you are going to have different CamelContexts across different JVM will need to use a different component.
{ "pile_set_name": "StackExchange" }
Q: Origin Destination matrix with Open Trip Planner scripting in Jython / Python I'm trying to write a Python script to build an Origin Destination matrix using Open Trip Planner (OTP) but I'm very new to Python and OTP. I am trying to use OTP scripting in Jython / Python to build an origin-destination matrix with travel times between pairs of locations. In short, the idea is to launch a Jython jar file to call the test.py python script but I'm struggling to get the the python script to do what I want. A light and simple reproducible example is provided here And here is the python Script I've tried. Python Script #!/usr/bin/jython from org.opentripplanner.scripting.api import * # Instantiate an OtpsEntryPoint otp = OtpsEntryPoint.fromArgs(['--graphs', 'C:/Users/rafa/Desktop/jython_portland', '--router', 'portland']) # Get the default router router = otp.getRouter('portland') # Create a default request for a given time req = otp.createRequest() req.setDateTime(2015, 9, 15, 10, 00, 00) req.setMaxTimeSec(1800) req.setModes('WALK,BUS,RAIL') # Read Points of Origin points = otp.loadCSVPopulation('points.csv', 'Y', 'X') # Read Points of Destination dests = otp.loadCSVPopulation('points.csv', 'Y', 'X') # Create a CSV output matrixCsv = otp.createCSVOutput() matrixCsv.setHeader([ 'Origin', 'Destination', 'min_time' ]) # Start Loop for origin in points: print "Processing: ", origin req.setOrigin(origin) spt = router.plan(req) if spt is None: continue # Evaluate the SPT for all points result = spt.eval(dests) # Find the time to other points if len(result) == 0: minTime = -1 else: minTime = min([ r.getTime() for r in result ]) # Add a new row of result in the CSV output matrixCsv.addRow([ origin.getStringData('GEOID'), r.getIndividual().getStringData('GEOID'), minTime ]) # Save the result matrixCsv.save('traveltime_matrix.csv') The output should look something like this: GEOID GEOID travel_time 1 1 0 1 2 7 1 3 6 2 1 10 2 2 0 2 3 12 3 1 5 3 2 10 3 3 0 ps. I've tried to create a new tag opentripplanner in this question but I don't have enough reputation for doing that. A: Laurent Grégoire has kindly answered the quesiton on Github, so I reproduce here his solution. This code works but still it would take a long time to compute large OD matrices (say more than 1 million pairs). Hence, any alternative answers that improve the speed/efficiency of the code would be welcomed! #!/usr/bin/jython from org.opentripplanner.scripting.api import OtpsEntryPoint # Instantiate an OtpsEntryPoint otp = OtpsEntryPoint.fromArgs(['--graphs', '.', '--router', 'portland']) # Start timing the code import time start_time = time.time() # Get the default router # Could also be called: router = otp.getRouter('paris') router = otp.getRouter('portland') # Create a default request for a given time req = otp.createRequest() req.setDateTime(2015, 9, 15, 10, 00, 00) req.setMaxTimeSec(7200) req.setModes('WALK,BUS,RAIL') # The file points.csv contains the columns GEOID, X and Y. points = otp.loadCSVPopulation('points.csv', 'Y', 'X') dests = otp.loadCSVPopulation('points.csv', 'Y', 'X') # Create a CSV output matrixCsv = otp.createCSVOutput() matrixCsv.setHeader([ 'Origin', 'Destination', 'Walk_distance', 'Travel_time' ]) # Start Loop for origin in points: print "Processing origin: ", origin req.setOrigin(origin) spt = router.plan(req) if spt is None: continue # Evaluate the SPT for all points result = spt.eval(dests) # Add a new row of result in the CSV output for r in result: matrixCsv.addRow([ origin.getStringData('GEOID'), r.getIndividual().getStringData('GEOID'), r.getWalkDistance() , r.getTime()]) # Save the result matrixCsv.save('traveltime_matrix.csv') # Stop timing the code print("Elapsed time was %g seconds" % (time.time() - start_time))
{ "pile_set_name": "StackExchange" }
Q: How to check if directory exist or not on passing as a parameter in python? I am trying to pass the directory as a parameter and checking its existence - def validatePath(DirectoryName): pathtodata="/temp/project/data/" if os.path.exists('pathtodata'DirectoryName): return True return False parser = argparse.ArgumentParser() parser.add_argument("DirectoryName", nargs='?', help="Input folder Name", type=str) args = parser.parse_args() myDir = args.DirectoryName validatePath(myDir) Error : Syntax Error in line os.path.exists('pathtodata'DirectoryName): A: In Python the way you combine paths is not 'pathtodata'DirectoryName but rather os.path.join(pathtodata, DirectoryName).
{ "pile_set_name": "StackExchange" }
Q: Are there known compounds of caesium with oxidation number >1? Given that the left neighbor of caesium, xenon, does have fluorides and oxides, it is not inconceivable that caesium can have oxides or fluorides with an oxidation number higher than 1. Are such compounds known and synthesized? Or, alternatively, are there computations that rule out such compounds as unstable? A: As noted in the answer to the other question, alkali metal can exist in higher oxidation state when bonded with polycylic multidendate ligands like cryptands etc. This is an excerpt from an eBook: The chemistry of group 1 elements have been dominated by +1 oxidation states. However, there have been indications that caesium might form higher oxidation species. Thus, electrochemical oxidation of $\ce{[CsL]PF6}$ L=18-crown-6 or cryptand-[222] gives evidence for $\ce{Cs^2+}$ and $\ce{Cs^3+}$. Compounds containing caesium in higher oxidation state is yet to be isolated. Also, compounds of form $\ce{CsF_n}$ is known to contain stoichiometric amount of caesium in higher oxidation state($\ce{Cs^2+,Cs^3+,Cs^4+,Cs^5+}$). Experimental calculations have confirmed the presence.(See here and here). Furthermore, it has also been observed by Moock and Seepelt, Angew, Chem. Intl. Ed. Engl. 28, 1676(1989) that $\ce{Cs+}$ can be oxidised in acetonitrile solution to $\ce{Cs^3+}$ at a potential of +3.0 V($\ce{E°}$). - (See this eBook)
{ "pile_set_name": "StackExchange" }
Q: How to eliminate Roxygen warning about "No name found..."? I'm calling roxygenize() with parameter use.Rd2 = TRUE. I have a file testcase.R where I create a simple S3 object using R.oo. Here's the contents of the file. There's nothing for roxygen to do here, and it should ignore the contents: library( R.oo ) setConstructorS3( "TestCase" , function() { extend( Object() , "TestCase", .parameters = list() , .validationData = list() ) } ) And here's the error: Error in parse.name(partitum) : (converted from warning) No name found for the following expression in E:/mypackage/R/te stcase.R line 1: `library( R.oo ) . . .' Calls: roxygenize ... <Anonymous> -> maybe.call -> do.call -> <Anonymous> -> par se.name How can I eliminate the warning? Per suggestions in other posts, I added the following as the first line, but it didn't work: #' @nord A: Upgrading to Roxygen2 eliminated the error.
{ "pile_set_name": "StackExchange" }
Q: Algorithm Checking Is it possible giving a well defined problem, to write an algorithm which takes in as input another algorithm and checks if that algorithm is correct.   If it isn't possible, I'm thinking of storing solutions to a large number of problem sizes, randomly selecting a smaller number of problem instances and seeing if the algorithm solves those particular problem cases. A: In theory, testing weather an algorithm terminates in a finite time is undecidable! This is the Halting Problem. Checking the correctness is harder. But in practice, you can try to test it. This book may help you: Introduction to Software Testing
{ "pile_set_name": "StackExchange" }
Q: Inserting PHP and XML into MYSQL I am using the below code to draw data from our service provider for LBS. What i am trying to do is also load this information that i receive into mysql. Using this code I am not getting any errors, and the location and map API's are working great but it is not placing the data drawn into mysql at all. <?php function parseXML($fstr,$tstr_start,$tstr_end) { if ( ! strstr($fstr,$tstr_start) || !strstr($fstr,$tstr_end) ){ return ; } $start = strpos($fstr,$tstr_start) + strlen($tstr_start); $stop = strpos($fstr,$tstr_end, $start); $length = $stop - $start; return trim(substr($fstr, $start, $length)); } define ("MAP_API_KEY","***"); define ("MAP_BASE_URL","http://maps.googleapis.com/maps/api/staticmap?"); $Data = $GLOBALS["HTTP_RAW_POST_DATA"]; //--- Get XML data into variables $DataAry['ResponseType'] = parseXML($Data,'Response Type="','"'); $DataAry['RefNo'] = parseXML($Data,'RefNo="','"'); $DataAry['SeqNo'] = parseXML($Data,'SeqNo="','"'); $DataAry['Network'] = parseXML($Data,'<NetworkID>','</NetworkID>'); $DataAry['Lat'] = (int) parseXML($Data,'<Lat>','</Lat>'); $DataAry['Lon'] = (int) parseXML($Data,'<Lon>','</Lon>'); $DataAry['Accuracy'] = parseXML($Data,'<Accuracy>','</Accuracy>'); $DataAry['DateTime'] = parseXML($Data,'<DateTime>','</DateTime>'); $DataAry["Lat"] = $DataAry['Lat']/1000000; $DataAry["Lon"] = $DataAry["Lon"]/1000000; $con = mysql_connect("localhost","****","****"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("****", $con); $sql="INSERT INTO trace (Lat, Lon, DateTime, RefNo) VALUES ('$_POST[Lat]','$_POST[Lon]','$_POST[DateTime]','$_POST[RefNo]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } // ---Create link to map $link = MAP_BASE_URL . "center={$DataAry['Lat']}, {$DataAry['Lon']}&zoom=15&size=500x500&key=" . MAP_API_KEY . "&sensor=true&markers= {$DataAry['Lat']},{$DataAry['Lon']}"; $handle = fopen("requests.php","c"); fwrite($handle, "<br/>Location Request @ ". date("Y-m-d H:i:s") . "<br/><textarea style='width:500px;height:200px' readonly>" . $GLOBALS["HTTP_RAW_POST_DATA"] . " </textarea><br/><img style='border:1px solid #000;width:500px;height:500px' src='$link'/><hr/>"); fclose ($handle); echo "done!"; ?> It does however throw it into the requests.php page as requested but i need to extract the info into msql A: The first problem is that there are no quotes around your string key indexes for your $_POST array. You might want to put !mysql_query($sql,$con) in a try-catch to see if you catch any errors then. Also the use of mysql_* functions in PHP is deprecated and should not be used anymore. Because you are using the mysql_* functions, you are also vulnerable to SQL-injections.
{ "pile_set_name": "StackExchange" }
Q: Connecting to SQL Server Analysis with a windows user How can you impersonate a windows user in a connection to an analysis server - using ADOMD.NET? Webserver is next to Analysis server, but they are not in a domain. The webservice running on the webserver needs to access the analysis server as a specific windows account. Is there something I can put in the connection string, or do I need to look into some kind of impersonation? A: Try using the Impersonator class at: http://www.codeplex.com/OlapPivotTableExtend/SourceControl/changeset/view/23587#288650 You call it by doing: using (new Impersonator(sUsername, sDomain, sPassword)) { AdomdConnection connCube = new AdomdConnection(sConnectionString); connCube.Open(); //etc } The original reference for this information is: http://social.msdn.microsoft.com/Forums/en-US/sqlanalysisservices/thread/b35ab490-9a47-4312-b9b1-c22df2348356 I don't want to take credit for someone elses information directly.
{ "pile_set_name": "StackExchange" }
Q: Closing a matplotlib figure with event handling occasionally causes "TypeError: isinstance()" For a project I needed to implement a tool that can intuitively adjust the contrast of an image. Eventually, I came up with a solution which you can find here. While this tool can certainly be improved on many levels, there is one particular thing that still irks me quite a bit. As I have pointed out in the other post, sometimes, when closing the window, I get the following error message: Exception ignored in: <function WeakMethod.__new__.<locals>._cb at 0x00000193A3D7C7B8> Traceback (most recent call last): File "C:\Users\mapf\Anaconda3\lib\weakref.py", line 58, in _cb File "C:\Users\mapf\Anaconda3\lib\site-packages\matplotlib\cbook\__init__.py", line 182, in _remove_proxy File "C:\Users\mapf\Anaconda3\lib\weakref.py", line 74, in __eq__ TypeError: isinstance() arg 2 must be a type or tuple of types I have simplified my program as much as I could so that you would still receive the error. Here is the code: import sys import matplotlib.pyplot as plt from matplotlib.backends.backend_qt5agg import \ FigureCanvasQTAgg as FigureCanvas from PyQt5.QtWidgets import QDialog, QApplication, QGridLayout class Figure: def __init__(self): self.fig, self.ax = plt.subplots() self.canvas = FigureCanvas(self.fig) self.canvas.setMaximumHeight(100) self.fig.canvas.mpl_connect('pick_event', self.on_pick_event) self.fig.canvas.mpl_connect( 'button_release_event', self.on_release_event ) self.fig.canvas.mpl_connect( 'button_press_event', self.on_button_press_event ) self.fig.canvas.mpl_connect( 'motion_notify_event', self.on_motion_event ) self.canvas.draw() def on_pick_event(self, _): # print('picked') pass def on_button_press_event(self, _): # print('pressed') pass def on_release_event(self, _): # print('released') pass def on_motion_event(self, _): # print('moved') pass class MainWindow(QDialog): def __init__(self): super().__init__() self.layout = QGridLayout(self) self.image = Figure() self.layout.addWidget(self.image.canvas, 1, 0) if __name__ == '__main__': app = QApplication(sys.argv) GUI = MainWindow() GUI.show() sys.exit(app.exec_()) Now, if I run the code and simply run my cursor over the figure (or click on it a couple of times) and immediately close the window afterwards by pressing the 'X'-button, I receive the error message about every other time. I have already pinpointed the cause to the event handling connections. I was able to reproduce the error whenever at least two of the connections are active. Can this have something to do with some kind of overlap in how the events are handled, and maybe the fact that you use the mouse to close the window? I really don't understand this. A: This turned out to be a bug and was solved.
{ "pile_set_name": "StackExchange" }
Q: ValidationError: User validation failed at MongooseError.ValidationError I am trying to create a simple node.js app with passport local authentication using mongoDb and express as a framework,but I'm having a problem Whenever I try to submit the data into database using registration form,after clicking submit it appears in node terminal immediately : here is how my user schema looks like: var mongoose = require('mongoose'); var bcrypt = require('bcrypt-nodejs'); // define the schema for our user model var userSchema = mongoose.Schema({ local : { name : String, username : String, mobile : Number, email : String, gender : String, password : String } }); // methods ====================== // generating a hash userSchema.methods.generateHash = function(password) { return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); }; // checking if password is valid userSchema.methods.validPassword = function(password) { return bcrypt.compareSync(password, this.local.password); }; // create the model for users and expose it to our app module.exports = mongoose.model('User', userSchema); and my router file : // process the signup form app.post('/signup', passport.authenticate('local-signup', { successRedirect : '/profile', // redirect to the secure profile section failureRedirect : '/signup', // redirect back to the signup page if there is an error failureFlash : true // allow flash messages })); passport configuration for sign up logic : passport.use('local-signup', new LocalStrategy({ nameField : 'name', usernameField : 'username', mobileField : 'mobile', emailField : 'email', genderField : 'gender', passwordField : 'password', passReqToCallback : true // allows us to pass back the entire request to the callback }, function(req, name, username, mobile, email, gender, password, done) { // asynchronous // User.findOne wont fire unless data is sent back process.nextTick(function() { // find a user whose email is the same as the forms email // we are checking to see if the user trying to login already exists User.findOne({ 'local.email' : email }, function(err, user) { // if there are any errors, return the error if (err) return done(err); // check to see if theres already a user with that email if (user) { return done(null, false, req.flash('signupMessage', 'That email is already taken.')); } else { // if there is no user with that email // create the user var newUser = new User(); // set the user's local credentials newUser.local.name = name; newUser.local.username = username; newUser.local.mobile = mobile; newUser.local.email = email; newUser.local.gender = gender; newUser.local.password = newUser.generateHash(password); // save the user newUser.save(function(err) { if (err) throw err; return done(null, newUser); }); } }); }); })); I am new to node.js as well as in mongoDb please help me out Thanks A: Reason: reason behind this error is invalid type to store in db. Like mobile is number type but if you are passing a value which can not be convert to number then it will give the same error. console.log(newUser); before saving the user and check the value you are passing in mobile field is convertible to Number as its data type is number in your schema. If mobile is "" or undefined or null i.e. not convertible to number then it will not work. Remove this key from object if it's value doesn't exists. Do not pass the undefined,null or "" or string(which can not be convert to number).
{ "pile_set_name": "StackExchange" }
Q: How to temporarily replace one primitive type with another when compiling to different targets? How to easily/quickly replace float's for doubles (for example) for compiling to two different targets using these two particular choices of primitive types? Discussion: I have a large amount of c# code under development that I need to compile to alternatively use float, double or decimals depending on the use case of the target assembly. Using something like “class MYNumber : Double” so that it is only necessary to change one line of code does not work as Double is sealed, and obviously there is no #define in C#. Peppering the code with #if #else statements is also not an option, there is just too much supporting Math operators/related code using these particular primitive types. I am at a loss on how to do this apparently simple task, thanks! Edit: Just a quick comment in relation to boxing mentioned in Kyles reply: Unfortunately I need to avoid boxing, mainly since float's are being chosen when maximum speed is required, and decimals when maximum accuracy is the priority (and taking the 20x+ performance hit is acceptable). Boxing would probably rules out decimals as a valid choice and defeat the purpose somewhat. Edit2: For reference, those suggesting generics as a possible answer to this question note that there are many issues which count generics out (at least for our needs). For an overview and further references see Using generics for calculations A: The best way to do this would be using #if as Andrew stated above. However, an interesting idea to think about would be something like this: #if USE_FLOAT using Numeric = System.Single; #endif #if USE_DOUBLE using Numeric = System.Double; #endif #if USE_DECIMAL using Numeric = System.Decimal; #endif public class SomeClass { public Numeric MyValue{get;set;} } EDIT: I still really like this solution, it allows you to do some other really cool things such as: Numeric.Parse(); Numeric.TryParse(); Which will work for all three types
{ "pile_set_name": "StackExchange" }
Q: How do I add resources to my AutoIt exe file? I want to include a few txt files to my AutoIT application. #AutoIt3Wrapper_Res_Field=#AutoIt3Wrapper_icon|C:\Scripts\AutoIt\HelpDeskIT\images\helpdesk_icon.ico #AutoIt3Wrapper_Res_File_Add=C:\Scripts\AutoIt\HelpDeskIT\Instructions.txt #AutoIt3Wrapper_Res_File_Add=C:\Scripts\AutoIt\HelpDeskIT\reportaproblem.txt but it's not being added to my exe file. (when I launch the app it can't find the files) A: From the SciTE4AutoIt3 help (under Extra Utilities --> AutoIt3Wrapper)... Adding a file: Files are stored in the RT_RCDATA section and are usually stored byte for byte. If the section value is set to -10 (RT_RCDATA is internally evaluated as 10) then the file is compressed before being added: #AutoIt3Wrapper_Res_File_Add=file_name, RT_RCDATA : UNCOMPRESSED #AutoIt3Wrapper_Res_File_Add=file_name, 10 ; UNCOMPRESSED #AutoIt3Wrapper_Res_File_Add=file_name, -10 ; COMPRESSED When the file is required it can be extracted using this code. Set the $isCompressed parameter to match the Res_File_Add directive: #include <WinAPIRes.au3> #include <WinAPIInternals.au3> Func _FileInstallFromResource($sResName, $sDest, $isCompressed = False, $iUncompressedSize = Default) Local $bBytes = _GetResourceAsBytes($sResName, $isCompressed, $iUncompressedSize) If @error Then Return SetError(@error, 0, 0) FileDelete($sDest) FileWrite($sDest, $bBytes) EndFunc Func _GetResourceAsBytes($sResName, $isCompressed = False, $iUncompressedSize = Default) Local $hMod = _WinAPI_GetModuleHandle(Null) Local $hRes = _WinAPI_FindResource($hMod, 10, $sResName) If @error Or Not $hRes Then Return SetError(1, 0, 0) Local $dSize = _WinAPI_SizeOfResource($hMod, $hRes) If @error Or Not $dSize Then Return SetError(2, 0, 0) Local $hLoad = _WinAPI_LoadResource($hMod, $hRes) If @error Or Not $hLoad Then Return SetError(3, 0, 0) Local $pData = _WinAPI_LockResource($hLoad) If @error Or Not $pData Then Return SetError(4, 0, 0) Local $tBuffer = DllStructCreate("byte[" & $dSize & "]") _WinAPI_MoveMemory(DllStructGetPtr($tBuffer), $pData, $dSize) If $isCompressed Then Local $oBuffer _WinAPI_LZNTDecompress($tBuffer, $oBuffer, $iUncompressedSize) If @error Then Return SetError(5, 0, 0) $tBuffer = $oBuffer EndIf Return DllStructGetData($tBuffer, 1) EndFunc Func _WinAPI_LZNTDecompress(ByRef $tInput, ByRef $tOutput, $iUncompressedSize = Default) ; if no uncompressed size given, use 16x the input buffer If $iUncompressedSize = Default Then $iUncompressedSize = 16 * DllStructGetSize($tInput) Local $tBuffer, $ret $tOutput = 0 $tBuffer = DllStructCreate("byte[" & $iUncompressedSize & "]") If @error Then Return SetError(1, 0, 0) $ret = DllCall("ntdll.dll", "long", "RtlDecompressBuffer", "ushort", 2, "struct*", $tBuffer, "ulong", $iUncompressedSize, "struct*", $tInput, "ulong", DllStructGetSize($tInput), "ulong*", 0) If @error Then Return SetError(2, 0, 0) If $ret[0] Then Return SetError(3, $ret[0], 0) $tOutput = DllStructCreate("byte[" & $ret[6] & "]") If Not _WinAPI_MoveMemory(DllStructGetPtr($tOutput), DllStructGetPtr($tBuffer), $ret[6]) Then $tOutput = 0 Return SetError(4, 0, 0) EndIf Return $ret[6] EndFunc
{ "pile_set_name": "StackExchange" }
Q: Referencing figure not working in Gummi Ok so I'm trying to reference a couple of images from my document. The code is: \begin{figure}[htp] \centering \includegraphics[scale=0.70]{grafico2.jpg} \caption{Aceleramiento con las 4 primeras imágenes} \label{grafico2} \end{figure} \begin{figure}[htp] \centering \includegraphics[scale=0.75]{grafico1.jpg} \caption{Aceleramiento real del método} \label{grafico1} \end{figure} In the text I'm referencing the images like this \ref{figure:grafico2} \ref{figure:grafico1} But all I get is this ??. I tried putting the label after the caption and even inside the caption. I also tried recompiling the document several times with the Gummi compile option and even cleaning up build files before compiling but it doesn't work. The strange thing is that I'm referencing some tables before and they are working but not my figures. Any idea why? A: You need to use \ref{grafico1}; the string used in the argument of \ref has to be the exact same string used in \label, so if you say \label{grafico1} you have to use \ref{grafico1}. Process the document twice to get the cross-reference number.
{ "pile_set_name": "StackExchange" }