text
stringlengths
64
89.7k
meta
dict
Q: extracting domain from host name variable without prefix or suffix with sed I have been mucking around with this for a couple of hours and cant seem to get it working. If I have www or ftp.somedomain.net.nz or just somedomain.com and I want to extract just the somedomain from the pattern to set as a variable by echoing the hostname to sed how would I go about it? For Example: var="echo $HOSTNAME | sed 's/someregex to fit all$//'" A: Do you really need to use sed? HOSTNAME="${HOSTNAME#*.}" HOSTNAME="${HOSTNAME%%.*}" Note that this, and some other solutions, won't get along with something like www.news.google.com but if you test for things like that you could do: HOSTNAME="${HOSTNAME#*.}" HOSTNAME="${HOSTNAME#*.}" HOSTNAME="${HOSTNAME%%.*}" What works depends only how nicely formed your input is. A: If you know the prefixes you can try (either "ftp.", "www." or nothing): var=$(sed -E 's/^((ftp|www)\.)?([^.]*)\..*/\3/' <<< "$HOSTNAME") Using sed ... <<< $VARIABLE is preferred to echo $VARIABLE | sed ...
{ "pile_set_name": "StackExchange" }
Q: Imagine Whether Or Not I have this sentence using "think": I was thinking whether or not he has money that I can borrow. is good English. If I replace "think" with "imagine": I was imagining whether or not he has money that I can borrow. Would this be okay English? A: Neither think nor imagine is used this way with whether. To think X is to hold it as a strong idea or opinion that X is true or happened, and to imagine it is to form and subsequently hold such an idea or opinion. These do not suit well with whether, which implies uncertainty between two or more ideas or opinions. Ordinarily we wonder whether X is true, to indicate that we raise the question in our minds; or if we ponder the question deeply we consider or think about whether it is true.
{ "pile_set_name": "StackExchange" }
Q: Was ist der Unterschied zwischen Gouvernante und Kindermädchen? When I was young, my parents put me in the care of a German-American woman. That's why I'm here. (Deshalb bin ich hier.) How is such a woman referred to, as a "governess," or "nanny?" Or some thing else? What is the difference? (Or isn't there any?) Wie nennt man eine solche Frau: Gouvernante, Kindermädchen oder anders? Was ist der Unterschied, oder gibt es keinen? A: Der gängige deutsche Begriff ist definitiv Kindermädchen oder, wenn es um nur um Tagesbetreuung geht, während die Eltern arbeiten sind, modern Tagesmutter. Kindermädchen und Gouvernante sind Angestellte im Haushalt der Eltern; die Tagesmutter arbeitet in ihrem eigenen Haushalt, die Kinder werden zu ihr gebracht. Gouvernante ist veraltet und wird im Alltag nicht mehr verwendet. Aus Wikipedia: Gouvernante - eine veraltete Bezeichnung für Hauslehrerin oder Erzieherin. Dieser Beruf stellte über lange Zeit für Frauen eine der wenigen Möglichkeiten dar, einen standesgemäßen Beruf auszuüben. Er wurde vor allem von Frauen aus der gebildeten Mittelschicht ergriffen, die nicht verheiratet waren. Für kurzzeitige Betreuung ohne erzieherische Aufgaben (z.B. Beaufsichtigung des Kindes für einen Abend) verwenden wir den Anglizismus Babysitter. Kindermädchen, Tagesmutter und (früher) Gouvernante waren demgegenüber feste Bezugspersonen für das Kind und für die Steuerung der Entwicklung des Kindes mitverantwortlich. Junge Frauen oder Männer - meistens Frauen - die für einen längeren Zeitraum (z.B. ein halbes oder ganzes Jahr) ins Ausland gehen, um in einer Familie Kinder zu betreuuen und dabei die fremde Sprache und Kultur kennenzulernen, werden Au-Pair genannt. A: There was a clear difference. The Gouvernante was always a teacher. She nearly always taught manners and French and often many other things like sketch, stitching and music. This paper by Mrs. Gresshöner cites Die Gouvernante by Hardach-Pinke as follows: ,,Mütter und weibliche Verwandte konnten zwar in der Regel kostenlos Unterricht in Lesen, Religion und Handarbeiten erteilen, aber nur selten in Fremdsprachen, Musik, Geschichte und Geographie". From the memoirs of the Bronte sisters you will see how difficult it was for them to get jobs as governances without a good knowledge of French. In fact, mastery of the French language was so essential, that at one point the word Französin came to mean governess. Gresshöner explains: Seit dem 18. Jahrhundert wurden deutsche Gouvernanten häufig ,,Erzieherinnen" genannt - zu polemischen Zwecken. Sollten doch die als tüchtig bekannten einheimischen Gouvernanten die als oberflächlich verrufenen Französinnen verdrängen. 1789 arbeiteten in Deutschland so viele französische Frauen als Gouvernanten, dass die eigentliche Nationalitätenbezeichnung ,,Französin" als Berufsbezeichnung genutzt wurde. Bis ins frühe 19. Jahrhundert hielt die starke Nachfrage nach französischen Erzieherinnen an, die bis dahin ein wahres Monopol im deutschen Erziehungswesen eingenommen hatten. There were also regional differences. In Germany, standardised training was offered, when British families still regarded class background and skills as solely important. Wikipedia cites Die Gouvernante by Hardach-Pinke on the claim that: In Großbritannien nahmen erst 1848 das Queen’s College und das Bedford College ihre Arbeit als Ausbildungsstätten für Gouvernanten auf. For Germany, on the other hand, referencing the same work, it claims: In Deutschland gab es bereits gegen Ende des 18. Jahrhunderts Forderungen nach der Einrichtung von Ausbildungsstätten von Erzieherinnen. Zu den Frauen, die sich unter anderem dafür einsetzten, zählen Amalia Holst, Betty Gleim und Elisabeth Bernhardi. In some countries there existed different types of governances, like the preparatory governess that taught writing to little boys and girls. I am not aware of such distinctions in Germany. Some people preferred to use Gouvernante for the educators of girls and Hauslehrer for the teachers of males. Wikipedia provides the following details based, again, on Hardach-Pinke: August Hermann Niemeyer beschrieb [...] 1796 in seinem Ratgeber für Hofmeister, dass die Gouvernante für die Erziehung der Mädchen zuständig sei, der Hauslehrer dagegen für die der Jungen. Beide können stundenweise die Zöglinge des anderen unterrichten. Beschäftigt ein Haushalt nur eine Gouvernante, dann übernahm sie die Erziehung der Jungen bis etwa zu deren achtem Lebensjahr. The Kindermädchen had a more general role. She frequently did housework and often didn't speak French. Kindermädchen who did where known as Bonne in Germany. However, the following citation from The Victorian governess by K. Hughes suggests there might have been some overlap in poorer British families: Those widowers who had failed to marry again, and who had no female relative living nearby, were obliged to pay a woman to live en Familie to carry out the duties formerly performed by their wives. It was these men, […] who use the governess much as single women had been used for centuries – as a way of plugging a gap in the household’s available personell. In these modest homes the governess was not simply a teacher, but a housekeeper, stepmother and even parlourmaid rolled into one. Note, however, how even this text contrasts the situation with the traditional role as a teacher! While many Gouvernanten lived with the family and participated at least in those activities their trainees attended, there was also the Tagesgouvernante, who did not live with the family.
{ "pile_set_name": "StackExchange" }
Q: pandas series,isnull() is not working inside list comprehension for the following simple code: drop_cols = [col for col in train.columns if col[0] == 'V' and train[col].isnulll().sum()/len(train) > 0.76] drop_cols I get this error: AttributeError Traceback (most recent call last) in () ----> 1 drop_cols = [col for col in train.columns if col[0] == 'V' and train[col].isnulll().sum()/len(train) > 0.76] 2 drop_cols in (.0) ----> 1 drop_cols = [col for col in train.columns if col[0] == 'V' and train[col].isnulll().sum()/len(train) > 0.76] 2 drop_cols C:\Anaconda3\lib\site-packages\pandas\core\generic.py in getattr(self, name) 5065 if self._info_axis._can_hold_identifiers_and_holds_name(name): 5066 return self[name] -> 5067 return object.getattribute(self, name) 5068 5069 def setattr(self, name, value): AttributeError: 'Series' object has no attribute 'isnulll' isnull() is working elsewhere. What is the cause and fix for this? A: Unfortunately I don't have more than 50 rep points to add a comment so need to reply here. You just have a typo in a code train[col].isnulll().sum()/len(train) (triple lll) drop_cols = [col for col in train.columns if col[0] == 'V' and train[col].isnull().sum()/len(train) > 0.76]
{ "pile_set_name": "StackExchange" }
Q: remove stop words without stemming in postgresql I want to remove the stop words from my data but I do not want to stem the words since the exact words matters to me. I used this query. SELECT to_tsvector('english',colName)from tblName order by lower asc; Is there any way that I can remove stopWords without stemming the words? thanks A: Create your own text search dictionary and configuration: CREATE TEXT SEARCH DICTIONARY simple_english (TEMPLATE = pg_catalog.simple, STOPWORDS = english); CREATE TEXT SEARCH CONFIGURATION simple_english (copy = english); ALTER TEXT SEARCH CONFIGURATION simple_english ALTER MAPPING FOR asciihword, asciiword, hword, hword_asciipart, hword_part, word WITH simple_english; It works like this: SELECT to_tsvector('simple_english', 'many an ox eats the houses'); ┌─────────────────────────────────────┐ │ to_tsvector │ ├─────────────────────────────────────┤ │ 'eats':4 'houses':5 'many':1 'ox':3 │ └─────────────────────────────────────┘ (1 row) You can set the parameter default_text_search_config to simple_english to make it your default text search configuration.
{ "pile_set_name": "StackExchange" }
Q: Change geom_bar width default to another default What I want to do I currently have a custom theme for my plots, and I want to have on top of that some predefined parameters for all type of plots. My first focus is on bar charts, where I want to change the default width. The default width of geom_bar in ggplot2 is "By default, set to 90% of the resolution of the data." (http://ggplot2.tidyverse.org/reference/geom_bar.html). I'd like to change that default to 75%. To be clear, I am not interested in changing it like this: geom_bar(stat='identity', width=0.75) Because that would mean I have to specify it everytime I create a bar chart. I want it to be the new default. What I tried so far I tried to change the width default using this: update_geom_defaults("bar", list(width=0.75)) But then I get an error message: Error: Aesthetics must be either length 1 or the same as the data (964): width. I'm thinking this might be due to the fact that the width is calculated based on the resolution of the data, which is not yet there at the moment I call update_geom_defaults Plus, I also realised that width is not part of the default aes of the bars : GeomBar$default_aes * colour -> NA * fill -> "grey35" * size -> 0.5 * linetype -> 1 * alpha -> NA My questions are: Where is that 90% default set? Can I change it in any way? If not, is there another way to pass a predefined set of parameters to all the geom_* functions? Thanks ! A: The default is defined in GeomBar: GeomBar <- ggproto("GeomBar", GeomRect, required_aes = c("x", "y"), setup_data = function(data, params) { data$width <- data$width %||% params$width %||% (resolution(data$x, FALSE) * 0.9) ## <- right here transform(data, ymin = pmin(y, 0), ymax = pmax(y, 0), xmin = x - width / 2, xmax = x + width / 2, width = NULL ) }, draw_panel = function(self, data, panel_params, coord, width = NULL) { # Hack to ensure that width is detected as a parameter ggproto_parent(GeomRect, self)$draw_panel(data, panel_params, coord) } ) The marked line uses %||%, which is used to set a default in the event params$width is NULL (which is the default in geom_bar, NULL means "set it to something reasonable for me"). There is no nice way like update_geom_defaults to change this. What you can do, is make your own geom_bar like this: geom_bar75 <- function (..., width = 0.75) { geom_bar(..., width = width) } This will work just fine in most cases, i.e. with a discrete x-axis (because the resolution is then 1). For more complicated cases you may need to adjust, or redefine GeomBar itself. ggplot(mpg, aes(class)) + geom_bar() ggplot(mpg, aes(class)) + geom_bar75()
{ "pile_set_name": "StackExchange" }
Q: JavaFX - load FXML-file without FXLoader I am experementing with the "new" JavaFX and it worked very well. Now I am at a point which is incomprehensible for me. I have a Controller for my View and I want to load my Controller from a main-method so the controller can load a view or do whatever it likes. My problem ist, that I have to load my FXML-File with the FXMLLoader.load() method. The FXMLLoader himselfe loads the controller. So in fact, with my method I will load the controller two times: I load the controller with XController xcontroller = new XController(); and inside that controller I load te view with the FXMLLoader.load() which will load the controller again. do I have to use FXMLLoader or can I let my controller load the view with an other method? edit I want to use the Presentation-Abstraction-Control (PAC) Pattern (variation of MVC), that's why I think it's importand to let the controller load the View. the main class public class Main extends Application { Override public void start(Stage primaryStage) { LoginController loginController = null; try { loginController = new LoginController(); loginController.loadSceneInto(primaryStage); primaryStage.show(); } ....... public static void main(String[] args) { launch(args); } } the controller public class LoginController { ..... public void loadSceneInto(Stage stage) throws IOException { this.stage = stage; Scene scene = null; Pane root = null; try { root = FXMLLoader.load( getClass().getResource( this.initialView.getPath() ) ); scene = new Scene(root, initialWidth, initialHeight); this.stage.setTitle(this.stageTitle); this.stage.setScene(scene); this.centralizeStage(); } ..... } } A: If I understand correctly, instead of root = FXMLLoader.load( getClass().getResource( this.initialView.getPath() ) ); Just do FXMLLoader loader = new FXMLLoader( getClass().getResource(this.initialView.getPath()); ); loader.setController(this); root = loader.load(); You will need to remove the fx:controller attribute from the FXML file for this to work.
{ "pile_set_name": "StackExchange" }
Q: Android: java.lang.NoClassDefFoundError after importing jar. Wrong jar? After I've imported jar file into Android project and ran it, I get java.lang.NoClassDefFoundError At first I thought that I'm doing something wrong while importing it, but then I tryed to import jar that I've from some online class and it worked! So here is my question: Is there any specific way of creating jar files for Android project? I've to point out that first jar is created from Java class that I wrote some time ago. This jar works without problems in another java app. The jar was created using Eclipse Kepler. Thanks for your help. A: The solution shoved up to be pretty simple. Currently I'm using Java 1.7 to create my jar files, but Android accepts only jars that were created with Java 1.6. So the problem is caused probably by some incompatibility in bytecode and therefore you need to force compiler to use Java 1.6. If you're using Eclipse, go to Project properties > Java compiler and select Compiler compliance level: 1.6 Save changes and rebuild your project. You're ready to export "working" jar :)
{ "pile_set_name": "StackExchange" }
Q: Paperclip file field not working sometimes I am developing a Rails application which uses Paperclip to save a picture in a model. In order to save this picture, I have a form_for which use a file input to save the picture. I haven't had any problem uploading the picture but sometimes it's not working. Most of time I receive a parameter like this: "picture"=>#<ActionDispatch::Http::UploadedFile:0x000000061faeb8 @original_filename="sample8.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"service[picture]\"; filename=\"sample.jpg\"\r\nContent-Type: image/jpeg\r\n", @tempfile=#<File:/tmp/RackMultipart20141026-3030-s39mpm>>, With this type of parameters I get to upload the picture. However, sometimes I receive a parameter like this: "picture" => "sample.jpg", so I get the following error: No handler found for "sample.jpg". I have been surfing on Internet trying to find a similar question but I have not found anything. Does anyone know why this is happening? This are the main files that I have use: = form_for service, url: service_path( service ), html: { method: :put } do |f| = file_field_tag :picture, value: service.picture, id: "selected_file_service_#{ service.id }", class: 'selected_file_service', size: '24', name: "service[picture]", rel: service.id %input#browseButton.upload_picture.service_upload.service_picture_upload{ type: "button", value: I18n.t( 'abadi.actions.upload_picture' ) } A: Finally I found the solution. I need to use multipart: true in the form in the html parameter.
{ "pile_set_name": "StackExchange" }
Q: append tuples to array in groups python I'm trying to append tuples to my array in groups. The number of groups or the number of tuples in each group is unknown. I'm aware there should be a very simple answer for this, but my mind is grasped on swift, which takes care of this issue for me. This is my issue, I need to be able to do this: array = [] array[0].append([1, 2]) # error because there isn't a '0' index array[0].append([7, 2]) array[0].append([89, -5]) array[1].append([2, 3]) so I don't get the wrong kind of responses of why I'm not doing it another way I made a simple program to illustrate the point of why I need it to work like this. def get_data(index, array): # loop for an un-determined number of times, calculates differently depending on the index one_or_more = 4 for i in range(0, one_or_more): # do some calculations depending on index, which should differ for each loop data1 = index * 3 + i data2 = index * 4 + i array.append([data1, data2]) def main(): array = [] array_index = 0 some_num = "110, 121, 122, 123, 124, 125, 130, 131, 323, 324, 325, 326, 340, 341, 342, 343".strip().split(", ") for i in some_num: get_data(int(i), array[array_index]) # error here with 'array[array_index]', because I can't index array with '0' because it's not initialized yet array_index += 1 if __name__ == "__main__":main() A: The value at a given index is being over written. So, an array is not a suitable data structure for your task. I would use a defaultdict. from collections import defaultdict key_lists = defaultdict(list) key_lists[0].append([1,2]) key_lists[0].append([89, -5]) key_lists[1].append([2, 3]) print(key_lists) print(key_lists[0]) one_or_more = 4 for i in range(0, one_or_more): data1 = index * 3 + i data2 = index * 4 + i key_lists[i].append([data1, data2]
{ "pile_set_name": "StackExchange" }
Q: Wasing the saying of speaking the what? At one point, the crew starts speaking in eastern street slang (known as High Imperial in later Mistborn eras) to annoy Breeze. Aside from Dockson who is speaking gibberish, do we know what they are saying? Here is the conversation. I have emphasised the eastern street slang: Spook rushed over and fetched Breeze a cup of wine. “He’s such a fine lad,” Breeze noted, accepting the drink. “I barely even have to nudge him Allomantically. If only the rest of you ruffians were so accommodating.” Spook frowned. “Niceing the not on the playing without.” “I have no idea what you just said, child,” Breeze said. “So I’m simply going to pretend it was coherent, then move on.” Kelsier rolled his eyes. “Losing the stress on the nip,” he said. “Notting without the needing of care.” “Riding the rile of the rids to the right,” Spook said with a nod. “What are you two babbling about?” Breeze said testily. “Wasing the was of brightness,” Spook said. “Nip the having of wishing of this.” “Ever wasing the doing of this,” Kelsier agreed. “Ever wasing the wish of having the have,” Ham added with a smile. “Brighting the wish of wasing the not.” Breeze turned to Dockson with exasperation. “I believe our companions have finally lost their minds, dear friend.” Dockson shrugged. Then, with a perfectly straight face, he said, “Wasing not of wasing is.” Breeze sat, dumbfounded, and the room burst into laughter. Breeze rolled his eyes indignantly, shaking his head and muttering about the crew’s gross childishness. Mistborn: The Final Empire - Chapter 24 A: Sanderson posted a large number of annotations and musings for the original Mistborn trilogy on his website. On this segment he says the following: If you hate Spook’s dialect, I apologize for this chapter. This is the place in the book where I spent the most time on it. I really like some of the phrases here–I tried to make the dialect focus on rhythm and sounds, making it alliterative and interesting simply to say out-loud. In case you need it, here’s a loose translation of the exchange in this chapter: Spook: “It’s not nice to play with people like that.” Kelsier: “Oh, don’t worry about what he does to you. He’s not worth your concern.” Spook: “You’re probably right.” Breeze: “What are you two babbling about?” Spook: “He wants to be clever. He pushes people around because he wants to prove that he is clever.” Kelsier “He’s always been like that.” Ham “He’s insecure. I think he worries that he’s really not that clever.”
{ "pile_set_name": "StackExchange" }
Q: SPI signal showing up on other pins of ATmega1284P microcontroller? I'm using an Atmel ATmega1284P MCU (40-pin DIP) for a project and noticed some low frequency spikes on the ADC0 pin (pin 40). After some troubleshooting I discovered that the spikes were perfectly synchronized with the SPI communication on pins 6 & 8. I was able to replicate the issue using the following minimal circuit: simulate this circuit – Schematic created using CircuitLab And the minimal code: #include <SPI.h> void setup() { SPI.begin(); } void loop() { SPI.transfer(B00000000); delay(61); } Monitoring pins 8 & 40 using an oscilloscope I can see that the SCK is correctly jumping to 5V every 61ms, but what is weird is that I see a roughly 400mV spike on the ADC0 line. Here's a screen grab from my scope, the ADC0 probe is in yellow and the SCK in blue: For reference, here's the pinout for the 1284 DIP: I'm really not sure what is going on here, but it seems like some sort of grounding issue. I've tried adding decoupling caps between pins 10 & 11, as well as pins 30 & 31, but it made no difference. Any ideas on how to eliminate this spike on the other MCU pins? Shot of the Vcc trace with 22uF electrolytic decoupling caps near both Vcc & AVcc: A: Pin 40 is an input i.e. it is relatively high impedance (compared to an output or a power supply line). That's the first important thing to note. Next you connect your o-scope probe to it and now you have basically a high impedance pin connected to what could be described as a medium length antenna. Is it any surprise that something might be seen? You might also find that if you hold the scope probe close by in several areas, fast transients on the SCK line also couple to the probe. General layout of breadboard could easily cause the spikes to appear (to a lesser extent) on any other pins. If it's on a PCB with a decent earthplane and the scope earth wire is connected to the closet 0V pin you may still see a little spike - this would be due to the scope probe acting as a loop antenna.
{ "pile_set_name": "StackExchange" }
Q: How to print a list in Python "nicely" In PHP, I can do this: echo '<pre>' print_r($array); echo '</pre>' In Python, I currently just do this: print the_list However, this will cause a big jumbo of data. Is there any way to print it nicely into a readable tree? (with indents)? A: from pprint import pprint pprint(the_list) A: A quick hack while debugging that works without having to import pprint would be to join the list on '\n'. >>> lst = ['foo', 'bar', 'spam', 'egg'] >>> print '\n'.join(lst) foo bar spam egg A: Simply by "unpacking" the list in the print function argument and using a newline (\n) as separator. print(*lst, sep='\n') lst = ['foo', 'bar', 'spam', 'egg'] print(*lst, sep='\n') foo bar spam egg
{ "pile_set_name": "StackExchange" }
Q: How to convert JSON to a hash, search for and change a value I'm trying to process a JSON file: { "features": { "additional-options": true }, "values": { "lo-value": 34, "hi-value": 554 }, "persons": [ { "name": "john", "member": true, "current": false, "sponsor": "pete", "profile": "", "credits": ["04"], "linked": ["philip","guy"], "maptools": ["crossfit","soccer","running"] }, { "name": "mary", "member": true, "current": false, "sponsor": "judy", "profile": "", "credits": ["all"], "activities": ["swimming","cycling","running"] } ], "data_map": [1122,3234] } I would like to be able to: Update a value on a key value pair Delete both the key/value Delete or insert a value that's an array I have tried so many thing to get this right. My simplified code idea is: require 'json' hash = JSON.parse(File.read('test.json')) # Add key & value or change existing one def change_key(hash, key, value) keys = key.strip(".") hash[*keys] = value end def add_to_array(hash, key, val) keys = key.strip(".") hash[*keys] = locate_arr(hash, key).insert(val) end # Delete a key and it's value def del_key(hash, key) keys = key.strip(".") hash[*keys].delete[-1] end def del_from_array(hash, key, val) keys = key.strip(".") hash[*keys] = locate_arr(hash, key).delete[-1] end f = File.write('test.json') ; f.puts JSON.pretty_generate(hash) change_key(hash, "features.additional-options", false) del_from_array(hash, "persons.name=mary.activities", "cycling") add_to_array(hash, "persons.name=mary.activities", "hockey") del_key(hash, "data_map") del_key(hash, persons.name=john.profile) del_key(hash, persons.name=mary.credits) The resulting JSON should be: { "features": { "additional-options": false }, "values": { "lo-value": 34, "hi-value": 554 }, "persons": [ { "name": "john", "member": true, "current": false, "sponsor": "pete", "credits": ["04"], "linked": ["philip","guy"], "maptools": ["crossfit","soccer","running"] }, { "name": "mary", "member": true, "current": false, "sponsor": "judy", "profile": "", "activities": ["swimming", "running","hockey"] } ] } I'm not sure how to work with JSON that is structured like this. A: I understand your JSON may look like this: "{\"features\":{\"additional-options\":true},\"values\":{\"lo-value\":34,\"hi-value\":554},\"persons\":[{\"name\":\"john\",\"member\":true,\"current\":false,\"sponsor\":\"pete\",\"profile\":\"\",\"credits\":[\"04\"],\"linked\":[\"philip\",\"guy\"],\"maptools\":[\"crossfit\",\"soccer\",\"running\"]},{\"name\":\"mary\",\"member\":true,\"current\":false,\"sponsor\":\"judy\",\"profile\":\"\",\"credits\":[\"all\"],\"activities\":[\"swimming\",\"cycling\",\"running\"]}],\"data_map\":[1122,3234]}" I suggest using an OpenStruct to organize your data: your_struct_name = JSON.parse(yourJson, object_class: OpenStruct) Then you get all the things you want. For the operations you show: #change_key(hash, "features.additional-options", false) your_struct_name.features['additional-options'] = false #this one above you set in this hash-like manner because of the '-' in the middle of the key. Otherwise you could just do your_struct_name.features.additional_options = false #del_from_array(hash, "persons.name=mary.activities", "cycling") your_struct_name.persons.last.activities.delete('swimming') # or selecting by name: your_struct_name.persons.select {|person| person.name == 'mary' }.first.activities.delete('swimming') #add_to_array(hash, "persons.name=mary.activities", "hockey") your_struct_name.persons.last.activities << 'hockey' #del_key(hash, "data_map") your_struct_name.delete_field('data_map') #del_key(hash, persons.name=john.profile) ... #del_key(hash, persons.name=mary.credits) ... Then, after you make your changes, you can use: your_struct_name.to_h.to_json You can also use the method as_json to get a structure very similar to what you showed on the question: your_struct_name.as_json OpenStruct is very nice to deal with data that has a changing structure. If you have data that can be "modeled", has a name you can call, has some attributes you can predict, and even methods you will use for this data, I suggest you to create a Class to describe this data, its properties and attributes (it can even inherit from OpenStruct). Then work inside this Class domain, creating a layer of abstraction. This way your code gets a lot more robust and readable. Don't forget to create automatic tests! It saves you a lot of time. The way you organize and abstract your data, and specially the way you name entities are things that have high impact on code quality. For further reading see: Object and ActiveData.
{ "pile_set_name": "StackExchange" }
Q: Using '%' as a wild card character in a parameter in SQL with Java So in my program I have: private static final String GET_USERS_BY_PARAMS = "select * from user t " + "where t.id like %?% " + "AND t.name LIKE %?% " + "AND t.location LIKE %?% " + "AND t.telephone LIKE %?% "; All of the parameters given above are stored as varchar in the database. However when I run the following: statement = connection.prepareStatement(GET_USERS_BY_SEARCH_PARAMS); statement.setString(1, userID); statement.setString(2, name); statement.setString(3, location); statement.setString(4, telephone()); rs = statement.executeQuery(); I get a SQL exception stating that there was an invalid character. The application throws the error on the executeQuery, so setting the params isn't an issue. I was wondering if this was down to using the % symbols, whihc I included so that you could search without having to input the exact user ID, name, or etc. Thanks for any help in advance! A: The wildcard has to be part of the value passed to the prepared statement. So you need something like this: private static final String GET_USERS_BY_PARAMS = "select * from user t " + "where t.id like ? " + "AND t.name LIKE ? " + "AND t.location LIKE ? " + "AND t.telephone LIKE ? "; statement = connection.prepareStatement(GET_USERS_BY_SEARCH_PARAMS); statement.setString(1, "%" + userID + "%"); statement.setString(2, "%" + name + "%"); statement.setString(3, "%" + location + "%"); statement.setString(4, "%" + telephone() + "%"); Btw: what datatype is user.id? If that is a numeric value, LIKE won't work correctly. You should probably explictely cast the ID to a character value instead: where to_char(t.id) like ?
{ "pile_set_name": "StackExchange" }
Q: Best way to performance image displaying in Qt I need display image with two requirements, it must be very fast (60-120 fps possible) and with low CPU performance overhead to displaying and draw primitives and scroll. I find some options, but I'm not sure witch will be the best. I will avoiding copy Image. Just date feeder will write directly to image Write custom QOpenGlWidget. Pros: no image copy, opengl backend. Cons: a lot of works, no scrolls implemented Use QGraphicsView as standard. Pros: also opengl backend possible. Cons: please correct me if I miss but image is copy in stanard way. QGraphicsView with repimplemented drawBackground function. Pros: no image copy, opengl backend. Cons: i don't know. Could you show me solutions what I miss and help to choose best one? A: I think that using QGraphicsItem and reimplementing QGraphicsItem::paint which calls the QPainter::drawImage, will do what you want without hassles of doing OpenGL stuff between QPainter::beginNativePainting() and QPainter::endNativePainting(). Taking the former path (native paitings) is also another option if the call to QPainter::drawImage won't give your desired outcome. void FastImageItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { painter->drawImage(image.rect, image, image.rect); } Obviously, you should implement QGraphicsItem::boundingRect() to return your image size.
{ "pile_set_name": "StackExchange" }
Q: C# Socket Server not have more 800 clients I have C# socket sever. Max clients count who able to connect with server about 800. If clients more then 800 new clients get socket error WSAECONNREFUSED 10061. How raizeup max clients count? Socket write between socket.BeginXXX and socket.EndXXX. Target: framework 4.0. Protocols: IP4, TCP A: The listener backlog queue is full. When the backlog queue is full Windows will start sending RSTs to further incoming connections, which become 'connection refused' at the client(s) concerned. You can raise the backlog queue length as per other answers here, but what it really means is that you aren't processing accepts fast enough. Take a good look at the code that does that, and grease the path. Make sure it doesn't do anything else, such as blocking I/O, disk I/O, other network operations. Once the connection is accepted it is off the backlog queue so other incoming connections can succeed.
{ "pile_set_name": "StackExchange" }
Q: Join on the same table in DB2 I have a table like col1 col2 col3 abc 123 A abc 345 B def 567 A ghi 890 B I want to have the data in one row related to an element. Col3 is the discriminator element. Only the 'A' and 'B' rows are related. Result should look like col1 col2A col2B abc 123 345 def 567 -- ghi -- 890 How can i do that?? A: That might not be case to use self join. This will work for the data you posted: select col1, max(case col3 when 'A' then col2 else null end) col2A, max(case col3 when 'B' then col2 else null end) col2B from YourTable group by col1 Of course, if you have data like below, it would fail: col1 col2 col3 abc 123 A abc 345 B abc 567 A Then again, not only the query would fail, but your whole business rule would fail if you have data like this.
{ "pile_set_name": "StackExchange" }
Q: APNS: The certificate is revoked My iPad app uses an ASP.Net server to send APNS messages (using MoonAPNS) to the app when a new document is uploaded to the server. I used MMC to import new certificates last week (Thursday) and had it working with an ad-hoc distribution version of the app. Today, I tried to upload a new document to the server and received the error: Server Error in '/' Application. The certificate is revoked The things is, between last Thursday and today I haven't revoked any certificates / provisioning profiles / etc. Anyone have an idea of why this might have happened? A: I eventually gave up trying to figure this one out and brute-force fixed it by removing then renewing all of the server certificates. Still no idea what caused the initial problem but this at least is a work-around.
{ "pile_set_name": "StackExchange" }
Q: Should I submit an app that only supports Android 6 and 5.1? On my free time, I started working on an app. Back then Android 6 was recently released and 5.1 was still hot. It seemed logical to use Android 6 as my preferred SDK. Now a days, I barely have any free time and the little that I've had, it's been used up working on this app. A few days ago, it came to my attention that android started shipping devices with Android 7. So should I submit my app even if 5.1 will soon become obsolete or should I scrap it? Sorry for my English, it's not my native tongue. A: You should submit it. Just because they're shipping devices with android 7 doesn't mean that there aren't people who still have 5.1 and 6.0. Then you can work on adding compatibility for 7.0 if you have time later
{ "pile_set_name": "StackExchange" }
Q: evaluate a condition when using syntax parse? Is there an equivalent of #:when from match for syntax-parse? Wasn't able to find it in the documentation. Thanks. A: Yes, there is. It’s also called #:when. It even shows up when you search for #:when in the documentation search. From the docs: #:when condition-expr Evaluates the condition-expr in the context of all previous attribute bindings. If the value is #f, the matching process backtracks. In other words, #:when is like #:fail-unless without the message argument. Equivalent to #:post (~fail #:unless condition-expr #f). Example: > (syntax-parse #'(m 5) [(m x:number) #:when (even? (syntax-e #'x)) #'x]) m: bad syntax in: (m 5)
{ "pile_set_name": "StackExchange" }
Q: Does a desktop application need CAPTCHA? I'm coding a desktop application for our university . Users need to signup before using this software and registration request is sent to a server written by me, too. So I'm struggling with kind of network application. ( Suppose that the request format is as simple as a HTTP request sent to an arbitrary port number ) But now I'm wondering whether it's necessary to protect registration process using CAPTCHA or not? Do I need to ensure that the signup request is not generated by a computer? A: As your application is for a limited user group (your university only), I think you do not need a captcha, because the risk is very low that someone is in this group how wants to annoy you. Also scripting for a desktop application is (a bit) more complicated than for web applications, this will decrease the risk, too. IF you are struggling with bot-registrations you could still ship the captcha as an update and only accept registrations from the updated version, don't you?
{ "pile_set_name": "StackExchange" }
Q: cup product in relative cohomology; why the subsets $A$ and $B$ of $X$ have to be open? I have a question about cup products in relative cohomology. In lecture we defined the cup product on singular cohomology as follows: Let $R$ be a commutative ring with unit $1_R$, let $X$ be a topolocial space. The cup product on singular cochain complexes is $$\smile: C^p(X;R)\otimes_R C^q(X;R)\to C^{p+q}(X;R)$$ $$\alpha \otimes \beta \mapsto \alpha \smile \beta$$ where $(\alpha \smile \beta )(\sigma):=(-1)^{pq}\alpha (\sigma_{|[0,..,p]})\beta (\sigma_{|[p,..,p+q]})$ für all $\sigma\in C_{p+q}(X;R)$ (or click here https://en.wikipedia.org/wiki/Cup_product ). This map induces a map in singular cohomology $$\smile: H^p(X;R)\otimes_R H^q(X;R)\to H^{p+q}(X;R)$$ $$[\alpha ] \otimes [\beta ] \mapsto [\alpha \smile \beta],$$which follows from the fact that the following formula holds:$$d^{p+q}(\alpha\smile \beta)=d^p(\alpha)\smile\beta + (-1)^p \alpha\smile d^P(\beta).$$ Now we stated that it's possible to define a cup product for relative homology: Let $A$ and $B$ open subsets of $X$ then there is a relative cup-pruct in singular cohomology $$\smile: H^p(X,A;R)\otimes_R H^q(X,B;R)\to H^{p+q}(X,A\cup B;R)$$ $$[\alpha ] \otimes [\beta ] \mapsto [\alpha \smile \beta].$$ Essential steps in the construction which I know: The key point of the construction is that the inclusion map $$i_*:C^*(X,A\cup B;R)\hookrightarrow C^*(X,A+B;R)$$ is a cochain homotopy equivalence. Here $C^*(X,A+B;R)$ denotes the singular cochain complex with basis: all cochains in $X$ vanishing on chains in $A$ and $B$. Next in the construction the essential step is to consider the composition of the maps $$i_A^*\times i_B^*: C^*(X,A;R)\times C^*(X,B;R)\to C^*(X;R)\times C^*(X;R)$$ and $$\smile: C^*(X;R)\otimes_R C^*q(X;R)\to C^{*}(X;R),$$ $\smile\circ i_A^*\times i_B^*$ (if nothing is wrong). The map $i_A^*$ is the incuced map of the inclusion $i_A:(X,\emptyset)\to (X,A)$ on singular cochain complexes. Then one can prove that $\smile\circ i_A^*\times i_B^*$ factorizes over $C^*(X,A+B;R)$, such that there exists a map $$\smile ': C^*(X,A;R)\times C^*(X,B;R)\to C^*(X,A+B;R)$$ which induces the desired cup product in relative cohomology (here we need the first step, that $H^*(X,A\cup B;R)\cong H^*(X,A+ B;R)$). My question is: Where do we need that $A$ and $B$ are open in $X$? Why can't $A$, $B$ arbitrary subsets in $X$? Best. A: Observe that one of the crucial step is to prove that the inclusion map $C^*(X,A\cup B;R) \hookrightarrow C^*(X,A+B;R)$ induced isomorphism on co-homology. To prove this we need to use the five lemma, and the fact that the restriction maps $C^*(A\cup B;R)\to C^*(A+B;R)$ induced isomorphism on cohomology. To prove the last claim, observe that $C^*(A+B)$ is the dual of the subgroup $C_*(A+B) \subset C_*(A\cup B)$ consists of sums of *-simplicies lying in $A$ or $B$. Now Excision Theorem says that if $X= \cup U_j$ s.t interior of $U_j$ covers $X$, then the inclusion map $i: C_n^U(X) \hookrightarrow C_n(X)$ is a chain homotopy equivalence. So by this theorem the inclusion is a chain homotopy equivalence, so dual restriction map $C^*(A\cup B;R)\to C^*(A+B;R)$ is also a chain homotopy equivalence, hence induced isomorphism on cohomology. And this complete the proof of our original claim. NOTE To use excision we need the fact that $A$ abd $B$ are two open set, otherwise $A$ may not be an open set in $A\cup B$ or otherway.
{ "pile_set_name": "StackExchange" }
Q: Defining multi-line strings in psql I would like to paste 123 456 789 into psql and to store multi-line string in some variable (ie. :str) for later use. Is that possible? Now I'm getting unterminated quoted string error. A: A little clunky, but in version 9.3 and up, you can do it with \gset in conjunction with a dollar-quoted literal: SELECT $$123 456 789$$ AS str \gset
{ "pile_set_name": "StackExchange" }
Q: JQuery / JS variable to alert text I have this code: $('#output').html("<strong>id:</strong>"+id); then <div id="output">this element will be accessed by jquery and this text replaced</div> The above works fine but what I need is for the output to go into an alert so.... <a href="#" onclick="alert('OUTPUT GOES HERE')">Alert Me</a> <- See here How can this be done? A: Give the anchor some type of id or attribute that can be used to look it up: <a href="#" id="alertOutput">Alert Me</a> Then bind to its click event to alert the text content of the #output element: $("#alertOutput").on("click", function(e){ e.preventDefault(); alert( $("#output").text() ); }); The e.preventDefault() portion will prevent the page from jumping back to the top of the document when the anchor is clicked.
{ "pile_set_name": "StackExchange" }
Q: Releasing a pointer causes program to crash, even though the variable isn't used I'm still slogging through learning memory allocation and Objective-C (my first run with Leaks was unpretty, at best). Here is a current issue, I hope everyone can understand it, I've used some pseudo-code, but I don't believe I've left anything out. I have a Row Class set for some database stuff, we'll use this: @interface Row : NSObject { int rowID; NSString *firstName; NSString *lastName; } I have a getRow function in my database class that looks something like this: -(Row *) getRow { rowPlaceholder = [[Row alloc] init]; ... rowPlaceholder.rowID = column1; rowPlaceholder.firstName = column2; rowPlaceholder.lastName = column3; ... return [rowPlaceholder autorelease]; //<-----Problem is happening here } Now in my ViewController I have 2 functions of importance to this situation: -(void) viewWillAppear:(BOOL)animated{ currentRow = [[Row alloc] init]; currentRow = getRow; firstNamelabel.text = currentRow.firstName; } The second function is a button the gets the second word: -(IBAction)btnLastName:(id)sender{ lastNamelabel.text = currentRow.lastName; //<---Crashes the program } So, as you can see, using currentRow against causes the program to crash, and what I can't understand is that if I don't release rowPlaceholder the program works fine. At this point why does currentRow care about the data from another function, since it already has what it want (a value from getRow()). A: autorelease means that the object in question will be automatically released. When this occurs is tied to when the autorelease pool is emptied, but for the default case it's when the UI "comes up for air" -- when your call chain returns back to the UI system code. If you're going to hold something "across" such a return to UI system code, you need to have it explicitly retained. In general, making it a retained property is the best way to do this (though of course you need to clear/release the property in your dealloc method). [And why do you do this:] currentRow = [[Row alloc] init]; currentRow = getRow;
{ "pile_set_name": "StackExchange" }
Q: How to hold SMD parts in place while soldering? I go through this every time I have PCBs I need to populate with SMD parts, and this has become more an issue as pin spacings have gotten tighter, and my hands have become less steady with age. So far I've modified some curved tweezers with a rubber band for grip tension, to help hold a component in place until 1 or 2 pins can be soldered. It works but it can be cumbersome. The clamping force needs to be very light, and it seems one slight tap with a sharp iron tip will still move it. I've also tried various glues, placing a pin drop of glue in the center of where a component would go. That sometimes works, but all the glues I've tried either waste my time waiting for it to dry, or dry (skin over) too quickly when grabbing some more. Worse, too often even a pin drop of glue will spread onto the pads, and then I have to waste more time cleaning things up. If I had my druthers, all SMD pars would come with peel off self stick backing. But anyway, suggestions would be welcome. It will be a long time and many test markets before anything I'm doing will be populated for me with pro pick and place machines. A: Pssshh to the guys using stencils :) Bet I can put a QFP down faster than you can paste, place, and re-flow :) Although it's nice if you want to get that center pad soldered. Seriously though if we're talking ICs here I just flux pen a little, then put some solder on one pin in the corner. Then put the chip near it. Now just flow the solder with your iron and nudge it into place with a pick, tweezers or the finger whatever works for that part. Then you can align all the other sides by heating the solder a little and nudging it. Then tack the opposite corner and off you go. Don't waste time trying to align then solder, align while you solder. For little guys like a SOT-23 or a 0201 I usually first put a bit of solder on one pad then heat it up and slide one pad of the component in with the tweezers. Pull the iron off and it stays in place, you can use as much force on the tweezers as you need to. Then just finish up the other pins. You can go pretty fast with this if you're placing multiple parts just prepare one pad on each footprint, then slide in the parts and then go back and do the other pins. That's my basic hand technique, works for QFNs too if you don't need the center pad soldered (the board needs to be on an angle). I usually drag solder the IC's which is really fast when you get the hang of it. For my stencil friends, you should see that new printer on kickstarter that puts down solder paste... A: I just saw the SMD beak on Hack-a-day that looks like what you are looking for (I want one!)... http://vpapanik.blogspot.de/2015/02/the-smd-beak.html I've also had luck... use a little piece of scotch or painter's tape on one side of a part to hold it down tack down a couple of leads with solder remove tape and solder down properly For smaller parts (ie. SOT23)... tin one pad (typically a middle one) hold the part in exactly the right place with tweeters quickly touch the lead over the tinned pad with your iron to tack it down properly solder the other pins and work your way around back to the tacked one. A nice feature of this technique is that you can rotate the part very precisely by moving your elbow (your arm acts like a big leaver). Even if you are a bit shaky, you can wait until the part happens to be perfectly aligned and then lock it down with the tack. A: In general I don't hand solder any more. There's a few components though that I do still prefer to do by hand, such as 0.5mm pitch TQFPs or TSSOPs (the really fine ones) - unless I have a stencil of course. For those I just hold it down with my finger until two pins have been tacked down, when it then holds itself in place. Anything smaller than that gets reflowed. I can't stress how much easier it is to use solder paste and a reflow workstation (or oven for full boards) instead of a soldering iron.
{ "pile_set_name": "StackExchange" }
Q: Is one allowed to smoke? Nowadays, since there are studies that show that smoking is dangerous to health, is one allowed to smoke or is it violating "Venishmartem Meod Lenafshosechem"? A: There is a machlokes haposkim on this matter. Igros Moshe wrote in 1964 that since there is a possibility of danger from smoking, one should refrain from doing so, however, it is not forbidden because "Shomer Psaim Hashem", Hashem guards the fools. In 1981, R' Moshe wrote that the danger of smoking is no more than the danger of eating unhealthy foods, about which the Rambam does not write that they are "forbidden", just unrecommended. Therefore, he writes, because people get withdrawal syndromes when they do not have what to smoke, and the danger is not so great (R' Moshe writes that the amount of people who get sick is a small minority). Therefore, we say that "Hashem guards the fools". However, he says that one should not start smoking, since there is some danger without any benefits, and there is no desire to smoke until one starts. However, R' Moshe Shternbuch said that it is forbidden because of danger from Cancer and heart problems. the Chazon Ish said that smoking hurts memory and comprehension, so smoking would be prohibited because of "Lo Tishkach", that one isn't allowed to do something to cause oneself to forget words of Torah. Binyomin Zilber takes a middle approach, and says that while it may be very unhealthy, yet it would not be intrinsically prohibited. He brings a proof from the Mishna Brurah which permits smoking on Yom Tov, yet in his Likkutei Amarim he says that smoking weakens a person, and causes a waste of time and money. In other words, there are things that are wrong to do, yet not officially "prohibited". The Previous Lubavitcher Rebbe writes (in 1943) to the Rosh Yeshiva of Tomchei Tmimim to absolutely forbid smoking to students under 20 wherever they may be for all 24 hours a day. He should also give over a request to students who are above 20 that it is in their benefit (both physical and spiritual) to quit smoking, by slowly lessening their smoking until they will quit completely. There are two opinions as to what was the Lubavitcher Rebbe's opinion. Someone asked the Rebbe why do Rabbonim not forbid smoking. The Lubavitcher Rebbe answered with two reasons: This matter is for doctors to decide, not Rabbonim. It is possible that a harmless cigarette will be invented. However, if there will be a ban, that cigarette would also be included and would be needlessly forbidden. There is a debate between R' Oberlander and R' Zayants as to the meaning of the Rebbe's answer. R' Oberlander writes that one reason to permit is because of "Hashem guards the fools". One of the sources that we can rely on the verse "Hashem guards the fools" is a Gemara in Yevamos(12b) that has an argument between R' Meir who says that a 11-12 year old should prevent pregnancy (because it is dangerous to give birth at that age) and the Chachamim who permit it because "Hashem guards the fools". However, he brings down the Tzemach Tzedek who asks if we can say "Hashem guards the fools" in cases where a pregnancy is dangerous for a woman. The Tzmeach Tzedek says that one could differentiate between the Gemara's case and a dangerous pregnancy, because in the case of the Gemara, most 11-12 year olds don't get pregnant, so we could rely on "Hashem guards the fools" and a "majority" to assume that the dangerous situation won't come up and there will be no pregnancy. However, if the danger is more definite, one can't say "Hashem guards the fools". R' Oberlander then goes on to say how smoking is not very dangerous, so we could rely on "majority" (majority of people who smoke don't get sick) and "Hashem guards the fools" to assume the "minority" dangerous situation won't happen and permit smoking. However, R' Zayents explains the Tzemach Tzedek differently. He explains the idea of "Hashem guards the fools" is that when it applies Hashem prevents the "minority" dangerous case from happening. In other words, by a 11-12 year old, "Hashem guards the fools" means that such a case will not occur (she won't get pregnant). However, if a dangerous situation would occur, we would have to worry about it in the first place. Since in smoking there is at least this "minority" of smokers who get sick, we would have to take them into account and forbid smoking. Moreover, R' Zayentz points out that the letter where the Rebbe gave reasons why Rabbis don't forbid smoking does not mention "Hashem guards the fools". The Rebbe's letter says that smoking is a medical questions for doctors to address, and as long as it's unhealthy it's automatically forbidden, and when it will become healthy, it will be automatically permitted. Interestingly enough, Igros Moshe permits the Dor Yeshorim test even though there is only a small chance of having children with birth-defects, and says that not taking the test is like closing one's eyes to danger. A: To add to the answer(s) about R' Moshe Feinstein's Pesak, R' Dr. Moshe D. Tendler, son-in-law of R' Moshe Feinstein, has been an outspoken advocate for banning smoking 'Al Pi Halachah, and he has publicly stated (in fact, I've been present in a large audience where he has stated) that he firmly believes R' Moshe Feinstein's Pesak would have been very different, outlawing it 100% in all cases, had the medical community known then what it knows now about just how deadly it actually is. One point he emphasized when I heard R' Dr. Tendler speak on the topic is that, at the time that R' Moshe Feinstein wrote his Teshuvah, it was believed by the medical community that those who get sick are a small minority and that the risk is small. R' Moshe consulted doctors and medical experts in rendering his decision. The consensus among them at the time of his decision was that it wasn't good for you, but it wasn't yet determined to be as severely or as commonly dangerous as we now know it to be. In other words, the wording of R' Moshe's ShU"T reflected the understanding of the medical community's overall consensus as conveyed to him by those experts he consulted at the time. According to R' Dr. Tendler, R' Moshe based the Pesak entirely on that assessment, which, according to him, means that the Pesak would have been a 100% ban with today's awareness in the medical community. A: To echo above answer: Rabbi Moshe Feinstein strongly discouraged it and prohibited new use, but couldn't quite prohibit existing smokers from continuing their awful habit (and as such, allowed one to give a smoker a light if asked), despite protests from his student Dr. Fred Rosner. Some 15 years later, in light of further medical proof of just how awful smoking is (and the advances in detection and treatment for many types of cancer, but not lung), the RCA's position became to flat-out prohibit it.
{ "pile_set_name": "StackExchange" }
Q: force product view layout to 1column I want to show the single product page information in one single column, but it is always displayed on 2-columns-left: <body data-container="body" itemtype="http://schema.org/Product" itemscope="itemscope" class="page-product-configurable catalog-product-view product-e16-mariniere-cannes page-layout-2columns-left"> I have in app/design/frontend/mycompany/mytheme/Magento_Catalog/layout/catalog_product_view.xml configured the page in 1column <page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> But still displaying the 2 columns layout, with the product info on the right, and a blank column on the left. I added <referenceContainer name="content.aside" remove="true" /> And now the left column is not there, but still the product is moved to the right as if the column is still there. When I edit this xml file, the changes are displayed, so the file is placed correctly, and it is being readed. But still 2 columns left layout. I even tried with no result the following approach: <body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_layout.xsd"> <update handle="1column"/> This is the full content file: <page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <head> <css src="mage/gallery/gallery.css"/> </head> <update handle="catalog_product_opengraph" /> <update handle="page_calendar"/> <body> <attribute name="itemtype" value="http://schema.org/Product" /> <attribute name="itemscope" value="itemscope"/> <referenceBlock name="head.components"> <block class="Magento\Framework\View\Element\Js\Components" name="checkout_page_head_components" template="Magento_Catalog::js/components.phtml"/> </referenceBlock> <referenceBlock name="page.main.title"> <arguments> <argument name="css_class" xsi:type="string">product</argument> <argument name="add_base_attribute" xsi:type="string">itemprop="name"</argument> </arguments> </referenceBlock> <referenceBlock name="root"> <arguments> <argument name="add_attribute" xsi:type="string">itemscope itemtype="http://schema.org/Product"</argument> </arguments> </referenceBlock> <referenceContainer name="content"> <container name="product.info.main" htmlTag="div" htmlClass="product-info-main" before="-"> <container name="product.info.price" label="Product info auxiliary container" htmlTag="div" htmlClass="product-info-price" after="product.info.review"> <container name="product.info.stock.sku" label="Product auxiliary info" htmlTag="div" htmlClass="product-info-stock-sku"> <container name="product.info.type" before="-"/> <block class="Magento\Catalog\Block\Product\View\Description" name="product.info.sku" template="product/view/attribute.phtml" after="product.info.type"> <arguments> <argument name="at_call" xsi:type="string">getSku</argument> <argument name="at_code" xsi:type="string">sku</argument> <argument name="css_class" xsi:type="string">sku</argument> <argument name="at_label" xsi:type="string">default</argument> <argument name="add_attribute" xsi:type="string">itemprop="sku"</argument> </arguments> </block> </container> <block class="Magento\Catalog\Block\Product\View" name="product.info.review" template="product/view/review.phtml" after="product.info.stock.sku" /> <block class="Magento\Catalog\Pricing\Render" name="product.price.final" after="product.info.sku"> <arguments> <argument name="price_render" xsi:type="string">product.price.render.default</argument> <argument name="price_type_code" xsi:type="string">final_price</argument> <argument name="zone" xsi:type="string">item_view</argument> </arguments> </block> </container> <block class="Magento\Catalog\Pricing\Render" name="product.price.tier" after="product.info.price"> <arguments> <argument name="price_render" xsi:type="string">product.price.render.default</argument> <argument name="price_type_code" xsi:type="string">tier_price</argument> <argument name="zone" xsi:type="string">item_view</argument> </arguments> </block> <container name="alert.urls" as="alert_urls" label="Alert Urls" after="product.price.tier"/> <block class="Magento\Catalog\Block\Product\View" name="product.info" template="product/view/form.phtml" after="alert.urls"> <container name="product.info.form.content" as="product_info_form_content"> <block class="Magento\Catalog\Block\Product\View" name="product.info.addtocart" as="addtocart" template="product/view/addtocart.phtml"/> </container> <block class="Magento\Framework\View\Element\Template" name="product.info.form.options" as="options_container"> <block class="Magento\Catalog\Block\Product\View" name="product.info.options.wrapper" as="product_options_wrapper" template="product/view/options/wrapper.phtml"> <block class="Magento\Catalog\Block\Product\View\Options" name="product.info.options" as="product_options" template="product/view/options.phtml"> <block class="Magento\Catalog\Block\Product\View\Options\Type\DefaultType" as="default" template="product/view/options/type/default.phtml"/> <block class="Magento\Catalog\Block\Product\View\Options\Type\Text" as="text" template="product/view/options/type/text.phtml"/> <block class="Magento\Catalog\Block\Product\View\Options\Type\File" as="file" template="product/view/options/type/file.phtml"/> <block class="Magento\Catalog\Block\Product\View\Options\Type\Select" as="select" template="product/view/options/type/select.phtml"/> <block class="Magento\Catalog\Block\Product\View\Options\Type\Date" as="date" template="product/view/options/type/date.phtml"/> </block> <block class="Magento\Framework\View\Element\Html\Calendar" name="html_calendar" as="html_calendar" template="Magento_Theme::js/calendar.phtml"/> </block> <block class="Magento\Catalog\Block\Product\View" name="product.info.options.wrapper.bottom" as="product_options_wrapper_bottom" template="product/view/options/wrapper/bottom.phtml"> <block class="Magento\Catalog\Block\Product\View" name="product.info.addtocart.additional" as="product.info.addtocart" template="product/view/addtocart.phtml"/> </block> </block> </block> <container name="product.info.extrahint" as="extrahint" label="Product View Extra Hint"> <container name="product.info.social" label="Product social links container" htmlTag="div" htmlClass="product-social-links" after="product.info.overview"> <referenceBlock name="product.info.addto" remove="true" /> <block class="Magento\Catalog\Block\Product\View" name="product.info.mailto" template="product/view/mailto.phtml"/> </container> </container> <block class="Magento\Catalog\Block\Product\View\Description" name="product.info.overview" template="product/view/attribute.phtml" group="detailed_info" after="product.info.extrahint"> <arguments> <argument name="at_call" xsi:type="string">getShortDescription</argument> <argument name="at_code" xsi:type="string">short_description</argument> <argument name="css_class" xsi:type="string">overview</argument> <argument name="at_label" translate="true" xsi:type="string">none</argument> <argument name="title" translate="true" xsi:type="string">Overview</argument> <argument name="add_attribute" xsi:type="string">itemprop="description"</argument> </arguments> </block> </container> <container name="product.info.media" htmlTag="div" htmlClass="product media" after="product.info.main"> <block class="Magento\Catalog\Block\Product\View\Gallery" name="product.info.media.image" template="product/view/gallery.phtml"/> </container> <block class="Magento\Catalog\Block\Product\View\Description" name="product.info.details" template="product/view/details.phtml" after="product.info.media"> <block class="Magento\Catalog\Block\Product\View\Description" name="product.info.description" template="product/view/attribute.phtml" group="detailed_info"> <arguments> <argument name="at_call" xsi:type="string">getDescription</argument> <argument name="at_code" xsi:type="string">description</argument> <argument name="css_class" xsi:type="string">description</argument> <argument name="at_label" xsi:type="string">none</argument> <argument name="title" translate="true" xsi:type="string">Details</argument> </arguments> </block> <block class="Magento\Catalog\Block\Product\View\Attributes" name="product.attributes" as="additional" template="product/view/attributes.phtml" group="detailed_info"> <arguments> <argument translate="true" name="title" xsi:type="string">More Information</argument> </arguments> </block> </block> </referenceContainer> <referenceContainer name="content.aside" remove="true" /> <referenceContainer name="customer.interceptor" remove="true" /> <referenceBlock name="product.info.addtocart"> <block class="Magento\Catalog\Block\ShortcutButtons\InCatalog" name="addtocart.shortcut.buttons"/> </referenceBlock> <referenceBlock name="product.info.addtocart.additional"> <block class="Magento\Catalog\Block\ShortcutButtons\InCatalog" name="addtocart.shortcut.buttons.additional"/> </referenceBlock> </body> Edit: I have the cache disabled, and I cleared it anyways (the first thing I did), but still no results. Edit 2: It is Magento 2.1.3 version A: I've discovered what is causing the problem, it seems that when importing the project from magento 1.9 to 2.1, each individual product in each store was imported with a migration_design of '2 columns with left bar' causing the xml page layout being overriden by the cms product option. If I edit a concrete product in a concrete store and change the migration design to 'no layout updates' then, this product have a 1 column layout in the store I changed it, if with this product I go to another store then it is displayed in 2 columns again. The solution is edit the database, changing all the products in all the stores to 'no layout updates'.
{ "pile_set_name": "StackExchange" }
Q: xquery return value off by one <?xml version="1.0" encoding="UTF-8"?> <library> <items> <book asin="0201100886" created="128135928" lastLookupTime="128135928"> <uuid>BA57A934-6CDC-11D9-830B-000393D3DE16</uuid> <title>Compilers</title> <authors> <author>Alfred V. Aho</author> <author>Ravi Sethi</author> <author>Jeffrey D. Ullman</author> </authors> <publisher>Addison Wesley</publisher> <published>1986-01-01</published> <price>102.00</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0122513363" created="128135600" lastLookupTime="128136224"> <uuid>F7468E09-6CDB-11D9-830B-000393D3DE16</uuid> <title>Database Driven Web Sites</title> <authors><author>Jesse Feiler</author></authors> <publisher>Morgan Kaufmann</publisher> <published>1998-04-15</published> <edition>Paperback</edition> <price>50.95</price> <purchaseDate>2005-01-22</purchaseDate> <currentValue>35.00</currentValue> <netRating>1.5</netRating> <genres> <genre>Computer Bks - Internet</genre> <genre>Computer Books: Web Programming</genre> <genre>Computer Networks</genre> <genre>Computers</genre> <genre>Database Management - General</genre> <genre>Database management</genre> <genre>Design</genre> <genre>Distributed Databases</genre> <genre>Information Technology</genre> <genre>Internet - Web Site Design</genre> <genre>Networking - General</genre> <genre>Web sites</genre> <genre>Computers / Computer Science</genre> </genres> <upc>608628133638</upc> </book> <book asin="0201441241" created="128136896" lastLookupTime="128136896"> <uuid>FBC45DF4-6CDE-11D9-830B-000393D3DE16</uuid> <title>Introduction to Automata Theory, Languages, and Computation (2nd Edition)</title> <authors> <author>John E. Hopcroft</author> <author>Rajeev Motwani</author> <author>Jeffrey D. Ullman</author> </authors> <publisher>Addison Wesley</publisher> <published>2000-11-14</published> <price>108.20</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0471250600" created="128136896" lastLookupTime="128136896"> <uuid>FBC7CA56-6CDE-11D9-830B-000393D3DE16</uuid> <title>Operating System Concepts</title> <authors> <author>Abraham Silberschatz</author> <author>Greg Gagne</author> <author>Peter Baer Galvin</author> </authors> <publisher>Wiley</publisher> <published>2002-03-08</published> <price>107.95</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0321193628" created="128136896" lastLookupTime="128136896"> <uuid>FBCB3DCF-6CDE-11D9-830B-000393D3DE16</uuid> <title>Concepts of Programming Languages, Sixth Edition</title> <authors><author>Robert W. Sebesta</author></authors> <publisher>Addison Wesley</publisher> <published>2003-07-24</published> <price>112.40</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0138613370" created="128136944" lastLookupTime="128136944"> <uuid>19E5E602-6CDF-11D9-830B-000393D3DE16</uuid> <title>First Course in Database Systems, A</title> <authors> <author>Jeffrey D. Ullman</author> <author>Jennifer Widom</author> </authors> <publisher>Prentice Hall</publisher> <published>1997-04-02</published> <edition>Hardcover</edition> <price>67.00</price> <purchaseDate>2005-01-22</purchaseDate> <netRating>3.2</netRating> <genres> <genre>Computer Books: Database</genre> <genre>Computers</genre> <genre>Database Engineering</genre> <genre>Database Management - General</genre> <genre>Database management</genre> </genres> <recommendations> <book asin="0130402648" created="128136952" lastLookupTime="128136952"> <uuid>1C60074A-6CDF-11D9-830B-000393D3DE16</uuid> <title>Database System Implementation</title> <authors> <author>Hector Garcia-Molina</author> <author>Jeffrey D. Ullman</author> <author>Jennifer D. Widom</author> </authors> <publisher>Prentice Hall</publisher> <published>1999-06-11</published> <price>89.00</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0130319953" created="128136952" lastLookupTime="128136952"> <uuid>1C635DB0-6CDF-11D9-830B-000393D3DE16</uuid> <title>Database Systems: The Complete Book</title> <authors> <author>Hector Garcia-Molina</author> <author>Jeffrey D. Ullman</author> <author>Jennifer D. Widom</author> </authors> <publisher>Prentice Hall</publisher> <published>2001-10-02</published> <price>98.00</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0201976994" created="128136952" lastLookupTime="128136952"> <uuid>1C66B7B4-6CDF-11D9-830B-000393D3DE16</uuid> <title>Computer Networking: A Top-Down Approach Featuring the Internet</title> <authors> <author>James F. Kurose</author> <author>Keith W. Ross</author> <author>James Kurose</author> <author>Keith Ross</author> </authors> <publisher>Addison Wesley</publisher> <published>2002-07-17</published> <price>100.00</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0131433512" created="128136952" lastLookupTime="128136952"> <uuid>1C6AC88C-6CDF-11D9-830B-000393D3DE16</uuid> <title>Computer Networks and Internets, Fourth Edition</title> <authors> <author>Douglas E Comer</author> <author>Ralph E. Droms</author> </authors> <publisher>Prentice Hall</publisher> <published>2003-07-28</published> <price>100.00</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0262062178" created="128136952" lastLookupTime="128136952"> <uuid>1C6E712C-6CDF-11D9-830B-000393D3DE16</uuid> <title>Essentials of Programming Languages - 2nd Edition</title> <authors> <author>Daniel P. Friedman</author> <author>Mitchell Wand</author> <author>Christopher T. Haynes</author> </authors> <publisher>The MIT Press</publisher> <published>2001-01-29</published> <price>62.00</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0471250600" created="128136952" lastLookupTime="128136952"> <uuid>1C71B23E-6CDF-11D9-830B-000393D3DE16</uuid> <title>Operating System Concepts</title> <authors> <author>Abraham Silberschatz</author> <author>Greg Gagne</author> <author>Peter Baer Galvin</author> </authors> <publisher>Wiley</publisher> <published>2002-03-08</published> <price>107.95</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0137903952" created="128136952" lastLookupTime="128136952"> <uuid>1C764AD4-6CDF-11D9-830B-000393D3DE16</uuid> <title>Artificial Intelligence: A Modern Approach (2nd Edition)</title> <authors> <author>Stuart J. Russell</author> <author>Peter Norvig</author> </authors> <publisher>Prentice Hall</publisher> <published>2002-12-20</published> <price>93.33</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="155860832X" created="128136952" lastLookupTime="128136952"> <uuid>1C898640-6CDF-11D9-830B-000393D3DE16</uuid> <title>Computer Networks: A Systems Approach, 3rd Edition</title> <authors> <author>Larry L. Peterson</author> <author>Bruce S. Davie</author> </authors> <publisher>Morgan Kaufmann</publisher> <published>2003-05-22</published> <price>89.95</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0130669474" created="128136952" lastLookupTime="128136952"> <uuid>1C8DD37A-6CDF-11D9-830B-000393D3DE16</uuid> <title>SQL Fundamentals (2nd Edition)</title> <authors><author>John J. Patrick</author></authors> <publisher>Prentice Hall PTR</publisher> <published>2002-05-07</published> <price>54.99</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0321122267" created="128136952" lastLookupTime="128136952"> <uuid>1C91D772-6CDF-11D9-830B-000393D3DE16</uuid> <title>Fundamentals of Database Systems, Fourth Edition</title> <authors> <author>Ramez Elmasri</author> <author>Shamkant B. Navathe</author> </authors> <publisher>Addison Wesley</publisher> <published>2003-07-23</published> <price>104.20</price> <purchaseDate>2005-01-22</purchaseDate> </book> </recommendations> </book> <book asin="1558604820" created="128136024" lastLookupTime="128136024"> <uuid>F3C7B24F-6CDC-11D9-830B-000393D3DE16</uuid> <title>A Complete Guide to DB2 Universal Database</title> <authors> <author>D. D. Chamberlin</author> <author>Don Chamberlin</author> </authors> <publisher>Morgan Kaufmann</publisher> <published>1998-08-15</published> <edition>Paperback</edition> <price>62.95</price> <purchaseDate>2005-01-22</purchaseDate> <netRating>4.4</netRating> <genres> <genre>Computer Bks - Data Base Management</genre> <genre>Computer Books: Database</genre> <genre>Computers</genre> <genre>Database Management - General</genre> <genre>General</genre> <genre>IBM Database 2</genre> <genre>Information Storage &amp; Retrieval</genre> <genre>Relational Databases</genre> <genre>Computers / Information Storage &amp; Retrieval</genre> </genres> <recommendations> <book asin="0072133449" created="128136024" lastLookupTime="128136024"> <uuid>F6B35F21-6CDC-11D9-830B-000393D3DE16</uuid> <title>DB2: The Complete Reference (Complete Reference Series)</title> <authors> <author>Roman B. Melnyk</author> <author>Paul C. Zikopoulos</author> </authors> <publisher>McGraw-Hill Companies</publisher> <published>2001-10-01</published> <price>59.99</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0130661112" created="128136024" lastLookupTime="128136024"> <uuid>F6B97E54-6CDC-11D9-830B-000393D3DE16</uuid> <title>DB2 UDB v8 Handbook for Windows and UNIX/Linux</title> <authors><author>Philip K. Gunning</author></authors> <publisher>Prentice Hall PTR</publisher> <published>2003-08-06</published> <price>59.99</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0131007726" created="128136024" lastLookupTime="128136024"> <uuid>F6BCBB88-6CDC-11D9-830B-000393D3DE16</uuid> <title>DB2 SQL Procedural Language for Linux, Unix and Windows</title> <authors> <author>Paul Yip</author> <author>Drew Bradstock</author> <author>Hana Curtis</author> <author>Michael Gao</author> <author>Zamil Janmohamed</author> <author>Clara Liu</author> <author>Fraser McArthur</author> </authors> <publisher>Prentice Hall PTR</publisher> <published>2002-12-24</published> <price>59.99</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0131424653" created="128136024" lastLookupTime="128136024"> <uuid>F6C0A296-6CDC-11D9-830B-000393D3DE16</uuid> <title>DB2 UDB V8.1 Certification Exam 700 Study Guide</title> <authors><author>Roger E. Sanders</author></authors> <publisher>Prentice Hall PTR</publisher> <published>2003-09-17</published> <price>49.99</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0764508415" created="128136024" lastLookupTime="128136024"> <uuid>F6C4058C-6CDC-11D9-830B-000393D3DE16</uuid> <title>DB2 Fundamentals Certification for Dummies</title> <authors> <author>Paul C. Zikopoulos</author> <author>Jennifer Gibbs</author> <author>Roman B. Melnyk</author> </authors> <publisher>For Dummies</publisher> <published>2001-08-01</published> <price>34.99</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0130463612" created="128136024" lastLookupTime="128136024"> <uuid>F6D9A3D8-6CDC-11D9-830B-000393D3DE16</uuid> <title>DB2 Universal Database V8 for Linux, UNIX, and Windows Database Administration Certification Guide (5th Edition)</title> <authors> <author>George Baklarz</author> <author>Bill Wong</author> </authors> <publisher>Prentice Hall PTR</publisher> <published>2003-02-10</published> <price>59.99</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0130463884" created="128136024" lastLookupTime="128136024"> <uuid>F6DDBAB9-6CDC-11D9-830B-000393D3DE16</uuid> <title>Advanced DBA Certification Guide and Reference for DB2 UDB v8 for Linux, Unix and Windows</title> <authors> <author>Dwaine R. Snow</author> <author>Thomas Xuan Phan</author> <author>Dwaine Snow</author> </authors> <publisher>Prentice Hall PTR</publisher> <published>2003-07-07</published> <price>59.99</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="155860443X" created="128136024" lastLookupTime="128136024"> <uuid>F6E1063D-6CDC-11D9-830B-000393D3DE16</uuid> <title>Advanced Database Systems (The Morgan Kaufmann Series in Data Management Systems)</title> <authors> <author>Carlo Zaniolo</author> <author>Stefano Ceri</author> <author>Christos Faloutsos</author> <author>Richard T. Snodgrass</author> <author>V. S. Subrahmanian</author> <author>Roberto Zicari</author> </authors> <publisher>Morgan Kaufmann</publisher> <published>1997-05-01</published> <price>88.95</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0131840487" created="128136024" lastLookupTime="128136024"> <uuid>F6E441CE-6CDC-11D9-830B-000393D3DE16</uuid> <title>DB2 UDB V8.1 Certification Exams 701 and 706 Study Guide</title> <authors><author>Roger E. Sanders</author></authors> <publisher>Prentice Hall PTR</publisher> <published>2003-12-12</published> <price>49.99</price> <purchaseDate>2005-01-22</purchaseDate> </book> <book asin="0132037955" created="128136024" lastLookupTime="128136024"> <uuid>F6E77C2C-6CDC-11D9-830B-000393D3DE16</uuid> <title>DB2 High Performance Design and Tuning</title> <authors> <author>Richard Yevich</author> <author>Susan Lawson</author> <author>Richard A. Yevich</author> </authors> <publisher>Prentice Hall PTR</publisher> <published>2000-08-24</published> <price>54.99</price> <purchaseDate>2005-01-22</purchaseDate> </book> </recommendations> </book> </items> <borrowers> <borrower id="1"> <name> John Doe </name> <phone> 555-1212 </phone> <borrowed> <book asin="0138613370"/> <book asin="0122513363"/> </borrowed> </borrower> <borrower id="2"> <name> Mary Jane </name> <phone> 555-1213 </phone> <borrowed> <book asin="0201100886"/> <book asin="0122513363"/> </borrowed> </borrower> <borrower id="3"> <name> Bill Jones </name> <phone> 555-1312 </phone> <borrowed /> </borrower> <borrower id="4"> <name> Anne Marie</name> <phone> 555-1314</phone> <borrowed> <book asin="0138613370"/> <book asin="0201100886"/> <book asin="0122513363"/> <book asin="1558604820"/> </borrowed> </borrower> </borrowers> </library> I need to return everyone that borrowed a book, their name and the title of the book. Here is my xQuery: xquery version "1.0"; for $library in doc("library.xml")/library for $book in $library/items/book let $borrowed := $library/borrowers/borrower return <borrower> <name> {data($borrowed/name)} </name> <title> {data($book[@asin = $borrowed//book/@asin]/title)} </title> </borrower> Here is what it returns: <borrower> <name> John Doe Mary Jane Bill Jones Anne Marie</name> <title>Compilers</title> </borrower> <borrower> <name> John Doe Mary Jane Bill Jones Anne Marie</name> <title>Database Driven Web Sites</title> </borrower> <borrower> <name> John Doe Mary Jane Bill Jones Anne Marie</name> <title/> </borrower> <borrower> <name> John Doe Mary Jane Bill Jones Anne Marie</name> <title/> </borrower> <borrower> <name> John Doe Mary Jane Bill Jones Anne Marie</name> <title/> </borrower> <borrower> <name> John Doe Mary Jane Bill Jones Anne Marie</name> <title>First Course in Database Systems, A</title> </borrower> <borrower> <name> John Doe Mary Jane Bill Jones Anne Marie</name> <title>A Complete Guide to DB2 Universal Database</title> </borrower> So first thing that is wrong is that it is returning all the names of people who have borrowed a book instead of one name per tag. Second, it should return 8 books and its only returning 7. Can anyone please help me understand what is wrong with my xQuery???? A: I'm pretty sure you're trying to get a list of each borrower with the titles of the books they have borrowed. The problem with your XQuery is that you are iterating over each /library/items/book instead of each borrower. Also, there are only 7 /library/items/book in your example; not 8. This XQuery should do what you want. XQuery <borrowers> { let $library := doc('library.xml') for $borrower in $library/library/borrowers/borrower let $name := $borrower/name let $asins := data($borrower/borrowed/book/@asin) let $titles := for $asin in $asins return $library/library/items/book[@asin = $asin]/title return <borrower> {$name} {$titles} </borrower> } </borrowers> Results <borrowers> <borrower> <name> John Doe </name> <title>First Course in Database Systems, A</title> <title>Database Driven Web Sites</title> </borrower> <borrower> <name> Mary Jane </name> <title>Compilers</title> <title>Database Driven Web Sites</title> </borrower> <borrower> <name> Bill Jones </name> </borrower> <borrower> <name> Anne Marie</name> <title>First Course in Database Systems, A</title> <title>Compilers</title> <title>Database Driven Web Sites</title> <title>A Complete Guide to DB2 Universal Database</title> </borrower> </borrowers>
{ "pile_set_name": "StackExchange" }
Q: What is causing the bark on my crabapple to crack and peel off? I have a flowering crabapple in my yard whose bark has several large areas where it cracks and curls away from the wood underneath: Hover over any image for description / click for full size I don't know what variety it is (the previous owners planted it), but it's a flowering crabapple with fragrant pink flowers and inedible 2" kidney-shaped fruit. I live in Portland, Oregon, USA which is USDA zone 8a. My questions: What is causing this damage and how can I treat it? Should I be worried about it spreading to my real apple tree which is approximately 20' away? A: I volunteered at a heritage garden (shameless plug for a place worth visiting) that had old crab apple and their bark did exfoliate or peel in little scales about two inches high by an inch wide. This is normal for mature crab apple and apple trees. What is in your pictures doesn't look like a mature tree with a trunk over eight inches in diameter and neither is the peeling all over the trunk. Given the diversity of the apple family it's hard to say whether this is normal or not. The real question is: does the tree look healthy and bear fruit? If it does then watch and wait is my advice. If the tree lacks healthy new growth or fruit then call an arborist for an on-site opinion. Edit: from the additional pictures I can see that there is healthy bark underneath the peeling area and that the tree does not look stressed. I am in agreement with @Ed Staub that this is normal for apple trees. Dropping bark allows the tree to drop pests and diseases in the top layer.
{ "pile_set_name": "StackExchange" }
Q: How to stop an async task? Suppose that I have a List<Task> which help me to manage all the task based on index: private List<Task> tasks = new List<Task>(new Task[3]); When the application start a menu is displayed, and the user can select which task can start, simply: public void Menu() { Console.WriteLine("1. Task"); Console.WriteLine("2. Task"); Console.WriteLine("3. Task"); Console.WriteLine("0. Exit"); ConsoleKeyInfo input; do { input = Console.ReadKey(); Console.WriteLine(); switch (input.Key) { case ConsoleKey.NumPad1: StartTask(1); break; case ConsoleKey.NumPad2: StartTask(2); break; case ConsoleKey.NumPad3: StartTask(3); break; } } while (input.Key != ConsoleKey.NumPad0); } inside the method StartTask I pass the number of Task to execute, this is the logic: public void StartTask(int instance) { int index = instance - 1; //Task not yet instantiated, create new one if(tasks.ElementAtOrDefault(index) == null) { //Make a new cancellation token cts.Insert(index, new CancellationTokenSource()); tasks.Insert(index, new Task(async () => { await foo.DoWork(cts[index].Token); }, cts[index].Token)); if(!tasks[index].Status.Equals(TaskStatus.Running)) { tasks[index].Start(); } } } as you can see I also have a List<CancellationTokenSource> cts which help me to terminate the task. The Cancel method is placed in another menu like above. Now the problem is pretty clear: I can't do that because the checking is executed before the await operation of DoWork(); that contains this: public class Foo { private async Task DoWorkAsync(CancellationToken token) { while (!token.IsCancellationRequested) { string newData = DateTime.Now.ToLongTimeString(); Console.WriteLine(newData); await Task.Delay(200); } } } essentially: how can I stop the Task that execute the loop with the CancellationToken? The token passed as parameter cannot change the value if the stop is executed later the start. Essentially the value of IsCancellationRequested is changing only in the Task class context, not in the argument passed. A: Pass cancellation token to DoWorkAsync. And use it in 'while' loop as a condition. while(!token.IsCancellationRequested) { await Task.Delay(200, token); } 'token' should be passed as a parameter. To be honest, I think there is too much redundant code in your solution ... How to cancel task using cancellation token source: void CancelTask(int taskNumber) { int index = taskNumber - 1; cts[index].Cancel(); } This code will set 'IsCancellationRequested' flag of 'token' you use in the loop into 'true'.
{ "pile_set_name": "StackExchange" }
Q: What does this mean? Entry e = table[bucketIndex]; I am studying how HashMap works inside and can not understand this method: void addEntry(int hash, K key, V value, int bucketIndex) { Entry<K,V> e = table[bucketIndex]; table[bucketIndex] = new Entry<K,V>(hash, key, value, e); if (size++ >= threshold) resize(2 * table.length); Why object e gets the address (or what happens here?) of table[bucketIndex] and then this table[bucketIndex] get the new Entry(hash, key, value, e)? What is the reason, why didn't just use what is below? Entry<K,V> e = new Entry<K,V>(hash, key, value) table[bucketIndex] = e; A: Because there could be collisions in the HashMap (i.e. different keys which produces the same bucketIndex). If they did what you suggests, in the case of a collision, the last inserted element would delete the previous ones in the case of a collision, possibly in a virtually unpredictable manner. The Entry is implemented as some sort of linked list, so it is actually a bit misnamed and is in fact a node of linked list of entries. This is the reason why e is passed as the last parameter of Entry constructor. Creating a new Entry that refers to the previous one (the e) and adding it in the same place where the e was is the operation of inserting a new node in the beggining of the linked list, and works even if e was null (i.e. there was no collision at all and the created Entry is the first one with the given bucketIndex).
{ "pile_set_name": "StackExchange" }
Q: Web Services for Checking Malicious Domains Does anyone know of any freely available web services or APIs which accept a website URL and check this URL against a list of known malicious websites? I was thinking of designing something similar to Web of Trust (WOT) to give you an idea? A: There are many, you can start with Google's Safe Browsing
{ "pile_set_name": "StackExchange" }
Q: Desktop Browsers Not Working, but "Metro" Internet Explorer Works (Windows 8) I'm trying to help my dad fix his computer after he inadvertently downloaded and installed a bundle of 15 spyware/malicious programs (which he has since uninstalled via the Control Panel). However, Windows is unable to complete a system restore and Windows Defender isn't picking up on anything. The only symptom seems to be that all browsers (IE 11, Chrome, Firefox) in "Desktop" mode are unable to connect to the Internet (displaying the classic "Internet Explorer cannot display the webpage", etc.). We know the internet connection does work because he is able to use Skype and the "Metro" version of Internet Explorer works fine. We tried all the suggestions on the Microsoft website below, but none seemed to help (I initially thought it would be some kind of proxy issue but it doesn't seem to be). http://support.microsoft.com/kb/956196 I'm not very familiar with Windows 8 (my system runs 7) or dealing with spyware-related issues, so I was hoping one of you might have some tips. I really appreciate any help you can provide. A: You realize that the virus/spyware might have infected the computer even after the removal of the stuff in the control panel. Realize that you might be looking at doing a FULL restore from the last known good backup (hopefully you are smart enough to make these -- even on home systems). Your final resort would be to reinstall from scratch to ensure all problems are taken care of and no residual of any virus/spyware is present. Good luck.
{ "pile_set_name": "StackExchange" }
Q: Открытие fragment Данный код позволяет выдвигать шторку с меню, пока никакой пункт меню не выбран, главное активити пустует. Как при открытии приложения сразу открывать фрагмент. public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { DialogF dialogF; String savedLogin,savedPass; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); dialogF = new DialogF(); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); //FragmentTransaction ftranse = getFragmentManager().beginTransaction(); android.support.v4.app.FragmentTransaction ftranse = getSupportFragmentManager().beginTransaction(); if (id == R.id.nav_camera) { ftranse.replace(R.id.conteiner,dialogF); } else if (id == R.id.nav_gallery) { } else if (id == R.id.nav_slideshow) { } else if (id == R.id.nav_manage) { } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { }ftranse.commit(); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } вот так я заменюя фрагменты и не знаю как правильней решить данную задачу ftranse.replace(R.id.conteiner,dialogF); думал в конце условий дописать ... } else if (id == R.id.nav_send) { }else{ реплейс фрагмент } но не сработало A: добавьте код вставки фрагмента в самый низ метода onCreate() вашей активити @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ................... //чтобы предовратить переход при пересоздании активити из-за поворота if (savedInstanceState == null) { getSupportFragmentManager() .beginTransaction() .replace(R.id.conteiner,dialogF) .commit(); } }
{ "pile_set_name": "StackExchange" }
Q: why is my gps getting "hung up?" I am trying to implement a gps location listener that will stay on and continuously update in the background. I realize this is bad practice but I am doing this for testing purposes. Right now I have a location listener that gets called with getGPS(). It can also be killed with killGPS(). It works perfectly when im walking around and I click my get gps button which takes the latitude and longitude from my location parameter which I get from GPSActivity.getGPS(); loc_listener = GPSActivity.loc_listener; locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, loc_listener); location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); However in the background, sometimes it will say I'm still at my apartment even though I've been out for 3hours! Why is my location listener not updating itself even though it turns on to find a new location every 10 mins? Thanks package com.cellphone; import android.app.Activity; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; public class GPSActivity extends Activity{ public static LocationListener loc_listener = null; public static void getGPS() { if (loc_listener == null) { loc_listener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onLocationChanged(Location location) { // TODO Auto-generated method stub } }; } } public static void killGPS(LocationManager locationManager) { if (locationManager != null && loc_listener != null) { locationManager.removeUpdates(loc_listener); } } } A: for location poller, here is simple & working example: https://github.com/commonsguy/cwac-locpoll you can keep state of your app by adding a function in Application context. So to say, location poller can be aware of app-state and skip gps action if app is not active.
{ "pile_set_name": "StackExchange" }
Q: Why 1 mole of H2 occupied the same volume occupied by 1 mole of O2? I'm asking a question about the volume occupied by gasses in standard temperature and pressure. My textbook said that a mole of any gas occupies $\pu{22.4 L}$ at standard temperature and pressure. But $\ce{O2}$ is greater than $\ce{H2}$ in size I asked my teacher why the volume occupied by 1 mole of $\ce{H_2}$ is equal to the volume occupied by $\ce{O_2}$ at standard temperature and pressure, but he seemed to not know the answer, and I remain confused. Please answer in simple words. A: The volume occupied by a gas has no relationship to the size of the molecules of the gas This is one of the principles of the gas laws in chemistry. It is based on observation: in the early days of chemistry it is what chemists observed to be true. And it is a very important chemical law. But, of course, that doesn't explain why it is true. There are several ways to gain some appreciation of this without too much theory. consider water as a liquid compared to water as a gas (I'm simplifying a bit but not by much). One mole of liquid water occupies about 18mL of space and this space is largely dominated by the size of the water molecule (again reality is a little more complex as the specific way the molecules interact makes a small difference to the volume occupied). As water vapour (the same substance but as a gas) 1 mole of water occupies over 22L of space (ignoring the fact that water is not a gas at STP, but bear with me as this is the space it would occupy if it were). That is well about 1200 times more space. This implies that very little of the space occupied has anything to do with how big the water molecule is. The same broad idea applies to all gases. So why does the molecular size not matter? A detailed understanding requires a fair few calculations about how gas molecules behave. But, the bottom line involves thinking about the molecular cause of pressure and the meaning of temperature. Pressure is caused by gas molecules bouncing off the walls of a vessel. Temperature is the average energy of those molecules which is a function of their speed and their mass. Doing the calculations shows the relationship between volume, pressure and temperature. This calculation explains the properties of gases but the volume of the molecules has no part. Strictly speaking the ideal gas laws assume that the size of molecules don't matter. But this is a good approximation when the gases are far away from the point where they become liquids. The simplified theory matches actual observations well. And the fact that, in typical gases, the volume occupied by the molecules is less than 0.1% of the volume occupied by the gas shows why the molecular volume is usually irrelevant.
{ "pile_set_name": "StackExchange" }
Q: in laravel how to search and display student data in view by using 2 input filed "id" and and "date of join" Present i created single input filed "id" if enter valid id it showing student ( name, email, Id). this is working Perfectly. now i what to add one more input filed "date of join" in this function i what to check input "id" and "date of join", is mach then show student data in view, or else it show ("data not found") message MY VIEW <form action="/search" method="POST" role="search"> {{ csrf_field() }} <div class="input-group"> <input type="text" class="form-control" name="id" placeholder="Search users"> <span class="input-group-btn"> <button type="submit" class="btn btn-default"> <span class="glyphicon glyphicon-search"></span> </button> </span> </div> </form> <div class="container"> @if(isset($details)) <p> The Search results for your query <b> </b> are :</p> <h2>Sample User details</h2> <table class="table table-striped"> <thead> <tr> <th>Name</th> <th>Email</th> <th>id</th> <th>Photo</th> <th>certificate_approval</th> </tr> </thead> <tbody> @foreach($details as $user) <tr> <td>{{$user->student_name}}</td> <td>{{$user->email}}</td> <div class="card-body"> <img src="STUDENT_DATA/STUDENT_PHOTO/{{ $user->student_photo }}" class="img-circle" width="90" /> </div> <td>{{$user->student_registration_id}}</td> <td>{{$user->student_certificate_approval}}</td> </tr> @endforeach </tbody> </table> @elseif(isset($message)) <p>{{$message}}</p> @endif </div> MY ROUTE use App\Student; use Illuminate\Support\Facades\Input; Route::any( '/search', function(){ $id = Input::get( 'id' ); if($id != ""){ $user = Student::where( 'student_registration_id', 'LIKE', '%' . $id . '%' )->get(); if (count ( $user ) > 0) return view( 'my-search' )->withDetails( $user )->withQuery($id); } return view ( 'my-search' )->withMessage ( "No Details found!" ); } ); MY MODEL <?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Database\Eloquent\Model; class Student extends Model { protected $table = 'student_lists'; protected $fillable = ['student_name', 'student_registration_id', 'date_of_join', 'student_phone_no', 'student_photo', ]; } A: As you said "input id and date of joining". Both match then student details show. $user = Student::where( 'student_registration_id', 'LIKE', '%' . $id . '%' ) ->where('date_of_join', 'LIKE', '%' . $date_of_join . '%') ->where('approved', 'APPROVE') ->get(); if(!empty($user)){ return view( 'my-search' )->withDetails( $user )->withQuery($id); } else { return view ( 'my-search' )->withMessage ( "No Details found!" ); }
{ "pile_set_name": "StackExchange" }
Q: why zero not going to database when its type integer? can I know why it is not inserting zero to my database when its type in integer. I have a table called contact and there is a column to keep users' 10 digits length mobile no. This number generally start with 0. Eg. 0713423454, 0234324545 etc. In my table I have create that column like this.. mobile INT(10) NOT NULL, In php I validate it something like this... // Check for a mobile number: if ( !empty($_POST['mobile'])) { $number = $_POST['mobile']; if (preg_match('/(0[0-9]{9})/', $number)) { $mobile = mysqli_real_escape_string ( $dbc, $number); } else { $reg_errors['mobile'] = 'You are NOT entered valid Mobile number!'; } } else { $reg_errors['mobile'] = 'Mobile number can not be empty!'; } But when inserting mobile number to database its going without 0 like this 234223434, 435453545 etc. So I would like to know is there a way to insert my mobile number with 0 to database.. Thank you. A: Integers do not (cannot) have leading zeros. That is, both '099' and '99' represent the same numeric value1. Use a char or varchar instead. 1 Sometimes a leading zero in the text-representation of a number specifies the [octal] base, but that is not the case here. A: Use zerofill for your column.. A: You cannot store leading zeros, but your larger problem is that you should not store a mobile number as INT. Store it as CHAR. Mobile numbers are identifiers, not numeric values. You'll save yourself a lot of grief if you alter your data model.
{ "pile_set_name": "StackExchange" }
Q: How can I connect geom_segment to geom_line? I would like to connect a segment from the bottom of the graph until it intersects with the geom_line at a given x. I think the best way to do this is with geom_segment. How do I programmatically find where geom_line will be for a given x? How can I expand this framework to support faceting? mtcars %>% ggplot(aes(hp, wt)) + geom_line() + geom_segment(aes(x = 150, y = 0, xend = 150, yend = 3.248397), col = "red") A: For this specific case this should work: mtcars %>% ggplot(aes(hp, wt)) + geom_line() + geom_segment(aes(x = 150, y = 0, xend = 150, yend = min(mtcars[mtcars$hp == 150, "wt" ])), col = "red") If you want it for a x that does not exist int the data you would have to interpolate. For all available x values and with faceting: library(dplyr) df <- mtcars %>% select(hp, wt, vs) %>% group_by(hp, vs) %>% summarise(min_wt = min(wt)) mtcars %>% ggplot(aes(hp, wt)) + geom_line() + geom_segment( aes(x = hp, y = 0, xend = hp, yend = min_wt),data = df, col = "red") + facet_grid(vs ~ .)
{ "pile_set_name": "StackExchange" }
Q: How to distinct grok filter for similar logs I have this to kind of logs for dhcpack: Jun 30 06:34:18 HOSTNAME dhcpd: DHCPACK to IP (MAC) via eth2 Jun 30 06:34:28 HOSTNAME dhcpd: DHCPACK on IP to MAC via eth2 How can I use grok, to use two different matches? I have these two matches for dhcpack, but just use the first: ((%{SYSLOGTIMESTAMP:timestamp})\s*(%{HOSTNAME:hostname})\sdhcpd\S+\s(%{WORD:dhcp_action})?.[for|on] (%{IPV4:dhcp_client_ip})?.[from|to] (%{COMMONMAC:dhcp_client_mac})?.*via (%{USERNAME:interface})) ((%{SYSLOGTIMESTAMP:timestamp})\s*(%{HOSTNAME:hostname})\sdhcpd\S+\s(%{WORD:dhcp_action})?.*[to] (%{IPV4:dhcp_client_ip})?.*via (%{USERNAME:interface})) Someone can help? A: I solve the problem with this: filter { grok { match => ["message", "(dhcpd\S+\s*(%{WORD:dhcp_action_test}))"] } if "DHCPINFORM" in [message] { grok { match => ["message","((%{SYSLOGTIMESTAMP:timestamp})\s* (%{HOSTNAME:hostname})\sdhcpd\S+\s(%{WORD:dhcp_action})?.[from] (%{IPV4:dhcp_client_ip}))"] } } else if "DHCPDISCOVER" in [message] { grok { match => ["message","((%{SYSLOGTIMESTAMP:timestamp})\s(%{HOSTNAME:hostname})\sdhcpd\S+\s(%{WORD:dhcp_action})?.*[from] (%{COMMONMAC:dhcp_client_mac})"] } } else { drop {} } }
{ "pile_set_name": "StackExchange" }
Q: Google Column Chart with string labels I did this chart with Adobe Flex and I have to redo it with Javascript: I've found Google Chart Tools, but after some investigation, I don't know if I can have string labels at the vertical column. Do you know how can I do it? Thanks A: Not sure if you want the labels on the Y axis or on the column itself although Highcharts.js does that and pretty much anything you want, check out this demo: http://www.highcharts.com/demo/column-rotated-labels
{ "pile_set_name": "StackExchange" }
Q: How can I get my comments restored? I had this comment exchange on this answer: https://scifi.stackexchange.com/a/68242/16835 but at some point some of my comments were deleted. Now, another comment refers to one of deleted comment, and then I answer again - but the context is lost since my original comments are missing. What can/should I do to get them restored? (For now I'm just reposting them) A: If the comments that are left on that answer are indicative of the ones that were deleted, I doubt there's any chance of them coming back. Comments are meant to provide feedback to improve questions and answers. They are intended to be temporary and fleeting. There is a very low bar for deleting comments, and once they are gone, that's it. If they were deleted in the first place, it's likely because someone found them to be unrelated to the purpose of improving the answer; for example, the current thread has devolved into discussion of the legal intricacies of murder in different jurisdiction. I wouldn't be surprised if they got deleted again.
{ "pile_set_name": "StackExchange" }
Q: Saving JSON to text file I have a form. The user adds the title and video URL on a page. This title and URL is read by Javascript and made into JSON. Now my JSON needs to be saved into existing myDB.txt file in JSON format. I'm using Ajax, PHP, and Javascript. I can't find my error, as JSON is created, I can see it with console log. However, data is not being saved in the text file. Can someone help me with this task? function jsonFunc() { var nn = document.getElementById('videoName').value; var vv = document.getElementById('videoUrl').value; var obj = { "name": nn, "url" : vv }; var myJSON = JSON.stringify(obj); console.log(myJSON); function savePHPfunc(myJSON){ var x=new XMLHttpRequest(); x.open("GET", "save.php="+myJSON, true); x.send(); } } <?php $myfile = fopen("myDB.txt", "a") or die("Unable to open file!"); $txt = $_GET["myJSON"]; fwrite($myfile, $txt); fclose($myfile); ?> <form> <input type="text" name="videoName" id="videoName">Video name <input type="text" name="videoUrl" id="videoUrl">Video <button type="submit" onclick="jsonFunc()">Add video</button> </form> _ A: Assuming that the php is not really commented out, the problem seems to be with the javascript: x.open("GET", "save.php="+myJSON, true); You are not sending the key with the value of your variable. It should be something like: x.open("GET", "save.php?myJSON="+myJSON, true); Note that you should also encode the variable so that it is safe to use as a query variable in your url. You can do that using encodeURIComponent(): x.open("GET", "save.php?myJSON="+encodeURIComponent(myJSON), true);
{ "pile_set_name": "StackExchange" }
Q: Can I encounter memory leaks when using vectors of classes? (C++) I'm using numerous vectors in a program and I want to avoid memory leaks. Here is an example of a vector containing classes I have created myself. vector<MyClass> objects; objects = vector<MyClass>(10); As you can see, I haven't used the "new" operator and the vector is not of a pointer type. Will I still encounter memory leaks without deleting the vector in some way? If so, how can I delete the vector and deallocate the memory? A: No, you won't encounter directly a memory leaks related to the vector this way. Indeed, objects is a variable with automatic storage duration. What this means is that the variable you created will live in the scope you created it. If you've created it in a function, and if/for/while/etc scope or even a raw block scope, it will be cleaned up at the end of this same scope, without the need for any actions from your part. Then, nothing is preventing your class itself from leaking, e.g. if you have ownership of some memory and don't release it as an instance of your class go away.
{ "pile_set_name": "StackExchange" }
Q: Change visual of histogram from image using matplotlib in Python I would like to present a histogram from an image in Python. Doing some research, I found a way of doing it using matplotlib. So, I just do this: im = plt.array(Image.open('Mean.png').convert('L')) plt.figure() plt.hist(im, facecolor='green', alpha=0.75) plt.savefig("Histogram.png") But I didn't like what I got: The bars are not green, and it's kind of complicated to read the histogram. I could not even figure out if the x axis is the number of points and y axis the rgb color or the inverse... :S I would like to know if somebody knows how could I turn this histogram more readable. Thanks in advance. A: To get the histogram you have to flatten your image: img = np.asarray(Image.open('your_image').convert('L')) plt.hist(img.flatten(), facecolor='green', alpha=0.75) Since you converted the image to grayscale with convert('L') the x axis is the grayscale level from 0-255 and the y axis is the number of pixels. You can also control the number of bins using the bins parameter: plt.hist(img.flatten(), bins=100, facecolor='green', alpha=0.75)
{ "pile_set_name": "StackExchange" }
Q: How to cancel time conversion in librecalc? Whenever I add an "hour" entry on a LibreOffice Calc field, it converts into a full hour format after I hit Enter. e.g. I get the following conversion: 17:00 => 05:00:00PM Any idea how to disable this? A: Just select a different time format to format the time value: select the cells to format right-click on them select "Format Cells..." From the leftmost listbox ("Category"), select "Time" From the listbox in the middle ("Format"), select the appropriate entry.
{ "pile_set_name": "StackExchange" }
Q: Linking Native/C++ DLL to Managed C++/CLI Wrapper in Visual Studio 2010 In my visual studio solution I have a dll containing native C++ code, a C++/CLI dll where I am trying to implement a wrapper for my unmanaged types, and finally my C# application. I am currently unable to reference my unmanaged types in my wrapper dll. Code Snippet: // In the unmanged file (in the unmanged dll project) using std::vector; namespace populationwin32 { class PopulationWin32 { public: PopulationWin32(); // ... }; } // In the managed file. (in the manged dll project) using namespace system; using populationwin32::PopulationWin32; namespace GSODFileParsing { public ref class PopulationWin32Wrapper { public: PopulationWin32Wrapper(); private: PopulationWin32 *_populationWin32; // unmanaged object }; // End class } // End namespace When I try to compile the managed dll (containing the wrapper) I get the following errors: Error 1 error C2653: 'populationwin32' : is not a class or namespace name Error 2 error C2873: 'PopulationWin32' : symbol cannot be used in a using-declaration Error 4 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Any ideas what these errors mean? I'm thinking they are from not correctly linking to the unmanged dll, but I'm not sure how to do this and everything I find online says something different. Any body know how to correctly and completely link an unmanged library (dll project) with a managed VC++/CLI wrapper library (dll project)? Note: Both these libraries are projects in a single visual studio solution. Edit: Thanks to Olaf Dietsche's comments I added #include "PopulationWin32.h" To the wrapper header file but now I get the following error: Error 1 error C1083: Cannot open include file: 'PopulationWin32.h': No such file or directory Is there a setting I'm missing or do I need to include the header file in both DLL projects? BTW, I added the unmanged dll output .lib file as a dependency to the managed dll via properties->configuration properties->linker->input->Additional Dependencies. A: Your first error 'populationwin32' : is not a class or namespace name means, the compiler has no knowledge about this namespace. Add an #include "PopulationWin32.h" to make this known to Visual Studio. You also must add the path to your include file, so the compiler can find it. This is described here VC++ Directories, Projects and Solutions, Options Dialog Box and here The #include Directive, for example.
{ "pile_set_name": "StackExchange" }
Q: Android Market Billing System There is issue with android market. I'm in country where I am not allowed to get funds from android market. There is solution for that: App is free and distributed via android market, but goods for software will be sold via some payment processor located on a web site. Is this legal solution? A: See section 3.3 of the Market developer distribution agreement: http://www.android.com/us/developer-distribution-agreement.html (The selector to see the version of the agreement for your country is in the upper right corner of the page.)
{ "pile_set_name": "StackExchange" }
Q: Can't access method server on mobile side or via REST I have already asked this question, but the previous method I used was created in 4D. This time I created a new class in Wakanda and a new datastore class method. I know how to use it in mobile side, but it won't works, so I try to call it via REST and I have this following message : "{"__ERROR":[{"message":"The \"method1\" attribute cannot be found in The \"TEST\" datastore class","componentSignature":"dbmg","errCode":1500},{"message":"The \"method1\" attribute cannot be found in The \"TEST\" datastore class","componentSignature":"dbmg","errCode":1500},{"message":"Error code: 1804\nCannot completely build a list of attributes with \"method1\" for the \"TEST\" datastore class\ncomponent: 'dbmg'\ntask 7963, name: 'HTTP connection handler'\n","componentSignature":"dbmg","errCode":1804}]}" My method is in public scope, and I can access to the datastore class TEST via REST. Can someone tell me how I can use this method, or what to do to correct this error ? Thanks in advance. A: This error indicates the method1 is not publicly available under table TEST. I tested and get the same exact error when the method scope is not set to public. Please double check the code to change scope is correct, like following: model.DataClass1.methods.method1.scope = 'public' And see if method1 is indeed published in table TEST by accessing http://127.0.0.1:8081/rest/$catalog/TEST/ The response JSON should have method1 in its methods property:
{ "pile_set_name": "StackExchange" }
Q: AWS Cognito prevent creating duplicate phone number While registering users in AWS Cognito user pool we are choosing the option to "allow email addresses" as the username to sign up and sign in. In the required attributes there is also phone number. But the same phone number can be used again for another user, while the email id is unique. Is there any way to stop the phone number being duplicated,so that both the phone number and email id is unique for each user? A: You can use Pre-Signup Lambda trigger to check whether the phone number is already in use and handle accordingly.
{ "pile_set_name": "StackExchange" }
Q: How to render the same component repeatedly with the same prop? I have a component that renders an Icon component many times. function MyComponent(props) { return( <IconStar/> <IconStar/> <IconStar/> <IconStar/> ); } I'm looking for a way to make something like: function MyComponent(props) { const IconStarWithProp = (<IconStar size="2rem"/>); return( <IconStarWithProp/> <IconStarWithProp/> <IconStarWithProp/> <IconStarWithProp/> ); } How can I do such thing? Do I have to use a HOC or is there a better way? A: const IconStarWithProp = (<IconStar size="2rem"/>) isn't a correct way to do this because IconStarWithProp is React element, not React component, it cannot be used as a <IconStarWithProp/> component, and reusing it as {IconStarWithProp} element may result in problems. This is the case for wrapper component, it can be defined outside component function: const IconStarWithProp = () => <IconStar size="2rem"/>; function MyComponent(props) { return <> <IconStarWithProp/> <IconStarWithProp/> <IconStarWithProp/> <IconStarWithProp/> </>; } MyComponent can be shortened for multiple IconStarWithProp: function MyComponent(props) { return Array(4).fill().map(() => <IconStarWithProp/>) } A: It's not viable make a other component only for render with specific props function MyComponent(props) { return Array(4).fill().map(() => <IconStar size="2rem"/> ); } the 4 of the Array you can use a props to render number of that component
{ "pile_set_name": "StackExchange" }
Q: Natural logarithm Can someone please suggest how one proves: $(1+2x)\ln(1+\frac{1}{x}) -2 >0$ where $x>0$. I plotted the function in a program and the inequality should be correct. A: Here is one approach. Let $f(x)=(1+2x)\ln(1+\frac{1}{x})$. You can show that $\lim\limits_{x\to+\infty}f(x)=2$, for example using l'Hôpital's rule, with a rewrite as $\dfrac{\ln\left(1+\frac{1}{x}\right)}{\left(\dfrac{1}{1+2x}\right)}$. You can show that $f$ is always decreasing by showing that $f'$ is always negative. In case working directly with $f'$ is too cumbersome, it turns out to be easy to show that $f''$ is always positive, and then it would suffice to show that $\lim\limits_{x\to+\infty}f'(x)=0$.
{ "pile_set_name": "StackExchange" }
Q: How to pass an argument to a button click function inside bootstrap popover content? I have a list of box objects and I am making each of them has a popover window. I add a button inside my popover window and I am trying to set the click event function for the button. The click function show invoke my showBox(box) function which takes an argument box. How can I pass this box argument to the button inside the popover window? Here is the code I have now: var tabindex = 0; box_resources.forEach(function(box) { var title = truncateTitle(box.title); var title_button = '<a tabindex="' + tabindex + '" class="box-title-item btn btn-primary btn-xs" role="button" data-trigger="focus" style="margin:5px" data-toggle="popover">' + title + '</a>'; var $list_item = $(title_button); $("#coverages-master-list").append($list_item); var show_box_button = '<a class="btn btn-primary" role="button">' + box.title + '</a>'; $list_item.popover({ html: true, placement: 'top', title: box.title, content: '<p>' + show_box_button + '</p>', trigger: 'focus' }); tabindex++; }); How can I bind a click event for my show_box_button and how can I make it invoke my showBox(box) function which takes an argument box? Thanks! Here is the jsfiddle link. A: You can use the popover .on('shown.bs.popover'... event to add your click event to the current popover button make sure to use .one('click'... here not .on('click'... and then call your showBox function with the box_resources array adding the tabindex of the current element. $(function () { var $coveragesMasterList = $("#coverages-master-list"); var showBox = function(box) { console.log(box.title); } var box_resources = [ { title: 'Box A' }, { title: 'Box B' }, { title: 'Box C' }, { title: 'Box D' }, { title: 'Box E' } ]; var tabindex = 0; box_resources.forEach(function(box) { var title_button = '<a tabindex="' + tabindex + '" class="box-title-item btn btn-primary btn-xs" role="button" data-trigger="focus" style="margin:5px" data-toggle="popover">' + box.title + '</a>'; var $list_item = $(title_button); $coveragesMasterList.append($list_item); var show_box_button = '<a class="btn btn-default btn-xs" role="button">' + box.title + '</a>'; $list_item.popover({ html: true, placement: 'top', title: box.title, content: '<p>' + show_box_button + '</p>', trigger: 'focus' }); $list_item.on('shown.bs.popover', function () { var boxIndex = $(this).attr('tabindex'); var $crntPopOver = $(this).next(); var $crntPopOverBtn = $crntPopOver.find('.btn-default'); $crntPopOverBtn.one('click', function() { showBox(box_resources[boxIndex]); }) }) tabindex++; }); }); @import url('https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css'); body { margin-top: 100px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script> <div id="coverages-master-list" style="display:inline-block; height:150px; overflow-y: auto"></div>
{ "pile_set_name": "StackExchange" }
Q: Este programa em Tkinter nao exibe seus widgets. Alguem pode explicar porque? from tkinter import * class Autenticar(object): def __init__(self, toplevel): self.Lab1 = Label(main, text = "Usuário", fg = "Blue") self.Lab1.pack() self.Entr1 = Entry(main) self.Entr1.pack() self.Lab2 = Label(main, text = "Senha", fg = "Blue") self.Lab2.pack() self.Entr2 = Entry(main) self.Entr2.pack() self.Bot1 = Button(main, text = "Confirmar", fg = "Black", command = self.AcessoNegado ) self.Bot1.pack() def AcessoNegado(self): self.Entr1.get() self.Lab1["text"] = "Usuario Invalido" self.Lab1["fg"] = "Red" main = Tk() main.geometry("250x250") main.title("Autenticar") A: Tu estavas a definir/configurar os teus widgets na tua class Autenticar mas não estavas a instancia-la em lado nenhum, melhorei um bocado a estrutura do teu código, faz assim: from tkinter import * class Autenticar(): def __init__(self): self.main = Tk() self.mount_gui() def mount_gui(self): self.main.geometry("250x250") self.main.title("Autenticar") self.Lab1 = Label(self.main, text = "Usuário", fg = "Blue") self.Lab1.pack() self.Entr1 = Entry(self.main) self.Entr1.pack() self.Lab2 = Label(self.main, text = "Senha", fg = "Blue") self.Lab2.pack() self.Entr2 = Entry(self.main) self.Entr2.pack() self.Bot1 = Button(self.main, text = "Confirmar", fg = "Black", command = self.AcessoNegado ) self.Bot1.pack() self.main.mainloop() def AcessoNegado(self): self.Entr1.get() self.Lab1["text"] = "Usuario Invalido" self.Lab1["fg"] = "Red" Autenticar() Estive a divertir-me um pouco com isto, e fiz um exemplo funcional de acertar/falhar as credênciais (user: Jefferson_Andr, pass: password): from tkinter import * class Autenticar(): def __init__(self): self.main = Tk() self.password = 'password' self.usuario = 'Jefferson_Andr' self.mount_gui() def mount_gui(self): self.main.geometry("250x250") self.main.title("Autenticar") self.Lab1 = Label(self.main, text = "Usuário", fg = "Blue") self.Lab1.pack() self.Entr1 = Entry(self.main) self.Entr1.pack() self.Lab2 = Label(self.main, text = "Senha", fg = "Blue") self.Lab2.pack() self.Entr2 = Entry(self.main) self.Entr2.pack() self.Bot1 = Button(self.main, text = "Confirmar", fg = "Black", command = self.auth ) self.Bot1.pack() self.main.mainloop() def auth(self): if(self.Entr1.get() != self.usuario or self.Entr2.get() != self.password): self.AcessoNegado() return None self.AcessoPermitido() def AcessoPermitido(self): self.Entr1.get() self.Lab1["text"] = "Olá {}".format(self.usuario) self.Lab1["fg"] = "Green" def AcessoNegado(self): self.Entr1.get() self.Lab1["text"] = "Usuario Invalido" self.Lab1["fg"] = "Red" Autenticar()
{ "pile_set_name": "StackExchange" }
Q: RSpec: NameError: uninitialized constant I am new in RSpec and I'd just like to test my controller. I wrote my test that way: RSpec.describe ServicesController do describe "GET index" do it "renders the index template" do get :index expect(response).to render_template("index") end end end But my controller isn't recognized by RSpec, I get this error: NameError: uninitialized constant ServicesController In found examples I can find require line, which maybe could solve this problem, but as far as I can see, it concerns only files in lib folder, while my controller path is app/controllers/services_controller.rb. I tried to add it with path ../app/controllers/services_controller.rb, going out from lib folder, but that doesn't work. What should I do? That's very basic case, but I wasn't able to find any help on the Web. A: You may miss require rails_helper at the beginning of your specs: require 'rails_helper'
{ "pile_set_name": "StackExchange" }
Q: How to run assembly in gdb directly? I can use call to run c functions ,but how to run assembly or even shell code directly? A: To execute shell code, you can edit a function's contents directly: (gdb) b foo Breakpoint 1 at 0x400608 (gdb) run Breakpoint 1, 0x0000000000400608 in foo () (gdb) x/16bx foo 0x400604 <foo>: 0x55 0x48 0x89 0xe5 0x53 0x48 0x81 0xec (gdb) set ((unsigned char *)foo)[6] = 0x85 (gdb) x/16bx foo 0x400604 <foo>: 0x55 0x48 0x89 0xe5 0x53 0x48 0x85 0xec (gdb) cont I don't know how to execute opcodes from within gdb, but you can certainly do whatever you want with registers. For instance, instead of mov %rbx, %rax you can use set $rax = $rbx: (gdb) p $rax $1 = 3671197290184 (gdb) set $rax = $rbx (gdb) p $rax $2 = 0 (gdb)
{ "pile_set_name": "StackExchange" }
Q: C# Html parsing I'm trying to parse HTML in my C# project without success, I am using a HtmlAgilityPack lib to do so, I can get some of the HTML body text but not all of it for some reason. I need to grab the div with ID of latestPriceSection, and filter to the USD value from https://www.monero.how/widget My function (doesn't work) public void getXMRRate() { HtmlWeb web = new HtmlWeb(); HtmlAgilityPack.HtmlDocument document = web.Load("https://www.monero.how/widget"); HtmlNode[] nodes = document.DocumentNode.SelectNodes("//a").Where(x => x.InnerHtml.Contains("latestPriceSection")).ToArray(); foreach (HtmlNode item in nodes) { Console.WriteLine(item.InnerHtml); } } A: Your function doesn't work because the widget is updated via script. The div contains nothing when you load the page. You can't use HAP to scrape the information of this. Find a web service that can give you the information you need. Alternatively you can use Selenium to get the HTML after the page has loaded the script. Or you the WebBrowser class, but that requires you to have a form application where the form contains the WebBrowser.
{ "pile_set_name": "StackExchange" }
Q: HR tag stays hidden while containing div is shown with jquery I have a hidden div which I reveal with the jquery fadein() method: $("#panel").fadeIn("slow"); and here's the html: <div id="panel" style="display:none;"> <hr/> <p>text</p> <button onclick="cancel()">cancel</button> </div> The text and the button within the panel is shown properly when the method is called but the hr stays hidden. Its display property is none according to firebug. Why the HR is not shown together with the other elements? It's jquery 1.3.2 A: I copied your markup and jQuery, and it fades in fine for me. However, if I add the following CSS rule, it does not fade in correctly... hr { display: none; } So you must have this rule somewhere. Remove it and your fade will work as expected.
{ "pile_set_name": "StackExchange" }
Q: Why is subprocess module giving me WinError193? I'm trying to open notepad with subprocess module but an error occurs. import subprocess subprocess.Popen(r'C:\Users\user\Desktop\notepad.lnk') Error: Traceback (most recent call last): File "C:\Python36\kodovi\proba.py", line 2, in <module> subprocess.Popen(r'C:\Users\user\Desktop\notepad.lnk') File "C:\Python36\lib\subprocess.py", line 709, in __init__ restore_signals, start_new_session) File "C:\Python36\lib\subprocess.py", line 997, in _execute_child startupinfo) OSError: [WinError 193] %1 is not a valid Win32 application A: It's clear from the error that shortcuts are not considered application by subprocess. The following code can be used to launch a shortcut - subprocess.Popen(r'start C:\Users\user\Desktop\notepad.lnk', shell=True)
{ "pile_set_name": "StackExchange" }
Q: Implementing Redux Form FieldArray in admin-on-rest My schema has a field which is an unlimited array of textfields. I want to do exactly what the example here at the end shows: http://redux-form.com/6.5.0/docs/api/FieldArray.md const renderSubFields = (member, index, fields) => ( <li key={index}> <button type="button" title="Remove Member" onClick={() => fields.remove(index)}/> <h4>Member #{index + 1}</h4> <Field name={`${member}.firstName`} type="text" component={renderField} label="First Name"/> <Field name={`${member}.lastName`} type="text" component={renderField} label="Last Name"/> </li> ) const renderMembers = ({ fields }) => ( <ul> <button type="button" onClick={() => fields.push({})}>Add Member</button> {fields.map(renderSubFields)} </ul> ) I imagine this is a fairly common thing to do but I don't see anything like this in the AOR docs or demo. Are there any examples that I'm missing? A: I think you meant EmbeddedManyInput that desribed in https://github.com/marmelab/admin-on-rest/issues/695
{ "pile_set_name": "StackExchange" }
Q: How do I set/get the volume level with Core Audio? I want to be able to get and set the system volume level with Core Audio. I've followed the code on this other thread: objective c audio meter However, my call to AudioHardwareServiceHasProperty to find the kAudioHardwareServiceDeviceProperty_VirtualMasterVolume property returns false. Why is this happening, and how do I get around it? What approach should I take to getting and setting the system volume level with Core Audio? A: Have you tried kAudioDevicePropertyVolumeScalar: UInt32 channel = 1; // Channel 0 is master, if available AudioObjectPropertyAddress prop = { kAudioDevicePropertyVolumeScalar, kAudioDevicePropertyScopeOutput, channel }; if(!AudioObjectHasProperty(deviceID, &prop)) // error Float32 volume; UInt32 dataSize = sizeof(volume); OSStatus result = AudioObjectGetPropertyData(deviceID, &prop, 0, NULL, &dataSize, &volume); if(kAudioHardwareNoError != result) // error
{ "pile_set_name": "StackExchange" }
Q: Eigenvector (Spectral) Decomposition I am trying to find a program in C code that will allow me to compute a eigenvalue (spectral) decomposition for a square matrix. I am specifically trying to find code where the highest eigenvalue (and therefore its associated eigenvalue) are located int the first column. The reason I need the output to be in this order is because I am trying to compute eigenvector centrality and therefore I only really need to calculate the eigenvector associated with the highest eigenvalue. Thanks in advance! A: In any case I would recommend to use a dedicated linear algebra package like Lapack (Fortran but can be called from C) or CLapack. Both are free and offer routines for almost any eigenvalue problem. If the matrix is large it might be preferable to exploit its sparseness e.g. by using Arpack. All of these libraries tend to sort the eigenvectors according to the eigenvalues if they can (real or purely imaginary eigenvalues).
{ "pile_set_name": "StackExchange" }
Q: how to find row from numeric cell that contain target vector in Matlab? I have cell array that is as follow: S{1} = [10,20,30,40,50]; S{2} = [10,20,40,50]; S{3} = [10,50,510]; S{4} = [10,20,70,40,60]; S{5} = [20,40]; and,i have a target vector: T=[10,70] i need to find rows of cell that T is subitem of those. for above example result is : 4 because T is subitems of row 4. A: Get the count of matches for each cell against T and see which cells have a match count being equal to the number of elements in T, indicating that those cells have all elements from T. The assumption here is that we have unique elements in each of those cells. Here's the implementation - find(cellfun(@(x) nnz(ismember(x, T)), S) == numel(T)) Or as suggested by @Leander Moesinger we can get the matches for each element off T across all elements in each cell and then simply use all(), like so - find(cellfun(@(x) all(ismember(T,x)),S))
{ "pile_set_name": "StackExchange" }
Q: Property change subscription with Aurelia I have a property on my viewmodel which I want to listen to and trigger events based on its value, like this: class viewModel { constructor() { this.value = '0'; let val = 2; subscribe(this.value, callbackForValue); subscribe(val, callbackForVal); } } Is this a feature of Aurelia? If so, how would I go about setting up such a subscription? A: In some plugins I've been using DI to get the ObserverLocator instance from the container: import {inject} from 'aurelia-dependency-injection'; // or from 'aurelia-framework' import {ObserverLocator} from 'aurelia-binding'; // or from 'aurelia-framework' @inject(ObserverLocator) export class Foo { constructor(observerLocator) { this.observerLocator = observerLocator; } ... } You can then do something like this: var subscription = this.observerLocator .getObserver(myObj, 'myPropertyName') .subscribe(myCallback); When you're ready to dispose of the subscription, invoke it: subscription(); I think this is all subject to change but it's something you could use right now if you needed to. More info here October 2015 update The ObserverLocator is Aurelia's internal "bare metal" API. There's now a public API for the binding engine that could be used: import {inject} from 'aurelia-dependency-injection'; // or from 'aurelia-framework' import {BindingEngine} from 'aurelia-binding'; // or from 'aurelia-framework' @inject(BindingEngine) export class ViewModel { constructor(bindingEngine) { this.obj = { foo: 'bar' }; // subscribe let subscription = bindingEngine.propertyObserver(this.obj, 'foo') .subscribe((newValue, oldValue) => console.log(newValue)); // unsubscribe subscription.dispose(); } } A: The observable attribute has less of an overhead to binding according to I kill nerds. import {observable} from "aurelia-framework"; export class Example { @observable public description: string; private descriptionChanged(newValue: string, oldValue: string): void { } } A: listen to and trigger events based on its value A snippet from code using TypeScript, hopefully that will get you an idea: import {bindingMode} from "aurelia-binding"; export class Example{ @bindable public description: string; private descriptionChanged(newValue: string, oldValue: string): void { console.log(newValue, oldValue); } } Method name should follow convention `${propertyName}Changed` EDIT: That's exactly what Decade Moon suggested in the comment above: Property change subscription with Aurelia
{ "pile_set_name": "StackExchange" }
Q: Php, Zend framework and google calendar issue My client has got 3 display screens, and she is updating her gym classes through google calendar, and the website is using zend framework updating the data. Now the client is requesting fourth screen, so I'm trying to set up a developing environment. I set up a new database, a new sub domain and copied all the original sql database and the site code to the new domain. The problem I have is that now if i put a new class in through google calendar, the new sql database/the copied 3 existing screens do not update any more. However the original database and screens are updating properly still. Can someone please piont me to the right direction to make my developing environment work? What are the possibilities causing the data not updating? I'm new to zend framework, so any help is appreciated. Thanks heaps S:) A: Thanks everyone, it turns out it is the cron jobs setting in cpanel did the trick. I need to add the gdata_calendar.php for the new site into the cron jobs, and it is working now. Cheers, S
{ "pile_set_name": "StackExchange" }
Q: How do I query tables located in different database? My original question was about whether to keep separate ASPNETDB.MDF from the application database or merge all the tables in one database. Checking the previous questions/answers, I learned that it depends on whether the membership data would be shared across several applications. Now, my question is this. In case I decide to keep ASPNETDB.MDF separate from the application DB, how can I query 2 tables located in 2 different databases? Thanks for helping. A: If you have two databases/schemas on the same database server, you can query across databases with the following syntax: select * from database1.dbo.table1 t1 join database2.dbo.table2 t2 on t1.field1 = t2.field2 If they are on physically separate servers, you can still do a cross-database query, but you need to link the servers first: http://msdn.microsoft.com/en-us/library/aa213778(v=sql.80).aspx
{ "pile_set_name": "StackExchange" }
Q: Clear the errors once input field is valid I'm using AngularJS with node.js. I've implemented error handler as follows: node router effect.js: router.post('/', function(req, res, next){ req.checkBody('name', 'Effect name is required.').notEmpty(); var errors = req.validationErrors(); console.log(errors); if(errors) { res.status(500).json(errors); return; } var effect = new Effect({ name: req.body.name }); Effect.createEffect(effect, function(err, result) { if(err) { next(err) } res.status(201).end(); }); }); effectController.js: $scope.submit = function(effect) { effectService.save(effect, function(err, result, status) { $scope.errors = err; if(err == null) { $scope.effect = null; if(!(effect == null || effect == undefined)) { if(!(effect._id == undefined || effect._id == '')) { $location.path('/effect'); } } reload(); } }); } effectService.js function save(effect, callback) { if(effect == undefined || effect._id == undefined || effect._id == '') { $http.post('/api/effect', effect) .success(function(data, status) { callback(null, data); }) .error(function(data, status) { var errors = {}; for (var i = 0; i < data.length; i++) { var err = data[i]; var param, msg; for(var key in err){ if(key == 'param') param = err[key]; if(key == 'msg') msg = err[key]; } errors[param] = msg; } callback(errors, null); }); } else { $http.put('/api/effect/' + effect._id, effect); } } HTML: <form novalidate> <div class="form-group"> <label for="name" class="form-label">Name</label> <div class="col-xs-12" ng-class="{ 'has-error': errors.fname }"> <input type="text" id="name" name="name" class="form-control form-input" ng-model="effect.name" ng-disabled="isReadOnly" required /> <p class="help-block" ng-model="errors.name" ng-show="(errors == null || errors == undefined) ? false : errors.name">Effect name is required</p> </div> </div> <div class="row"> <div class="col-md-4 col-md-offset-8"> <div class="form-group form-controls"> <button id="submit" class="btn btn-success btn-input submit" ng-click="submit(effect)" ng-hide="isReadOnly">Save</button> <button id="clear" class="btn btn-input clear" ng-class="isReadOnly ? 'btn-primary' : 'btn-danger'" ng-click="clear()">{{clearButtonText}}</button> </div> </div> </div> </form> -> This works as expected. Problem: When there is an error from server, the error is displayed on the page. But error does not go away as soon as the input is valid. In short I want that errors should go away as soon as the input field is valid. I don't want the user to click submit button to clear the errors. Update: I have implemented another validation for duplicates in server as follows: index.js file: app.use(expressValidator({ customValidators: { duplicateRecord: function(input, propertyName, collection) { var duplicateRecordFound = false; collection.forEach(function(element) { if (element.propertyName == input) { duplicateRecordFound = true; return; } }, this); return duplicateRecordFound; } } })); router effect.js file: router.post('/', function(req, res, next){ Effect.find(function(err, effects) { if(err){ next(err); } req.checkBody('name', 'Effect name is required.').notEmpty(); req.checkBody('name', 'Duplicate effect name.').duplicateRecord('name', effects); var errors = req.validationErrors(); console.log(errors); if(errors) { res.status(500).json(errors); return; } var effect = new Effect({ name: req.body.name }); Effect.createEffect(effect, function(err, result) { if(err) { next(err) } res.status(201).end(); }); }); }); Also I changed the angular controller as @lean suggested: $scope.validate = function () { if($scope.errors != undefined) { if (angular.isDefined($scope.effect.name) && $scope.effect.name.length > 0) { $scope.errors.showName = false; } else { $scope.errors.showName = true; } } } $scope.submit = function(effect) { effectService.save(effect, function(err, result, status) { $scope.errors = err; if(err == null) { $scope.effect = null; if(!(effect == null || effect == undefined)) { if(!(effect._id == undefined || effect._id == '')) { $location.path('/effect'); } } reload(); } else { $scope.errors.showName = true; } }); Also I changed paragraph element in html file as follows: <input type="text" id="name" name="name" class="form-control form-input" ng-model="effect.name" ng-change="validate()" ng-disabled="isReadOnly" required /> <p class="help-block" ng-model="errors.name" ng-show="(errors == null || errors == undefined) ? false : (errors.showName)">{{errors.name}}</p> Problem: When I enter a name of the effect in input and then click on submit button, then if the name of the effect already exists in database then I get a message saying Duplicate Effect name. Then if I change a character in input box then error message goes away. Up to this point it works fine. But then if I delete all the text in input box, then the error message displayed is again Duplicate Effect name. instead of Effect name is required. A: You could use ng-change on your input to call a validator function like validate() in this example. View <form novalidate> <div class="form-group"> <label for="name" class="form-label">Name</label> <div class="col-xs-12" ng-class="{ 'has-error': errors.name }"> <input type="text" id="name" name="name" class="form-control form-input" ng-model="effect.name" ng-change="validate()" ng-disabled="isReadOnly" required /> <p class="help-block" ng-model="errors.name" ng-show="(errors == null || errors == undefined) ? false : errors.name">Effect name is required</p> </div> </div> <div class="row"> <div class="col-md-4 col-md-offset-8"> <div class="form-group form-controls"> <button id="submit" class="btn btn-success btn-input submit" ng-click="submit(effect)" ng-hide="isReadOnly">Save</button> <button id="clear" class="btn btn-input clear" ng-class="isReadOnly ? 'btn-primary' : 'btn-danger'" ng-click="clear()">{{clearButtonText}}</button> </div> </div> </div> </form> Validation $scope function //init scopes $scope.errors = {}; $scope.effect = { name: '' } /** * Manually validate fields */ $scope.validate = function () { if (angular.isDefined($scope.effect.name) && $scope.effect.name.length > 0) { $scope.errors.name = false; } else { $scope.errors.name = true; } }
{ "pile_set_name": "StackExchange" }
Q: C: Database too powerful for small files? I'm working on a scientific application in C for sending instructions telling a device to perform an experiment, then reading out the data from that experiment, and specifically for automating that function so that it can largely be performed without my input. I'm storing the pulse programs and the data files as ASCII files at the moment, but there are two issues with this - the first is that I find that when I load the data files into matlab matrices and save them from matlab, then read them in again later, it takes 100x longer to read from the ASCII files than to read from the .mat files - this jibes with my previous experience that these ASCII read/write operations are the slowest part of my program. The second issue is that any time I try and increase the versatility of the program, I have to create a new format specification for the storage of the files, which is annoying. I'm thinking about finding an SQL library and storing everything as relational databases, but from what I know about databases, you aren't meant to create a large number of small databases (data files are between maybe 50k and 50M, program files are very small). I'm really looking for something like the Matlab save() function, where I can dump a struct() variable into a file, then read it out by name. A database would make that easy enough, but it seems like there must be a more tailored way to store files that way. Any suggestions? Edit Sorry for the vague language here. I was trying not to get bogged down in specifics so that the question could have more broad applicability, but I see the folly in that now. Here's exactly what I do: Starting from a pulse program that is saved in file, here are the steps I'm doing: 1.) Read pulse program from an ASCII file that looks like this: #ValidPulseProgram# NInstructions= 15 NTransients= 1 DelayTime= 0.000000 TriggerTTL= 0 NPoints= 2000 SamplingRate= 2000.000000 PhaseCycle= 0 NumCycles= 4 CycleInstr= 2 CycleFreq= 60.000000 Dimensions= 2 [Point] IndirectDim 1 - 1 of 51 [Instructions] Instruction 0 0 4 0 0 10.000000 1000000000.000000 ... Instruction 2 0 266 0 0 750.000000 1000000.000000 Instruction 14 0 4 1 0 100.000000 1000000.000000 [EndInstructions] nVaried= 1 VaryInstr 0 5 0 -1.000000 24 -1.000000 1200 -1.000000 1 This is read out line-by-line and put into a struct that contains all the information. 2.) Send the struct to a program which translates it into something readable by the device which sets up the timings and such and starts the experiment. 3.) Data comes in and is stored in ASCII files, which have a header containing the program that was used, some other information about the acquisition. Each acquisition is stored as a separate ASCII file. There are sometimes thousands of these files, organized in a folder hierarchy. 4.) Later on, I want to be able to read out from the ASCII files. I either read them out from this C program I'm working on, or I read them out using a Matlab script that reads them into matlab variables (for more intense data analysis). The last step in that script is a call to save() which saves the .mat matlab file. For acquisitions with say 50 files of 1000 points each, it takes around 10-30 seconds to get all the data out into an array. If I save that array to a .mat file and later read it into the workspace, it takes milliseconds. So the two problems are step 4.) -> I should be saving these immediately in such a way that I can read them out in milliseconds, since it shouldn't take 30s to read a few MB from file, and step 1.), where I'd like to change that ASCII file into something like a binary file containing a struct. A: MATLAB has a C/C++ and Fortran API library that includes a MAT-File Library. That would be the most obvious solution. When reading an ASCII file, MATLAB it is possible perhaps that it adds each value to the matrix variable without a priori knowledge of the ultimate size, so it will constantly allocate, reallocate, and move data in memory as the matrix size grows - for large data sets, this will often involve virtual memory disk-swapping, and can be very slow. Either way it is both slow and non-deterministic. When a .MAT file is read, it allocates the correct size once and loads the data in one go. A: HDF5 is a library/file format designed as a database for scientific data. It is slightly more complex than just dumping into ASCII, but it was optimized for speed and has bindings for quite a lot of languages (C, Fortran, Python, also it seems Matlab has a builtin capabilities too). I don't know if HDF5 is common in your domain, but it seems to me its better suited than SQL databases. SQL provides ability to do complex queries, which might be unnecessary for you.
{ "pile_set_name": "StackExchange" }
Q: How to redirect intended user to a different route based on their role? I'd like to redirect my user to different route, based on their role. I have two secured area in my app, "admin" and "dashboard". I'd like to check if user is authenticated, then redirect to intended, but if user has role editor it should be redirected to dashboard, otherwise if he has role admin should be redirected to admin area. I'm using AuthenticatesAndRegistersUsers class in my login. I have this on my custom controller: /** * The default redirecTo path. * */ protected $redirectTo = '/dashboard'; So when a user is authenticated it will be redirected to dashboard, but I'd like to check if the intended url is on admin group route and if user has admin role it should be redirected to admin area. I'm using this middleware to redirect to login: public function handle($request, Closure $next) { if ($this->auth->guest()) { if ($request->ajax()) { return response('Unauthorized.', 401); } else { return redirect()->guest('auth/login'); } } return $next($request); } A: You could overwrite the redirectPath method used by the trait in your AuthController to inject the logic you need. Something like this: /** * Get the post register / login redirect path. * * @return string */ public function redirectPath() { // Logic that determines where to send the user if (\Auth::user()->type == 'admin') { return '/admin'; } return '/dashboard'; } EDIT: Laravel uses the following declaration in the AuthenticatesAndRegistersUsers trait to redirect the user after successful login: return redirect()->intended($this->redirectPath()); This will try to redirect the user to the previously attempted URL. If you need to redirect users to the right place when they're already logged in, that would be best done by adding more logic to your authentication middleware.
{ "pile_set_name": "StackExchange" }
Q: Why is the movie titled "Independence Day"? The title of the movie Independence Day (1996) makes no sense to me. A country gains independence when: It was depending on some other country (being ruled by another country). It becomes sovereign, freeing itself from the rule of a foreign country. The movie "Independence Day" has absolutely nothing to do with independence beside the fact that the last counter-attack by humans against the alien invaders happened to occur on the 4th of July (i.e. the American Independence Day). Anyway, as I understand it when an enemy state invades your country and you defeat them and send them back home then that doesn't mean that you gained independence. It just means that you successfully protected yourself. Now, if the enemy state successfully invaded your country and enforced their own law upon you and then you sent them back home then yes, you gained independence. However, as I currently see it that's not what happened in the movie. My argument is that you can't gain independence if you never depended on something. In the movie the humans certainly didn't depend upon the aliens. Hence, it makes no sense for them to commemorate an "Independence Day". Anyway, I know that Stack Exchange answers shouldn't be primarily opinion-based. I've been using Stack Exchange for a very long time now. Hence, here's my objective question: What's the justification for commemorating the 4th of July as a worldwide "Independence Day" in the movie? Did Roland Emmerich or Dean Devlin ever give an official explanation why? This question has been bothering me for a long time now. Especially since I saw the new movie trailer. A: The 4th of July holiday in America is called Independence Day, celebrating the day the Thirteen Colonies made themselves a new nation, free from the British. So from a historical point of view, it's quite logical whilst the national holiday is called Independence Day. However, in the film they twist this a little. Consider the president's rousing speech towards the end of the film: Perhaps it's fate that today, July the Fourth, we will once again fight for our freedom. Not from tyranny, persecution or oppression. But from annihilation. We're fighting for our right to live, to exist. From this day on, the fourth day of July will no longer be remembered as an American holiday but as the day that all of mankind declared we will not go quietly into the night. We will not vanish without a fight. We will live on. We will survive. So the President here is referring to Independence Day as primarily symbolising the day the fight for America's freedom was won. He then relates it to their current situation by showing how they're no longer fighting for freedom, but to avoid annihilation. But his point is, it's still a fight. However this time, it's not American's fight against the British, but the world's fight against invaders - so when they win, the world can celebrate the day together, because the world will have been saved. Of course, it doesn't quite make sense for it to be called Independence Day, as they're not independent of anything as you correctly surmise. However, given how the President relates it to the existing Independence Day coupled with the fact these events are occurring on 4th July, it makes sense that he is inviting the world to celebrate winning the fight on that day. A: In the movie,aliens have destroyed most cities of world and mankind's best weapon is the will to survive. I think the survival of humans in this movie is called 'Independence' Here is what Wiki has to say about your question justification for commemorating the 4th of July as a worldwide "Independence Day": With the successful implantation of the virus, Whitmore leads the attack against an alien destroyer approaching Area 51. Although the force field is deactivated and the fighters are able to inflict damage, the hull of the destroyer is too big to inflict serious damage. As a result, the fighter's supply of missiles quickly becomes exhausted. As the destroyer prepares to fire on the base, Casse has one missile left, but it jams. He decides to fly his plane directly into the alien weapon in a kamikaze attack, which kills him but destroys it. The Americans inform resistance forces around the world about how to destroy the alien ships. The nuclear device destroys the alien mothership as Hiller and Levinson escape unharmed back to Earth. The whole world then celebrates its heroes' victory as well as its true 'Independence Day'.
{ "pile_set_name": "StackExchange" }
Q: wxpython button with stock icon but no text I am using wxPython and would like to create a button with a stock icon and no text. If I do wx.Button(self,wx.ID_ADD) I get a button with a plus sign icon and the word 'Add' beside it. How can I get a button with only the icon ? A: At first glance, it looks like wx.BU_NOTEXT could work for this, but it actually doesn't because wxWidgets supposes that if this style is used, then the button is supposed to have a bitmap explicitly associated with it. So the simplest fix is to actually do set this bitmap by calling btn->SetBitmapLabel(wxArtProvider::GetBitmap(wxART_PLUS, wxART_MENU)) (this is C++, but should be easily translatable to Python too). If you do it like this, you don't need to use wxID_ADD as the button ID any more, but if you still want to keep using this ID, then you also need to use wxBU_NOTEXT to get rid of the stock text. And, unlike stock buttons, which intentionally conform to the standard platform look and so may show the icon or not depending on the platform, this code will work the same everywhere.
{ "pile_set_name": "StackExchange" }
Q: Induce system lag in vb.net I need to induce a variable amount of lag in vb.net. System should be noticeably slower. I can raise the CPU usage of the program with infinite loops and some variable creation/assignments, but how can I actually cause lag? I understand this is an odd request, but I appreciate any help and would appreciate it being taken seriously. This is NOT being used maliciously. I'd like to have an "InvokeLag" sub which will perform an action to slow down the computer, the faster the function is called the faster it lags. The function should be as mundane as possible, not modifying anything or doing anything to cause damage other than simple lag. Thanks for your help! EDIT: Preferably only achieving this effect with crazy math operations and making variables and such. Nothing system if possible. A: What about creating a new thread with the highest priority? Calculating Pi will never end and with a high priority it should lag your system down. If you have several processors you could start several threads to calculate pi or have a separate program that calculates pi and start several processes of it? Public Class Test Shared Sub Main() Dim threadLag As Thread = _ New Thread(AddressOf CalculatePi) threadLag.Name = "ThreadWait" threadLag.Priority = ThreadPriority.Highest threadLag.Start() End Sub Private Sub LagRoutine() While True Thread.SpinWait(10000) End While End Sub End Class or Public Class Test Shared Sub Main() For i as Integer = 1 to 10 Dim p As New Process("C:\MyLagProgram.exe") p.Start() Next i End Sub End Class CalculatePi MSDN Update: I think Eric might have a good point about SpinWait and it might be more what you are looking for: The SpinWait method is useful for implementing locks. Classes in the .NET Framework, such as Monitor and ReaderWriterLock, use this method internally. SpinWait essentially puts the processor into a very tight loop, with the loop count specified by the iterations parameter. The duration of the wait therefore depends on the speed of the processor. Contrast this with the Sleep method. A thread that calls Sleep yields the rest of its current slice of processor time, even if the specified interval is zero. Specifying a non-zero interval for Sleep removes the thread from consideration by the thread scheduler until the time interval has elapsed. There is no System IO, its basically just a tight loop which does not give up its processing time. I am sure if you used my suggestion of spawning several threads with the highest priority with Eric's suggestion SpinWait you would achieve what you are looking for. This would also reduce the amount of code you would need to write.
{ "pile_set_name": "StackExchange" }
Q: Are there any reasonable paying jobs one can get without a college degree? I'm a student in college currently pursuing a degree in mental health, but I was wondering whether anyone could offer me job suggestions which pay reasonably well. I'm 19 years old and would not mind a job that was tedious or "boring" as long as it does not require making phone calls or dealing with customers. A sort of background office job? I do not have any experience in the workforce, but I have volunteered at churches and libraries and homeless shelters. I would prefer to hit the ground with a running start if possible because I need to make payments for my house. A desk or office like position would be preferable. Fetching coffee and items for others, filing paperwork, transcribing, making orders of items, typing out letters or emails, taking notes, shelving? Is there any job which meets a description like this which won't require actual up front contact with the customers? Or very little, at least? Thank you very much. A: The best kept secret in the workforce is Trades pay extremely well. Plumbers, electricians, HVAC technicians and other skilled trades all pay very well, and are in constant demand. They are going to command take home pay easily comparable to the average university educated worker. This is assuming you are in a first world country.
{ "pile_set_name": "StackExchange" }
Q: Doctrine query one entity in one-to-many unidirectional with join table I have two entities linked by a one-to-many unidirectional with join table association. use Doctrine\ORM\Mapping as ORM; /** * @Entity(repositoryClass="FooRepository") */ class Foo { /** * @var Collection * @ORM\ManyToMany(targetEntity="Bar") * @ORM\JoinTable( * name="foo_bar", * inverseJoinColumns={@ORM\JoinColumn(unique=true)} * ) */ private $bars; /** * @var int * @ORM\Column(type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; // [...] } /** * @Entity(repositoryClass="BarRepository") */ class Bar { /** * @var int * @ORM\Column(type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; // [...] } I'd like to create a method into my BarRepository class using the a foo id and a bar id which return one or null Bar object. Actually my class looks like this: use Doctrine\ORM\EntityRepository; class BarRepository extends EntityRepository { /** * Finds a single bar. * @param int $fooId The foo identifier. * @param int $barId The bar identifier. * @return Bar|null */ public function findOneByFoo($fooId, $barId) { $qb = $this->createQueryBuilder('b'); $qb->innerJoin('Foo', 'f', Expr\Join::WITH, 'f.id = :fooId') ->where('b.id = :barId') ->setParameter('fooId', $fooId) ->setParameter('barId', $barId) ->getQuery()->getOneOrNullResult(); } } But this always returns a bar object even if the bar id is not associated to the foo object. A: OK, thanks to staskrak, I rewrite my "query" like this, and it works fine. The Foo and Bar entities are the same. I kept the same base of the query but added an inner join between the Foo->bars property and the Bar entity. use Doctrine\ORM\EntityRepository; class BarRepository extends EntityRepository { public function findOneByFoo($fooId, $barId) { $parameters = [ ':fooId' => $fooId, ':barId' => $barId ]; $qb = $this->createQueryBuilder('b'); return $qb ->innerJoin('Foo', 'f', 'WITH', 'f.id = :fooId') // below, the added inner join // it makes the link between the Foo->bars property and the Bar entity ->innerJoin('f.bars', 'fb', 'WITH', 'b.id = fb.id') ->where('b.id = :barId') ->setParameters($parameters) ->getQuery() ->getOneOrNullResult(); } }
{ "pile_set_name": "StackExchange" }
Q: Instalar plugin de PHP para o editor Atom Já instalei vários Plugins do Atom para habilitar recursos para reconhecer sintaxe de PHP no meu projeto, mas não tive sucesso, qual é meu objetivo? E quando eu digitar o código ele poder completar, veja o exemplo abaixo; @foreach($courses as $course) <div class="col-md-3"> <h3>{{ $course->name }}</h3> <p>{{ $course->description }}</p> </div> @endforeach No exemplo, com o plugin instalado era para quando eu digitar @forea... e ele completar. Eu só preciso saber qual o plugin certo para instalar no Editor Atom. Com as sugestões que me passaram ele fica assim, mas não é do jeito que preciso; Ao digitar o @fore.. não era para ele ter colocar o <?php ?> @<?php foreach ($variable as $key => $value): ?> <?php endforeach; ?> A: O Linter PHP seria uma boa solução, mas ele foi uma gambiarra temporária. Graças ao Nuclide, uma comunidade bem ativa e potente adotada pelo Facebook, agora o que era apenas um editor, acabouse transformando em uma verdadeira IDE. Para fazer o seu Atom Editor se transformar em uma IDE oficial, é muito fácil. Vem comigo e siga os passos abaixo: Instale o pacote atom-ide-ui Instale o seu pacote de linguagem favorita. Neste caso, o PHP: ide-php Eu escrevi um artigo fazendo um review e um comentário mais bacana da ferramenta do Atom IDE. Acesse este link para obter mais informações.
{ "pile_set_name": "StackExchange" }
Q: How do I remember a WPF XmlDataProvider bound Treeview's IsExpanded property when refreshed? I have a WPF treeview that is databound to an XmlDataProvider - the XML source is used by many PCs. When the XmlDataProvider is refreshed all the TreeViewNodes collapse. I would like each PC to remember the status of the IsExpanded attribute. I understand that I could add an IsExpanded property to the XML, however then this would be updated to all PCs that use the central XML file. Is there any other solutions to remember which nodes are expanded? Thanks! A: You could create classes that wrap the XML data, bind to the class, then add the IsExpanded property to this class so it only affects only the current user's view. (You probably don't want to go to all that work.) Or, you could bind the IsExpanded attribute to a converter that uses some identifying feature of the XML row. The converter could use any sort of internal data structure to remember whether a node is expanded or not.
{ "pile_set_name": "StackExchange" }
Q: Is splitting databases a legitimate security measure? When previous devs at my company had to store sensitive user data (for example, medical records), they did the following. I doubt its merits. There is data considered "insensitive" (user login, profile info), and "sensitive" (user medical records). There are three databases. Insensitive data in A, medical records in B, and the mapping between A and B in C. A hacker must hack all three databases to tie users (A) to medical records (B). Our own backend code calls C to tie A and B data together for user display. I think the ubiquity of this code invalidates the benefit of splitting databases: if the hacker accesses our system, he can call our logic. What benefits of the above system am I missing (or are there better ways to secure such data)? A: I'd say that once your system has been compromised and the assailant is past the threshold with access, then the databases are just a matter of time. What it is doing is at least perhaps delaying to intruder in their intent - but the cost (in terms of maintenance, performance, project clarity and so on) might outweigh the benefits. I'm sure there will be sufficient information for a determined person to decide that X, Y and Z databases are linked - unless you obfuscate database names, table names and other structural indicators. Ideally you should be looking to make your system impenetrable, all other things beyond that are mitigations, the treating of symptoms with neglect for the problem (that you've been exploited), of which the trade-off must be considered uniquely to the situation. In my experience and opinion, splitting the database like this is a strangely contrived approach to security that I find to be ingeniously silly.
{ "pile_set_name": "StackExchange" }
Q: Premium and opensource I am thinking about releasing my premium (commercial) project as an opensource project, but I am not sure how the user might benefit, how I will benefit and which license will I use. I really need to know anything possible about this step... A: An important thing to remember is that if none of your users are programmers, and don't want to be programmers, and if they don't have access to/can't pay programmers, then your project isn't going to form any sort of community. Only programmers really care about the source. They're the only ones that can use it. I've seen non-programmers in the maptool community, gamers, learn how to program just to help out. And that's pretty fantastic. But unless you have some zealous users, I wouldn't count on it. Of course, it couldn't hurt, but unless you've had excited users asking for improvements or asking for the source, opening it up might not make that big of a splash.
{ "pile_set_name": "StackExchange" }
Q: jQuery to not perform function on child click but perform on parent I am trying to make a FAQ and I make a list of block and when < li> is clicked it's child expands and when again < li> is clicked will close . Everything is working fine but when I also click on it still closing it. I want only when box was clicked is clicked it will open his child "reveal" only and when it click again, it will hide "reveal" My jQuery is: $(".toggle").click(function(){ $(this).find('.reveal').addClass('open').slideToggle(); return false; }); I been 1 hour, I searched stackflow, and one said to use "return false;"; but it doesn't do anything. What am I doing wrong? and here's the demo at the list of boxes: demo $(".toggle").click(function() { $(this).find('.reveal').addClass('open').slideToggle(); }); ol { display: block; width: 100%; height: auto; position: relative; margin: 0 auto; box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.1); border: 1px solid rgba(61, 70, 77, 0.1); } ol li { display: block; width: 100%; min-height: 80px; border-bottom: 1px solid #e9eaec } ol li .shown { width: 100%; position: relative; } ol li .shown * { float: left; line-height: 80px; height: 80px; } ol li .number { width: 8%; position: relative; float: left; display: block; } ol li .number span { background-color: #F29898; display: block; position: absolute; line-height: 0px; border-radius: 50px; padding: 15px 8px; font-weight: 800; color: #fff; font-size: 21px; top: 25px; left: -15px; height: 30px; width: 30px; display: block; } ol li .name { width: 52%; line-height: 80px; height: 80px; float: left; } .detailed ol li .name { margin-left: 10%; } ol li .name span { font-size: 26px; font-weight: 800; color: #F29898; } ol li .rating { width: 20%; } ol li .rating span { font-size: 18px; font-weight: 800; color: #F29898; opacity: .8; } ol li .goto { width: 20%; } ol li .goto .btn { line-height: 40px; height: 40px; text-align: center; padding: 0 24px; margin-top: 20px; } ol li .reveal { display: none; width: 90%; margin: 0 auto; padding: 0 0 20px 0; position: relative; line-height: 1; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ol> <li class="toggle"> <div class="shown"> <div class="number"> <span>4</span> </div> <div class="name"> <span>GoDaddy</span> </div> <div class="rating"> <span>8.5/10</span> </div> <div class="goto"> <a class="btn">Visit</a> </div> </div> <div class="reveal" id="four-reveal"> <p>We personally love GoDaddy but <u>their are many mix reviews about the company hosting services</u>. Some love them, some don't. But GoDaddy doesn't get so big by accident, they have more than 14 million customers. We personally host our clients websites on GoDaddy;</p> <p>GoDaddy shared hosting plan offers <b>uptime of 99.9% guarantee</b>, with <b>24/7 support via phone and email or Fourm</b>; and We can tell you one thing sure, their <b>Support is the best</b>. </p> </div> </li> </ol> A: So instead of firing an event on li, try fire it on shown. check the below code: $(".toggle .shown").click(function() { $(this).parent().find('.reveal').addClass('open').slideToggle(); }); ol { display: block; width: 100%; height: auto; position: relative; margin: 0 auto; box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.1); border: 1px solid rgba(61, 70, 77, 0.1); } ol li { display: block; width: 100%; min-height: 80px; border-bottom: 1px solid #e9eaec } ol li .shown { width: 100%; position: relative; z-index: 9999; } ol li .shown * { float: left; line-height: 80px; height: 80px; } ol li .number { width: 8%; position: relative; float: left; display: block; } ol li .number span { background-color: #F29898; display: block; position: absolute; line-height: 0px; border-radius: 50px; padding: 15px 8px; font-weight: 800; color: #fff; font-size: 21px; top: 25px; left: -15px; height: 30px; width: 30px; display: block; } ol li .name { width: 52%; line-height: 80px; height: 80px; float: left; } .detailed ol li .name { margin-left: 10%; } ol li .name span { font-size: 26px; font-weight: 800; color: #F29898; } ol li .rating { width: 20%; } ol li .rating span { font-size: 18px; font-weight: 800; color: #F29898; opacity: .8; } ol li .goto { width: 20%; } ol li .goto .btn { line-height: 40px; height: 40px; text-align: center; padding: 0 24px; margin-top: 20px; } ol li .reveal { display: none; width: 90%; margin: 0 auto; padding: 0 0 20px 0; position: relative; line-height: 1; } ol li .reveal .btn { width: 200px; text-align: center; line-height: 20px; height: 40px; display: inline-block; } ol li.email { text-align: center; } ol li.email input { width: 70%; padding: 0 10px; border-color: #F29898; } ol li.email button { width: 20%; padding: 10px auto; border: 2px solid #F29898; background-color: #F29898; font-size: 15px; height: 23px; color: #fff; font-weight: bolder; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ol> <li class="toggle"> <div class="shown"> <div class="number"> <span>4</span> </div> <div class="name"> <span>GoDaddy</span> </div> <div class="rating"> <span>8.5/10</span> </div> <div class="goto"> <a class="btn">Visit</a> </div> </div> <div class="reveal" id="four-reveal"> <p>We personally love GoDaddy but <u>their are many mix reviews about the company hosting services</u>. Some love them, some don't. But GoDaddy doesn't get so big by accident, they have more than 14 million customers. We personally host our clients websites on GoDaddy;</p> <p>GoDaddy shared hosting plan offers <b>uptime of 99.9% guarantee</b>, with <b>24/7 support via phone and email or Fourm</b>; and We can tell you one thing sure, their <b>Support is the best</b>. </p> </div> </li> </ol>
{ "pile_set_name": "StackExchange" }
Q: How to add a jQuery plugin in theme? I have been looking into RequireJS for a while, but till now, I still can not figure out how to add the TouchSwipe plugin into my theme. Would somebody take the time to give me a step by step? A: copy js file jquery.touchSwipe.min.js into your custom theme web/js folder. app/design/frontend/Vendor/themename/web/js/jquery.touchSwipe.min.js Now you have to use inside your template file, just create requirejs-config.js file inside your theme template, app/code/Vendor/Module/view/frontend/requirejs-config.js code for js file, var config = { paths: { 'touchswipe': "js/jquery.touchSwipe.min" }, shim: { 'touchswipe': { deps: ['jquery'] } } }; Now you can use inside your template like this, <div id="touchme">Touch me to see effect</div> <script> require([ 'jquery', 'touchswipe' ], function($, swipe){ $(function() { $("#touchme").swipe({ //keep your code here }); }); }); </script> Now Remove var folder from root Remove pub/static folder contents. Run deploy command, php bin/magento setup:static-content:deploy A: Step 1: Create requirejs-config.js under CompanyName\Custom\view\frontend\ folder with the following code -: var config = { map: { '*': { jquery_cookie: 'CompanyName_Custom/js/jquery_cookie', } } }; Step 2: Add jquery_cookie.js or any other jquery plugin under CompanyName\Custom\view\frontend\web\js\ Step 3: Now the jquery plugin has been added, now you can call jquery cookie plugin from any of your template files <script> //<![CDATA[ require(['jquery','jquery_cookie'], function($){ $(window).load(function() { $.cookie.json = true; var customCookie = $.cookie("customCookie"); if (customCookie != undefined) { console.log(customCookie); $.removeCookie("customCookie", {path: '/', domain: document.domain}); } }); }); //]]> </script> The key thing to notice here is that we are using require JS as part of the first line require([‘jquery’,’jquery_cookie’] and declaring to use jquery and our newly added jquery plugin i.e. jquery_cookie. Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: Activities for calc based physics I was sort of thrown into teaching calculus based physics to a bunch of non-physics majors, who have taken one semester of calculus, and are poor with that material. It is only a 50 minute per week class. So I've been stuck in between teaching elements they'd receive in the calc sequence (integration by parts, $i$ and $j$ vector notation, dot product, partial derivatives, etc), and somewhat random integral or derivative versions of stuff they've seen in their normal physics class running in parallel. I also don't like the calc based text I'm using in parallel to their regular non-calc class text. Since it's a 50 minute per week, 1 credit hour class with low expectations, can anyone recommend me some "interesting" activities, or else point me to a nice standard problem set, to do in there? A: I am going to assume that you are teaching a calculus "helper" versus the entire physics class. Your initial statements don't match that. But then all your content described is math, not physics. And also 50 minutes per week sounds rather light for a whole class. [If the converse is the case, I would spend your time on...physics.] With that in mind, my advice is NOT to look for some interesting activities. Instead use this as an opportunity for you to learn about the math required in stereotypical physics 101 classes. And give the kids a brushup related to that. Look at the homework and see what are the key math steps in them. And give a little help on them. Don't teach the physics of it (no word problems, they get that in real class). But abstract it down just to the math itself. I would try to parallel whatever is being done in physics class. If vectors are important this week, spend some time on vectors this week. If integrals are important a different week, spend time on that. Now, it may not match perfect match, and some remediation may be needed of issues in previous semester. But let that be a general guide. In terms of format, I would try to do something interactive, using a handout each week. Some lecture and some practice, using the sheet.
{ "pile_set_name": "StackExchange" }
Q: how to show dynamically added cell selected in uitableview I'm adding cell into uitableview on some action event. The cell is added at the top position in uitableview. I want the newly added cell to be selected by default. A: Just call the method selectRowAtIndexPath:animated:scrollPosition: of the table view after the cell is added, assuming the cell is added in index 0 of section 0: NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; [tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewRowAnimationTop]
{ "pile_set_name": "StackExchange" }
Q: Filter in django between from date and to date More pdf file is saved in table with different dates,How to filter pdf file between fromdate and todate. How to filter inbetween dates and list the pdf file. views.py def select_date(request): client = Client.objects.all() process = Client_Process.objects.all() pdf = Client_files.objects.all() today = date.today() yesterday = today - timedelta(days = 1) print(today) print(yesterday) if request.method == "POST": fromdate = request.POST.get('fromdate') todate = request.POST.get('todate') user = Client_files.objects.filter(Date__range=(fromdate,todate)) print(user) return render(request,'select_date.html', {'pdf':pdf,'client':client,'process':process}) models.py class Client_files(models.Model): Date = models.DateTimeField(default=datetime.now, blank=True) client = models.ForeignKey(Client, on_delete=models.CASCADE,null=True) client_process = models.ForeignKey(Client_Process, on_delete=models.CASCADE,null=True) File_Name = models.FileField() Pages = models.IntegerField(null=True) Count = models.IntegerField(null=True) Status = models.BooleanField(default = False) class Meta: db_table : 'client_files' A: You should use the __date lookup [Django-doc], to convert a datetime to a date first: def select_date(request): client = Client.objects.all() process = Client_Process.objects.all() pdf = Client_files.objects.all() today = date.today() yesterday = today - timedelta(days = 1) print(today) print(yesterday) if request.method == "POST": fromdate = request.POST.get('fromdate') todate = request.POST.get('todate') pdf = Client_files.objects.filter(Date__date__range=(fromdate, todate)) print(pdf) return render(request,'select_date.html', {'pdf':pdf,'client':client,'process':process}) Usually however when you filter items, you pass the parameters as GET parameters in a GET request. A POST request usually changes data.
{ "pile_set_name": "StackExchange" }
Q: Triangle in descending output Why is it the output enters new line after 3? like this: 9 8 7 6 5 4 3 2 1 any number i input it always enters a new line after 3. My target output should be like this when i input 9: 9 8 7 6 5 4 3 2 1 0 Will you please clarify to me why is it enters a new line after 3? public class TriangleWithInput { /** * @param args */ @SuppressWarnings("resource") public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); int input = sc.nextInt(); while (input >= 0) { int c = 1; while ( c <= input) { int r = 1; while (r <= c) { System.out.print(input + " "); input--; r++; } System.out.println(); c++; } } } } A: You seem to have one too many nested loops. You are getting a new line because of the test c <= input; when input reaches 3 and c >= 3, you do a line break and reset c to 1. I'd write your loops like this: for (int r = 1; input >= 0; ++r) { for (int c = 1; c <= r && input >= 0; ++c, --input) { System.out.print(input + " "); } System.out.println(); }
{ "pile_set_name": "StackExchange" }
Q: How is the free modular lattice on 3 generators related to 8-dimensional space? Here are three facts which sound potentially related. What are the actual relationships? In 1900, Dedekind constructed the free modular lattice on 3 generators as a sublattice of the lattice of subspaces of an 8-dimensional vector space. If the basis of the vector space is $e_1, \dots, e_8$, he looked at the subspaces $$ X = \langle e_2, e_4, e_5, e_8 \rangle , \; Y = \langle e_2, e_3, e_6, e_7 \rangle, \; Z = \langle e_1, e_4, e_6, e_7 + e_8 \rangle $$ By repeatedly taking intersections and unions, you can build up 28 subspaces starting from these three. This proves the free modular lattice on 3 generators has at least 28 elements. In fact it has exactly 28 elements. I think Dedekind showed this by working out the free modular lattice 'by hand' and noting that it, too, has 28 elements. The dimension of $\mathrm{SO}(8)$ is 28. Its Lie algebra $\mathfrak{so}(8)$, also called $D_4$, has 12 positive roots, and its Cartan algebra has dimension 4. As usual, the Lie algebra is spanned by positive roots, an equal number of negative roots, and the Cartan subalgebra, so we get $$ 28 = 12 + 12 + 4 $$ The 3 subspace problem asks us to classify triples of subspaces of a finite-dimensional vector space $V$, up to invertible linear transformations of $V$. There are finitely many possibilities, unlike the situation for the 4 subspace problem. One way to see this is to note that 3 subspaces $X, Y, Z \subseteq V$ give a representation of the $D_4$ quiver. This is nothing profound: a representation of the $D_4$ quiver is just 3 linear maps $X \to V$, $Y \to V$, $Z \to V$, and here we are taking those to be inclusions. The nontrivial part is that indecomposable representations of any Dynkin quiver correspond in a natural one-to-one way with positive roots of the corresponding Lie algebra. So, in particular, the $D_4$ quiver has 12 indecomposable representations. The representation coming from $X, Y, Z \subseteq V$ must be a direct sum of indecomposable representations, so we can classify the possibilities and solve the 3 subspace problem. Here is a way of making my question more concrete. However, it may be on the wrong track: Is there a natural 1-1 correspondence between the 28 elements of the free modular lattice on 3 generators and some basis of $\mathfrak{so}(8)$? Here is another more cautious way: What is known about the relation between the free modular lattice on 3 generators and the 3 subspace problem? It would help if one could somehow directly relate the free modular lattice on 3 generators to something built from $D_4$. The free modular lattice on 3 generators looks like this: For more background information, see: John Baez, The free modular lattice on 3 generators, The n-Category Café, September 19, 2015. A: The Darmstadt school, particularly Christian Herrmann, studied the Gelfand Ponomarev papers carefully to see what they said about 4-generated modular lattices; see Ch. Herrmann, Rahmen und erzeugende Quadrupel in modularen Verbande, Algebra Universalis, 14(1982) 357-387. Some of the interesting results include: The lattice of subspaces of every $n$-dimensional vector space, $3 \le n < \infty$, over a prime field is $4$-generated. Moreover, the quadruples generating the whole lattice are known. The dimension of each of the subspaces in the generating set can differ from $n/2$ by at most $2$. The lattice of subgroups of $(\mathbb Z/p^k\mathbb Z)^n$ is four generated if $3 \le n < \infty$. The hope was to classify the modular lattices generated by quadruples and so solve the word problem for $FM(4)$. But is now known that the word problem for free modular lattices is undecidable. A: Edited to be more of an answer. But, unfortunately, to be quite wrong. I apologize for having been borne away by my enthusiasm. The picture of the free modular lattice above shows thirty elements. Comparing with Grätzer's book, it appears that the top and bottom elements should be removed. And that makes sense, as there is clearly no way to generate them from the other elements. However, I guess your picture could be viewed as the "free modular lattice on three elements with top and bottom element". The reason I don't want to tell you to change your picture, is that the part of it above the middle rank is exactly the poset of positive roots of $D_4$! I don't know why, though. Addition starts here: clearly, the most general lattice you can get from three subvectorspaces of a vector space is obtained by adding together one copy of each of the indecomposable representations of $D_4$ (with arrows oriented inwards) such that all the maps are injections, because if you take multiple copies of a representation, it doesn't help you. This is almost what Dedekind did, as described above, but not quite: he is missing two of them: the simple at the central node, and the representation which is one-dimensional at each node (i.e., add $e_9$ in all of $X,Y,Z$, and $e_{10}$ in none of them (just in the ambient space)). Then you get the full 30 elements of the lattice. Everything from here on is pretty much junk. For each of element of the lattice, you can ask "which indecomposable representations survive here?" This isn't really enough information, because, for example, the biggest indecomposable only "partly" survives (because only one of its two dimensions at the middle node is hit by the map from $X$). So, for the element X, the answer is "all the indecomposable representations supported over X". For $X \wedge Y$ it is "all indecomposable representations supported over $X$ and $Y$. Etc. This translates the problem into a question about subsets of indecomposable representations of $D_4$. In fact, it seems to be simpler to think about the subsets of indecomposable representations which are killed at each node. Thus, for the top node, there are none. For the next node down, there is just the simple at the central vertex. Clearly, the set of indecomposables which are killed at a given element of the lattice is closed under subrepresentations. However, more is true. By inspection i.e., blinded by optimism, we see that the set of indecomposables killed by a given lattice element is also closed under extensions. (I thought this was obvious but I no longer think so. However, there is probably a conceptual explanation.) Subcategories closed under extensions and subobjects are called "torsion-free classes". The torsion-free classes in rep($D_4$) are known to form a lattice but not a modular lattice. And in fact, the full lattice (on 30 elements) consists of all the torsion-free classes inside the representations of $D_4$ for which the maps are injective. There are not enough torsion-free classes, and in this case they don't form a modular lattice (it's not even graded). A: Here's a nice clean statement that emerged from discussions on The n-Category Café. A representation of the $D_4$ quiver consists of three linear maps $f_i : L_i \to L$ ($i =1,2,3$) between finite-dimensional vector spaces over your favorite field. We can take direct sums of these representations, and define an indecomposable representation to be one that’s not a direct sum of two others. Given a representation of the $D_4$ quiver, the images of the maps $f_i$ are subspaces of $L$. These generate a sublattice $\mathcal{L}$ of the lattice of all subspaces of $L$. Clearly $\mathcal{L}$ is a modular lattice with 3 generators. Theorem. If we take a direct sum of indecomposable representations of the $D_4$ quiver, one from each isomorphism class, we obtain a representation of the $D_4$ quiver whose corresponding modular lattice is the free modular lattice on 3 generators. In this representation the spaces $\mathrm{im} (f_i)$ have dimension 5 and the space $L$ has dimension 10. 10 is the smallest possible dimension for a vector space $L$ containing subspaces that generate a copy of the free modular lattice on 3 generators. (Here I should emphasize that I'm using lattice to mean a poset for which every finite subset has a least upper bound and greatest lower bound. Such a thing has a top and bottom as well as binary operations $\vee$ and $\wedge$. So, the free modular lattice on 3 generators, in this sense, has 30 elements, including a freely adjoined top and bottom element. This gives a cleaner statement of the result than working with Dedekind's original definition of lattice.) The proof is lurking in discussions here: John Baez, The free modular lattice on 3 generators, The n-Category Café, September 19, 2015. but I will put a cleaned-up version onto Visual Insight on January 1, 2016.
{ "pile_set_name": "StackExchange" }
Q: How to slice an audio blob at a specific time? I have an audio blob and I want to chop it up at a specific time.How should I do that in Javascript ? Example: sliceAudioBlob( audio_blob, 0, 10000 ); // Time in milliseconds [ start = 0, end = 10000 ] Note: I have no clue how to do that, so a little hint would be really appreciated. Update : I'm trying to build a simple audio recorder, but the problem is that there are differences in time duration for each browser, some of them adds few seconds ( Firefox ) and others don't ( Chrome ). So, I came up with the idea to code a method that returns only the slice I want. Full HTML code : <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Audio Recorder</title> <style> audio{ display: block; } </style> </head> <body> <button type="button" onclick="mediaRecorder.start(1000)">Start</button> <button type="button" onclick="mediaRecorder.stop()">Stop</button> <script type="text/javascript"> var mediaRecorder = null, chunks = [], max_duration = 10000;// in milliseconds. function onSuccess( stream ) { mediaRecorder = new MediaRecorder( stream ); mediaRecorder.ondataavailable = function( event ) { // chunks.length is the number of recorded seconds // since every chunk is 1 second duration. if ( chunks.length < max_duration / 1000 ) { chunks.push( event.data ); } else { if (mediaRecorder.state === 'recording') { mediaRecorder.stop(); } } } mediaRecorder.onstop = function() { var audio = document.createElement('audio'), audio_blob = new Blob(chunks, { 'type' : 'audio/mpeg' }); audio.controls = 'controls'; audio.autoplay = 'autoplay'; audio.src = window.URL.createObjectURL( audio_blob ); document.body.appendChild(audio); }; } var onError = function(err) { console.log('Error: ' + err); } navigator.mediaDevices.getUserMedia({ audio: true }).then(onSuccess, onError); </script> </body> </html> A: There is no straight forward way to slice an Audio media like that, and this is because your file is made of more than sound signal: there are multiple segments in it, with some headers etc, which position can't be determined just by a byteLength. It is like you can't crop a jpeg image just by getting its x firsts bytes. There might be ways using the Web Audio API to convert your media File to an AudioBuffer, and then slicing this AudioBuffer's raw PCM data as you wish before packing it back in a media File with the correct new descriptors, but I think you are facing an X-Y problem and if I got it correctly, there is a simple way to fix this X problem. Indeed, the problem you describe is that either Chrome or Firefox doesn't produce an 10s media from your code. But that is because you are relying on the timeslice argument of MediaRecorder.start(timeslice) to give you chunks of perfect time. It won't. This argument should only be understood as a clue you are giving to the browser, but they may well impose their own minimum timeslice and thus not respect your argument. (2.3[Methods].5.4). Instead, you'll be better using a simple setTimeout to trigger your recorder's stop() method when you want: start_btn.onclick = function() { mediaRecorder.start(); // we don't even need timeslice // now we'll get similar max duration in every browsers setTimeout(stopRecording, max_duration); }; stop_btn.onclick = stopRecording; function stopRecording() { if (mediaRecorder.state === "recording") mediaRecorder.stop(); }; Here is a live example using gUM hosted on jsfiddle. And a live snippet using a silent stream from the Web Audio API because StackSnippet's protection doesn't run well with gUM... var start_btn = document.getElementById('start'), stop_btn = document.getElementById('stop'); var mediaRecorder = null, chunks = [], max_duration = 10000; // in milliseconds. start_btn.onclick = function() { mediaRecorder.start(); // we don't even need timeslice // now we'll get similar max duration in every browsers setTimeout(stopRecording, max_duration); this.disabled = !(stop_btn.disabled = false); }; stop_btn.onclick = stopRecording; function stopRecording() { if (mediaRecorder.state === "recording") mediaRecorder.stop(); stop_btn.disabled = true; }; function onSuccess(stream) { mediaRecorder = new MediaRecorder(stream); mediaRecorder.ondataavailable = function(event) { // simply always push here, the stop will be controlled by setTimeout chunks.push(event.data); } mediaRecorder.onstop = function() { var audio_blob = new Blob(chunks); var audio = new Audio(URL.createObjectURL(audio_blob)); audio.controls = 'controls'; document.body.appendChild(audio); // workaround https://crbug.com/642012 audio.currentTime = 1e12; audio.onseeked = function() { audio.onseeked = null; console.log(audio.duration); audio.currentTime = 0; audio.play(); } }; start_btn.disabled = false; } var onError = function(err) { console.log('Error: ' + err); } onSuccess(SilentStream()); function SilentStream() { var ctx = new(window.AudioContext || window.webkitAudioContext), gain = ctx.createGain(), dest = ctx.createMediaStreamDestination(); gain.connect(dest); return dest.stream; } <button id="start" disabled>start</button> <button id="stop" disabled>stop</button>
{ "pile_set_name": "StackExchange" }
Q: Is it possible to get an object by its primary key in django-nonrel / Google App Engine? I'm trying to retrieve a model object like the code below: (r'^album/(?P<album_id>\w+)/$', 'core.views.album'), def album(request, album_id): album = Album.objects.get(pk=album_id) The problem is that the PK is not an integer: >>> a = Album.objects.all()[0] >>> a.pk 46L The error I'm getting when I run the view: ValueError at /album/46L/ invalid literal for int() with base 10: '46L' Ideas? Thanks. A: The problem was unrelated with the urls / views. Everytime I executed "runserver" my local datastore was being erased. So the data I was able to retrieve when using "shell" was not synced correctly. This happened because, for some weird reason, I commented this line (and forgot about it) on settings.py: AUTOLOAD_SITECONF = 'indexes'
{ "pile_set_name": "StackExchange" }
Q: Raylib undefined reference to functions on raspberry pi I am trying to learn C and I'm struggling to understanding linking. I'm having trouble getting my main.c file to compile using the raylib library. The makefile CFLAGS= -g -O -Wall -W -pedantic -std=c99 -O0 BASIC = -o -std=c99 LINKFLAGS=-I. -I/raylib/src -I../src -L/raylib/src -L/opt/vc/lib -lraylib -lbrcmGLESv2 -lbrcmEGL -lpthread -lrt -lm -lbcm_host -ldl -DPLATFORM_RPI run: gcc $(CFLAGS) $(LINKFLAGS) main.c -o main.o the main.c file #include <stdio.h> #include "raylib.h" int main(void) { const int screenWidth = 800; const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [core] example - basic window"); SetTargetFPS(60); // Set our game to run at 60 frames-per-second while (!WindowShouldClose()) // Detect window close button or ESC key { BeginDrawing(); ClearBackground(RAYWHITE); DrawText("Congrats! You created your first window!", 190, 200, 20, LIGHTGRAY); EndDrawing(); //---------------------------------------------------------------------------------- } CloseWindow(); // Close window and OpenGL context return 0; } The directory structure Pong/ - main.c - Makefile - raylib/ - raylib.h But when I run make && ./main.o I get this error. Even though I have the raylib.h file and I've got the raylib folder in my project. Does anyone know what might be going on? gcc -g -O -Wall -W -pedantic -std=c99 -O0 -I. -I/raylib/src -I../src -L/raylib/src -L/opt/vc/lib -lraylib -lbrcmGLESv2 -lbrcmEGL -lpthread -lrt -lm -lbcm_host -ldl -DPLATFORM_RPI main.c -o main.o /usr/bin/ld: /tmp/ccvCErhi.o: in function `main': /home/pi/pong/main.c:12: undefined reference to `InitWindow' /usr/bin/ld: /home/pi/pong/main.c:14: undefined reference to `SetTargetFPS' /usr/bin/ld: /home/pi/pong/main.c:27: undefined reference to `BeginDrawing' /usr/bin/ld: /home/pi/pong/main.c:29: undefined reference to `ClearBackground' /usr/bin/ld: /home/pi/pong/main.c:31: undefined reference to `DrawText' /usr/bin/ld: /home/pi/pong/main.c:33: undefined reference to `EndDrawing' /usr/bin/ld: /home/pi/pong/main.c:18: undefined reference to `WindowShouldClose' /usr/bin/ld: /home/pi/pong/main.c:39: undefined reference to `CloseWindow' collect2: error: ld returned 1 exit status make: *** [Makefile:6: run] Error 1 A: You must put libraries at the end of the link line, after all object files. Also, -I and -D are compiler flags not linker flags: CFLAGS = -g -O -Wall -W -pedantic -std=c99 -O0 -I. -I/raylib/src -I../src -DPLATFORM_RPI LDFLAGS = -L/raylib/src -L/opt/vc/lib LDLIBS = -lraylib -lbrcmGLESv2 -lbrcmEGL -lpthread -lrt -lm -lbcm_host -ldl run: gcc $(CFLAGS) $(LDFLAGS) main.c -o main.o $(LDLIBS)
{ "pile_set_name": "StackExchange" }
Q: How to implement click event on dynamically generating ? I have a drop down select box. Through jquery on run time that drop then hides and the new drop down made which made from <ul> and <li> tags. Now through firebug I notice that when the drop down is closed then there is one <li> and when I expand the drop down then in the firebug more <li> displayed. So I want to implement the click event on these <li>. I tried this code. $(document).ready(function() { alert('a'); $('.fb li').each(function() { alert('li'); $(this).click(function(event) { alert('hed'); var fbpage = $(this).attr("rel"); if(fbpage != 0) { window.open(''+fbpage+'', '_blank'); } }); }); }); the alert('a') and alert('li') works but then that click event is not working. Any idea about this? and if you does not understand my question then ask me I will explain it more. A: Since you are running D6, you should look into the live() jQuery handler ( http://api.jquery.com/live/ ) that can be used to attach these click handlers to your dynamic elements. More information on this can be found by googling or otherwise searching for jquery click event on dynamically generated elements You might also want to look into the Drupal.behaviors method of including jQuery and javascript instead of the $(document).ready() approach you've used.
{ "pile_set_name": "StackExchange" }
Q: Load Balancer Emitting Wrong Time in Http Header Our intranet web app is behaving very strangely. Very often posting back (asp.net) to save form input end in no-action. After a month or so of on-and-off troubleshooting, I finally got around to compare the http request and response headers. Basically, I have 2 browser sessions, 1 requesting directly to the web server, the other requesting through the load balancer URL. One of the differences between the 2 responses were Date header. The version coming from the LB has a Date header which is 6 minutes in the future. The other difference is Persistent-auth: the LB response is ON, and direct response is OFF. I am not network admin, so I don't get to poke around. My impression is that http header is emitted by the web server, not the load balancer. Is this even a valid scenario? What should I ask my admin to look for? A: The general behavior would be that the server would set the Date header and not the load balancer. However, it is possible to set headers with a load balancer. In particular, a caching load balancer might be doing this since according to RFC 2616 the Date header is part of determining the age (date_value is derived from the Date Header): Given that we have two independent ways to compute the age of a response when it is received, we can combine these as corrected_received_age = max(now - date_value, age_value) So I recommend working with your admins closely to better understand the architecture surrounding the application. Together find out what caching may be going on, what type of load balancer you are using, and of course verify that all servers in the pipeline have their time accurately set.
{ "pile_set_name": "StackExchange" }
Q: How do I add a transparent arrow that changes color between two points to a plot in R? Can I use the arrow() function in R to plot a transparent arrow between two points that changes color? For example, an arrow that starts out as red at one point, and gradually changes to blue at the other point (both points are on the same row in a dataframe)? If so, how? And if not, is there another function that can do that in R? Here is the piece of code I have until now, which draws points (blue and red) and connects the blue points with the red points with transparent blue arrows: par(xpd=NA, mfrow=c(1,1), mar=c(4.25,3.2,6.20,3.55)) plot(data$x1,data$y1,col="red",pch=20,cex=0.6,xlim=c(xmin,xmax),ylim=c(ymin,ymax),axes=FALSE,ann=FALSE,xaxt='n',yaxt='n') par(new=T) plot(data$x2,data$y2,col="blue",pch=20,cex=0.6,xlim=c(xmin,xmax),ylim=c(ymin,ymax),axes=FALSE,ann=FALSE,xaxt='n',yaxt='n') par(new=T) plot(grid.picture(NLmap[-1]),xlim=c(xmin,xmax),ylim=c(ymin,ymax),axes=FALSE,ann=FALSE,xaxt='n',yaxt='n') par(new=T) points(data$x1,data$y1,col="red",pch=20,cex=0.25) par(new=T) points(data$x2,data$y2,col="blue",pch=20,cex=0.25) par(new=T) arrows(data$x1,data$y1, data$x2, data$y2, length = 0.05, angle = 30, code = 2, col = "#9AC0CD40", lty = par("lty"), lwd = par("lwd")) Hope this helps! A: First of all, I should mention that my answer is directly derived from the information provided in the comments and the answer by DWin. I had never seen those functions before, so I thought I would give them a shot. I ended up creating a little function that works like arrows except a colour scale is added. I think this is essentially what you want. require(plotrix) color.scale.arrow = function(x1,y1,x2,y2,first.col,second.col, lwd= par('lwd'),lty=par('lty'),angle=30,length=0.25) { x=mapply(seq,x1,x2,length.out=256) # Each column is one arrow y=mapply(seq,y1,y2,length.out=256) # Each column is one arrow arrows(x[255,],y[255,],x[256,],y[256,], col=ifelse(y[256,]<y[255,],first.col,second.col), lwd=lwd,lty=lty,angle=angle,length=length) rgb1=col2rgb(first.col)[,1] / 255 rgb2=col2rgb(second.col)[,1] / 255 cols=rbind(rgb1,(rgb1 + rgb2) / 2,rgb2) invisible( sapply(seq(ncol(x)),function(line) color.scale.lines(x[,line],y[,line], cols[,'red'],cols[,'green'],cols[,'blue'], lwd=lwd,lty=lty) ) ) } # Create sample data set.seed(1) x <- runif(12); y <- rnorm(12) i <- order(x,y); x <- x[i]; y <- y[i] x1=x[s] x2=x[s+1] y1=y[s] y2=y[s+1] # Plot sample data plot(x,y, main='', type='n') color.scale.arrow(x1,y1,x2,y2,'red','blue',lwd=2) The arrow head will have a colour that matches the 'end' colour given in color.scale.arrow.
{ "pile_set_name": "StackExchange" }
Q: Can Moshiach be a woman? Is there any statement by chazal or the poskim which precludes Moshiach from being a woman? A: Rambam Hilchos Malachim perek 1 Halacha 5 "אין מעמידין אשה במלכות שנאמר עליך מלך ולא מלכה וכן כל משימות שבישראל אין ממנים בהם אלא איש." women cannot become kings. Also when the gemara discusses Mashiach they use the loshon "him" and Ben Dovid see Sanhedrin 98
{ "pile_set_name": "StackExchange" }
Q: Ajax Query gives null value Everytime I try to do something on my site which includes AJAX query, I get null value, but on Post value is not null. Function function lawProposePrompCall(v,m,f){ if(v == 1){ $.prompt('',{callback: reload, buttons:{Close: 0}}); $(".jqimessage").hide(); $(".jqimessage").html('<div style="text-align:center;"><img src="/public/images/loading.gif" alt="Loading" id="loading" /></div>'); $('.jqimessage').fadeIn('fast'); $.post(url+'/ajax-query', { action: "law-propose-acc", data: f.colawtype, data2: f.colawd2, data3: f.colawd3, data4: f.colawd4, data5: f.colawd5, data6: f.colawd6}, function(data){ if(data.status==1){ $('.jqimessage').html(data.communicat); $('.jqimessage').fadeIn('fast'); }else{ $('.jqimessage').html('Server Error'); $('.jqimessage').fadeIn('fast'); } }, "json"); } } And how do I properly convert it to JSon code? A: Removed one of the RecurencyDownRow() functions and it worked.
{ "pile_set_name": "StackExchange" }
Q: Parse JSON with AJAX I am trying to parse a JSON result with AJAX. My JSON looks like this [{ "_id" : "54fb09b7d059bdf3107f9486", "lastName" : "Record", "firstName" : "First", "__v" : 0 }, { "_id" : "54fb0a2fd059bdf3107f9487", "lastName" : "Record", "firstName" : "First", "__v" : 0 } ] I call this in Javascript $.getJSON('api/people', function(data) { item3="+data.item3+"</p>"); $.each(data,function(i,j){ content ='<span>'+j[i].firstName+'<br />'+j[i].lastName+'<br /></span>'; }); alert(content); }); Unfortunately I get "Uncaught TypeError: Cannot read property 'firstName' of undefined" in the console. Can someone please tell me how to properly parse this JSON? A: jQuery.each's second argument (the function executed for each element) takes two arguments (in your example, i and j), the first representing the key and the second the value, so there's no need for j[i]. This should work: $.getJSON('api/people', function(data) { $.each(data,function(i, item){ content ='<span>'+item.firstName+'<br />'+item.lastName+'<br /></span>'; }); alert(content); });
{ "pile_set_name": "StackExchange" }
Q: Unexpected result when skipping first rows with nrow in Pandas python I am trying to use the skiprows in pandas pd.read_csv function, however when I use it I only get that specific row from where it should start. I.e. skiprows=1, will ONLY output row 1. Any idea why this is happening. I am loading the CSV file in like this: df = pd.read_csv(filename, usecols=cols,skiprows=4,nrows=10) The following is a snapshot of my df, which as per the above example should give me Canada-Italy: iyear country_txt y x count code 0 1970 Argentina 4 0 15 ARG 1 1970 Australia 0 0 0 AUS 2 1970 Belgium 0 0 0 BEL 3 1970 Brazil 2 0 5 BRA 4 1970 Canada 1 0 1 CAN 5 1970 Colombia 0 0 0 COL 6 1970 Dominican Republic 1 0 1 DOM 7 1970 Germany 0 0 9 DEU 8 1970 Egypt 0 2 0 EGY 9 1970 Greece 2 0 2 GRC 10 1970 Guatemala 2 0 2 GTM 11 1970 Iran 0 0 4 IRN 12 1970 Ireland 1 0 0 IRL 13 1970 Israel 1 0 0 ISR 14 1970 Italy 0 0 1 ITA 15 1970 Japan 0 0 1 JPN 16 1970 Jordan 1 0 6 JOR 17 1970 Lebanon 0 0 0 LBN 18 1970 Mexico 0 0 1 MEX 19 1970 Netherlands 0 0 1 NLD 20 1970 Nicaragua 0 0 0 NIC 21 1970 Pakistan 1 0 0 PAK 22 1970 Paraguay 1 1 0 PRY 23 1970 Philippines 5 0 7 PHL 24 1970 Spain 0 0 2 ESP 25 1970 Switzerland 47 0 2 CHE 26 1970 Turkey 0 0 9 TUR 27 1970 United Kingdom 20 0 7 GBR 28 1970 United States 33 0 364 USA 29 1970 Uruguay 2 0 22 URY 30 1970 Venezuela 0 0 1 VEN However the output is the following: Empty DataFrame Columns: [1970, Brazil, 2, 0, 5, BRA] Index: [] A: I think you want to use the iterator=True parameter: Demo: reader = pd.read_csv(fn, iterator=True) # read first 5 rows df = reader.get_chunk(5) # read next 10 rows df = reader.get_chunk(10) # read next 12 rows df = reader.get_chunk(12) and so on..
{ "pile_set_name": "StackExchange" }
Q: How can I create my custom xmlrpc fault error in python When using xmlrpclib in python an error on the server side is reported by the client side as an xmlrpclib.Fault. A division by zero error in a method on the server side (using SimpleXMLRPCServer) usually gives an output like the following: xmlrpclib.Fault: <Fault 1: "<type 'exceptions.ZeroDivisionError'>:integer division or modulo by zero"> This is useful as it notes the type of error, but now where it happened. How is it possible to overwrite/modify the xmlrpclib.Fault method (in SimpleXMLRPCServer?) so it reports the error e.g. as follows: xmlrpclib.Fault: <Fault 1: "<type 'exceptions.ZeroDivisionError'>:integer division or modulo by zero MODULE: myMethod.py LINE: 657"> i.e. to include the name of the module the error appeared and the line number. Is that possible to do on the server-side, without raising custom exceptions? ANY error should reported in the same way on the client side. A: If you use SimpleXMLRPCServer, you can override the internal _marshaled_dispatch method to add information to the Fault() instance generated: This is the original method: def _marshaled_dispatch(self, data, dispatch_method = None, path = None): try: params, method = xmlrpclib.loads(data) # generate response if dispatch_method is not None: response = dispatch_method(method, params) else: response = self._dispatch(method, params) # wrap response in a singleton tuple response = (response,) response = xmlrpclib.dumps(response, methodresponse=1, allow_none=self.allow_none, encoding=self.encoding) except: # report low level exception back to server # (each dispatcher should have handled their own # exceptions) exc_type, exc_value = sys.exc_info()[:2] response = xmlrpclib.dumps( xmlrpclib.Fault(1, "%s:%s" % (exc_type, exc_value)), encoding=self.encoding, allow_none=self.allow_none) return response You can subclass SimpleXMLRPCServer.SimpleXMLRPCServer and override this method: import SimpleXMLRPCServer import sys import xmlrbclib class VerboseFaultXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer): def _marshaled_dispatch(self, data, dispatch_method = None, path = None): try: params, method = xmlrpclib.loads(data) # generate response if dispatch_method is not None: response = dispatch_method(method, params) else: response = self._dispatch(method, params) # wrap response in a singleton tuple response = (response,) response = xmlrpclib.dumps(response, methodresponse=1, allow_none=self.allow_none, encoding=self.encoding) except: # report low level exception back to server # (each dispatcher should have handled their own # exceptions) exc_type, exc_value, tb = sys.exc_info() while tb.tb_next is not None: tb = tb.tb_next # find last frame of the traceback lineno = tb.tb_lineno code = tb.tb_frame.f_code filename = code.co_filename name = code.co_name response = xmlrpclib.dumps( xmlrpclib.Fault(1, "%s:%s FILENAME: %s LINE: %s NAME: %s" % ( exc_type, exc_value, filename, lineno, name)), encoding=self.encoding, allow_none=self.allow_none) return response Then use VerboseFaultXMLRPCServer instead of SimpleXMLRPCServer.SimpleXMLRPCServer.
{ "pile_set_name": "StackExchange" }
Q: Implementing a custom Binding I have a MyUserControl that contains a Label label, and a BO public Person Person {get;set;}. I want that the Person's Name be always bind to the label like this: ("Name: {0}", person.Name), in case if person != null and ("Name: {0}", "(none)"), in case if person == null more than that, if the person name is changed, the label automatically update it. is there a possibility for such a binding? "Dirty" variant: private void label_LayoutUpdated(object sender, EventArgs e) { label.Content = string.Format("Name: {0}", _Person == null ? "(none)" : _Person.Name); } A: How about: <StackPanel Orientation="Horizontal"> <TextBlock Text="Name: "/> <TextBlock Text="{Binding Person.Name, FallbackValue='(none)'}"/> </StackPanel> This doesn't use a Label, but it accomplishes the goal. If it needs to be a Label, you can do this: <Label Content="{Binding Person.Name, FallbackValue='(none)'}" ContentStringFormat="Name: {0}"/> One caveat with both approaches is that the text will also display Name: (none) if the binding is incorrect (Person == null is equivalent behavior to no property Person found).
{ "pile_set_name": "StackExchange" }
Q: 4A XL6009 DC-DC For Laptop Charging I live in a place that suffers from electricity shortages, I have a 12V 20AH battery and I want to charge my laptop using it, rather than buying an inverter I thought it would be more efficient if I use a DC-DC step up module I got the XL6009 4A max it does provide the wanted voltage (19.5V) but then I checked my laptop charge adapter and it says 4.62A MAX. Is this a real problem or I'll get away with it if I provide decent ventilation? A: 4.62A is out of spec even for the XL6009 itself, so you will need a more powerful converter. In practice, the actual current you can get from these pre-fabricated DC-DC converters is further limited by their design. The cheapest ones and the smallest ones can barely deliver 2A continuously, before they start getting too hot and eventually shut down thanks to thermal protection. Websites selling them will still advertise them as 4A converters, without mentioning that 4A is in fact a spike value. If you're lucky your laptop only pulls 4.62A occasionally, and a well-designed converter based on XL4015 or LTC3609 may suit your needs. Pick a module with a toroidal coil: these coils heat up quite a bit, so you don't want a coil which has good thermal contact with the PCB and contributes to the overheating of the converter chip. If you don't want to guess, buy a real power supply rated for 5A or more of continuous load.
{ "pile_set_name": "StackExchange" }