text
stringlengths
15
59.8k
meta
dict
Q: Dribble is producing empty output files I need to create an output file for a program in lisp, but I cannot get dribble to properly record my output. I'm using lispbox and my buffer looks like this when I try to use dribble: (dribble "output.txt") "output.txt" ... Calls to functions I defined ... I've tried entering expressions, values, strings (dribble) NIL But when I go to output.txt I have an empty file that is 0 bytes. I'm pulling my hair out because I'm having trouble finding the answer and it seems like my computer is the problem. Any thoughts on where to start troubleshooting this (or solutions) would be greatly appreciated. A: I'd bet dribble is rebinding some streams that are different from the ones being used by SLIME to get output to and from the REPL. (Issue DRIBBLE-TECHNIQUE might be worth reading.) Your solution depends on what your are doing. If you just want a record of your interactions with Lisp, remember that emacs is a text editor and you can save the contents of the REPL buffer to a file or copy an excerpt. If you want to write a program that saves output to a file, dribble is not a good mechanism for this. Have a look at open, close, print, format, and with-open-file.
{ "language": "en", "url": "https://stackoverflow.com/questions/12591432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: react-typeahead - invariant violation: addComponentAsRefTo(...) issue Node v0.12.2 React v0.13.2 Npm v2.7.4 Using the standard typeahead input causes the following error: Uncaught Error: Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. This usually means that you're trying to add a ref to a component that doesn't have an owner (that is, was not created inside of another component's render method). Try rendering this component inside of a new top-level component which will hold the ref. This is how I am implementing the typeahead... Index.jsx has: 'use strict' var React = require('react'); var ReactTypeahead = require('react-typeahead').Typeahead var QuickSearch = React.createClass({ render: function () { return( <ReactTypeahead options={["spam", "foodbar"]}/> ); } }); var Topbar = React.createClass({ render: function() { return ( <QuickSearch /> ); } }); module.exports = Topbar; And then in my App.jsx I have: 'use strict'; var React = require('react'); var Topbar = require('./topbar'); var App = React.createClass({ render: function () { return ( <div> <Topbar /> </div> ); } }); module.exports = App; A: Seems to me you are missing a semicolon after requiring the typeahead.
{ "language": "en", "url": "https://stackoverflow.com/questions/30108848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to use data returned from subprocess.call without returning the entire output? def is_akamaized(url): stripped_http_url = url[8:] clean_host = stripped_http_url.rsplit('/')[0] nslookup_data = subprocess.call(["nslookup", clean_host], stdout=subprocess.PIPE) if nslookup_data.find('akamaiedge'): return "\033[1;31mEnvironment is Acamaized {0} - {1}\033[1;m" This function just takes a url and runs nslookup on it. What I WANT to happen is I want to take the output of nslookup and parse through it for certain keywords. The problem is, with the current code if I pass in a url that should work (contain the word acamai in the nslookup) print is_acamaized(url) it returns 0 Note, I added the stdout=subprocess.PIPE so that the entire output of nslookup is not returned to the terminal. Any suggestions on how to assign the output of nslookup to a variable so I can access it? A: subprocess.call() returns the exit code, not the stdout. You can use the Popen class directly: nslookup_data = subprocess.Popen(["nslookup", clean_host], stdout=subprocess.PIPE).communicate()[0] The .communicate()[0] at the end is important. That tells Popen that we are done, and it returns a tuple: (stdout, stderr). The first item in the tuple [0] is the stdout. You could also use subprocess.check_output(): nslookup_data = subprocess.check_output(["nslookup", clean_host])
{ "language": "en", "url": "https://stackoverflow.com/questions/35946800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add data with image in response I want to send userid with image in response. I am using httpServletResponse class for that. This is my code. I am adding data in header and image in regular body..But I want data with image in body.I dont want to add in header. Is this possible? bytes = objUserMaster.getProfilePicture(); responseImage = ImageIO.read(new ByteArrayInputStream(bytes)); out = response.getOutputStream(); response.addHeader("Hiiiiiii", "message");
{ "language": "en", "url": "https://stackoverflow.com/questions/20738403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to save PDF file directly into the file without using UIActivityViewController or UIDocumentInteractionController iOS? I need to save a PDF document from URL into the device. Is it possible to save the PDF and access it from device file manager without using UIActivityViewController or UIDocumentInteractionController. A: Add these 2 keys in your Info.plist: LSSupportsOpeningDocumentsInPlace and UIFileSharingEnabled. And set YES as the value for both. Now you will be able use the Files app to see any file saved by your app in Documents Directory. A: Swift 5.0 and iOS13 let documentController = UIDocumentPickerViewController(url: exportToURL, in: .exportToService) self.present(documentController, animated: true, completion: nil) exportToURL represent application local URL whichever file want to save into iPhone Files app.
{ "language": "en", "url": "https://stackoverflow.com/questions/53652067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: InvalidPipelineOperator MongoError: Unrecognized expression '$replaceAll' I am running following code in MongoDB: db.response_graphs.aggregate( [ { $match : { "Response_measure" : "MasksMandatory" } }, { $project : { date_end: { $replaceAll: { input: "$date_end", find: "NA", replacement: "2020-08-01" }} } } ] ) I am getting following error: { "message" : "Unrecognized expression '$replaceAll'", "ok" : 0, "code" : 168, "codeName" : "InvalidPipelineOperator", "name" : "MongoError" } I am following the syntax from the following link still getting the above error: https://docs.mongodb.com/manual/reference/operator/aggregation/replaceAll/ Please help me resolve it. Thanks in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/63982187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to differentiate usage and inheritance in a layered architecture? I'm trying to validate the following dependencies: Source In this picture, red relationships are forbidden, green relationships are allowed: * *no class in the adapter package can inherit from a class in the port package; *any class in the adapter package can use (e.g. have a field) a class in the port package; *no class in the service package can use (e.g. have a field) from a class in the port package; *any class in the service package can inherit a class in the port package; If possible I'd like to add these validations to Layered Architecture. Thank you. A: LayeredArchitecture considers all dependencies between layers. You cannot forbid inheritance, but allow access – nor vice versa. I recommend to define individual specific rules instead: @ArchTest ArchRule adapter_should_not_inherit_from_port = noClasses() .that().resideInAPackage("….adapter") .should().beAssignableTo(JavaClass.Predicates.resideInAPackage("….port")); @ArchTest ArchRule service_should_not_access_port = noClasses() .that().resideInAPackage("….service") .should().accessClassesThat().resideInAPackage("….port");
{ "language": "en", "url": "https://stackoverflow.com/questions/70567456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Blueprism get all files contained in a root folder I have a root folder with multiple sub folders and those sub folders could have more sub folders and so on and so forth. I want to run an action and pass it the base folder and get all files that are contained in there (Even in sub folders). The Get files action only gets the files at the first level and to use get folders you'd need to create a huge process which checks every level to see if there are more sub folders and you could potentially miss some files. A: run the command through command prompt maybe and then pipe your results out to read them? something like dir /s /b /o:gn Gives you all sub files etc in a root directory you can use that to pipe your answer into something readable or stdout it direct into a variable in your code if you can. A: Zip Parent folder by using 7z commands or simply by Blueprism Zip Folder action and Use 7z Commands to extract recursive and relocate to single outputpath folder. 7zip tool is free of cost and usually every other organisation has these Tools. Use recursive commands (X) of extraction and set the output path to a single location. 7z will do all the recursive fetching. https://7ziphelp.com/7zip-command-line
{ "language": "en", "url": "https://stackoverflow.com/questions/70033450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the Path for Call_History.db in iOS 6. Is it same as that of iOS5? I am new at iPhone development. I want to access iOS6 call_history. My code work for iOS5 but not work for iOS6. please help me to solve this problem. Many Thanks. A: You cannot access the call log using the SDK and approved APIs. There are some workarounds, as you probably already know. The only option I know about is accessing call_history.db. Take a look at this tutorial. Unfortunately for you, security has been made more severe, and you only can access that file in iOS < 5.0 (and probably all jailbreacked versions).
{ "language": "en", "url": "https://stackoverflow.com/questions/19654495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python: Loop not giving desired result So I'm trying to write a code that simulates a predator and prey situation where it starts off with a low population of predators and high population of prey. Over time the predator population grows while the prey population shrinks until the prey population is too little to sustain the predator population. The predator population dies off and then the prey population is able to repopulate. The simulation is supposed to stop whenever one of the two populations reach 0, in this case the predator population will and plot two populations over time of the simulation until it stopped. This is my code so far: import matplotlib.pyplot as plt def simulate(initialPred, initialPrey, preyGrowth, predationRate, predShrink, predFedBirthRate): preyCounts = [] predatorCounts = [] predatorI = initialPred preyI = initialPrey predator = predatorI prey = preyI while predator > 0 and prey > 0: predator = predatorI * (1 - predShrink + predFedBirthRate * preyI) prey = preyI * (1 + preyGrowth - predationRate * predatorI) predatorCounts.append(predator) preyCounts.append(prey) predatorI = predator preyI = prey plt.plot(predatorCounts, 'r', preyCounts, 'b') plt.show() return preyCounts, predatorCounts simulate(50,1000,0.25,0.01,0.05,0.00002) Its output is this : But it's supposed to come out like this: Can someone help me please? *Also aside from this whenever I put my plotting code outside of the function after the function line with values inside like this: simulate(50,1000,0.25,0.01,0.05,0.00002) plt.plot(predatorCounts, 'r', preyCounts, 'b') plt.show() It doesn't plot the values from the function and says predatorCounts and preyCounts are undefined. A: So you looked at your process/calcs and it seems correct but you look at your result and it's funny. One thing you notice when you print the counts... print predatorI, preyI is that there are fractions of predators and prey which, in the real world, doesn't make sense. You are trying to simulate the real world. All your rate parameters are probably based on whole things, not fractional things. So you decide that there can't be any fractional beings in your simulation and you only deal with whole beings (ints) after the population growth calculations ... Your function returns the count vectors. If you want to move the plotting statements outside of the function you need to assign the function's return value(s) to a name and then use them for plotting. prey, predator, = simulate(50,1000,0.25,0.01,0.05,0.00002) plt.plot(predator, 'r', prey, 'b') plt.show() Here are some things to read from the docs concerning names, scope, namespaces https://docs.python.org/3/tutorial/classes.html#a-word-about-names-and-objects https://docs.python.org/3/reference/executionmodel.html#naming-and-binding You might need to read them periodically as you use the language more. A: If I initialize your plot data with the starting populations and use int() truncation for the populations, I get the plot you say you're supposed to see: import matplotlib.pyplot as plt def simulate(initialPred, initialPrey, preyGrowth, predationRate, predShrink, predFedBirthRate): preyCounts = [initialPrey] predatorCounts = [initialPred] predator = initialPred prey = initialPrey while predator > 0 and prey > 0: predatorScaleFactor = 1.0 - predShrink + predFedBirthRate * prey preyScaleFactor = 1.0 + preyGrowth - predationRate * predator predator = int(predator * predatorScaleFactor) prey = int(prey * preyScaleFactor) predatorCounts.append(predator) preyCounts.append(prey) plt.plot(predatorCounts, 'r', preyCounts, 'b') plt.show() return preyCounts, predatorCounts simulate(50, 1000, 0.25, 0.01, 0.05, 0.00002)
{ "language": "en", "url": "https://stackoverflow.com/questions/40791807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Writing unit tests with QTestLib this is my first step into the world on unit-testing so please be patient. I'm writing a Qt 4.8.1 C++ program and as test framework I'm using the integrated QTestLib. I should test a class that inhrerits from a base one and that loads a certain XML file to read and parse it later with a function that will return a C++ class object with the xml values that I can retrieve and set via set/get functions. The class in the constructor instantiate a QFile object and in the readXml function I use it to parse with the QXmlStreamReader the file. What's the best way to test all this class with unit-tests? I don't see how I could bypass the file-read operation to inject a own string representing the file content. Or should I use as test content a different ad-hoc XML file? A: Injecting a string to represent the file contents seems like it would be the most straightforward way of testing a class such as this. However, directly instantiating a QFile instance in your class constructor makes this impossible (in other words, it's impossible to inject your dependency). Moreover, it's quite a bit of work to create a "Fake" or "Mock" version of a QFile (a.k.a. a Test Double of a QFile). The easiest way to resolve this is to pass a QIODevice into your class constructor (QFile inherits from QIODevice). In your unit test, you can fake the contents of the file by passing in a QIODevice with the contents you wish to test. In this case, you can accomplish this with a QBuffer, which allows you to arbitrarily set its contents. As such, your class would like something like the following: class MyXmlParser { MyXmlParser(QIODevice* device); ... }; Your unit test constructs the class with a QBuffer; your production code constructs it with a QFile. Should I use a real XML file in my test? Generally speaking, the more external dependencies your unit test has, the more costly it is to ensure that it doesn't break in the future (it potentially makes your unit test sensitive to its context). As such, it is advisable to avoid using a real XML file in order to ensure that your test is self-contained. Moreover, passing in a real XML means that you are now implicitly testing QFile as well as your XML parser (in other words, it's not longer a unit test, it's an integration test). You can generally assume that the IO device that you pass into your parser works; you only need to verify that your parser uses the IO device correctly and that it can parse the XML properly. Consider reading through the material at xunitpatterns.com, particularly the section on Test Smells.
{ "language": "en", "url": "https://stackoverflow.com/questions/12030534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Property list in a Model property couldn't be mapped while trying to migrate I'm setting up a migration in an MVC5 that has a Model that's called "Order" with 3 properties, one of them is a class of PizzaModel. PizzaModel has the code below, what I'm trying to do is to enable multiple instances of pizzas in a single Order, so one Order can have many pizzas. public class PizzaModel { [Key] public int Id { get; set; } public List<PizzaSet> Pizzas { get; set; } public int Cost { get; set; } } public class PizzaSet { public enum Toppings { GreenOlives, BulgarianCheese, Onions, Mushrooms, Peppers, Basil, Sausage, Pepperoni, Ham, Beef } public enum Sauces { BBQ, Islands } public enum Size { Personal, Medium, Family } public Size PizzaSize { get; set; } public List<Sauces> PizzaSauces { get; set; } public List<Toppings> PizzaToppings { get; set; } } Is this a wrong approach for a migration? A: Your PizzaSet class is using a List of Enums, which will not map to a database schema in EF. If you want to use an enum for Sauces and Toppings and want to allow multiple selections, you need to use the [Flags] property for the enum, to treat it as a bit field. public class PizzaSet { [Flags] public enum Toppings { GreenOlives = 1, BulgarianCheese = 2, Onions = 4, Mushrooms = 8, Peppers = 16, Basil = 32, Sausage = 64, Pepperoni = 128, Ham = 256, Beef = 512 } [Flags] public enum Sauces { BBQ = 1, Islands = 2 } public enum Size { Personal, Medium, Family } public Size PizzaSize { get; set; } public Sauces PizzaSauces { get; set; } public Toppings PizzaToppings { get; set; } } Then Toppings and Sauces become a bit field of possible values (notice the values will need to represent unique bits) To select multiple toppings:- PizzaSet ps = new PizzaSet(); ps.Toppings = Toppings.GreenOlives | Toppings.Peppers; However, given your list of toppings and sauces may change over time, it's probably better to have a separate table that lists toppings, and use a join table (since it's EF Core) A: You have enums as your list type. If youre storing this data in a database. The database needs a placeholder to store the enum values. In general this is done by a table. So, if you make classes of your enums, these will be translated to tables and the mapping will work. public class Topping { public string Name {get;set;} } Use this class as your list type. Do note that you need to fill the topping, sauces and etc. tables. The good news is: you can extend them without changing the code :-) Alternatively, you can put the [NotMapped] attribute on your property. Do note that this won't help you in your specific case because it would not store the toppings in the database then.
{ "language": "en", "url": "https://stackoverflow.com/questions/57344222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Flutter : stack & Ink overlay I am using a Stack to recreate this effect : But for some reason, using the Ink widget to be able to get the gradient effect, this is what I have : This is my code : Stack( children: [ SizedBox( height: 100.0, width: 100.0, child: ClipRRect( borderRadius: BorderRadius.circular(20.0), child: CachedNetworkImage( imageUrl: 'https://images.unsplash.com/photo-1570296767266-60ccc88974a5', fit: BoxFit.cover, placeholder: (context, url) => MC_Shimmer(), ), ), ), Positioned( right: -5.0, bottom: -5.0, child: SizedBox( height: 30.0, width: 30.0, child: Ink( decoration: BoxDecoration( gradient: gradient, borderRadius: BorderRadius.all(Radius.circular(5.0)), ), child: Icon( OMIcons.cameraAlt, color: Colors.white, size: 15.0, ), ), ), ) ], ), A: you can use Container instead of Ink and able to use gradient effect. Positioned( right: -5.0, bottom: -5.0, child: SizedBox( height: 30.0, width: 30.0, child: Container( decoration: BoxDecoration( gradient: gradient, borderRadius: BorderRadius.all(Radius.circular(5.0)), ), child: Icon( OMIcons.cameraAlt, color: Colors.white, size: 15.0, ), ), ), ) A: I tried this in dart pad it worked alright. Positioned( right: -5.0, bottom: -5.0, child: SizedBox( height: 30.0, width: 30.0, child: Material( child: Ink( decoration: BoxDecoration( gradient: LinearGradient( colors: [Colors.pink, Colors.yellow]), borderRadius: BorderRadius.all(Radius.circular(5.0)), ), child: Icon( Icons.camera, color: Colors.white, size: 15.0, ), ), ), ), )
{ "language": "en", "url": "https://stackoverflow.com/questions/63493092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: There is a way to use not operator in regex when ^ inside bracket is not an option? I went through dozen of already answered Q without finding one that can help me. I have a string like this: aaa.{foo}-{bar} dftgyh {foo-bar}{bar} .? {.!} -! a}aaa{ and I want to obtain a string like this: aaa{foo}-{bar}dftgyh{foo-bar}{bar}-aaaa Essentially I want to keep: * *valid word chars and hyphens wrapped in an open and a closed curly bracket, something that will match the regex \{[\w\-]+\} *all the valid word chars and hyphens outside curly brackets Using this: $result = preg_replace( array( "#\{[\w\-]+\}#", '#[\w\-]#' ), "", $string ); I obtain the exact contrary of what I want: I remove the part that I want to keep. Sure I can use ^ inside the square brackets in the second pattern, but it will not work for the first. I.e. this will not work (the second pattern in the array is valid, the first not): $result = preg_replace( array( "#[^\{[\w\-]+\}]#", '#[^\w\-]#' ), "", $string ); So, whis the regex that allow me to obtain the wanted result? A: You may consider matching what you want instead of replacing the characters you do not want. The following will match word characters and hyphen both inside and outside of curly braces. $str = 'aaa.{foo}-{bar} dftgyh {foo-bar}{bar} .? {.!} -! a}aaa{'; preg_match_all('/{[\w-]+}|[\w-]+/', $str, $matches); echo implode('', $matches[0]); Output as expected: aaa{foo}-{bar}dftgyh{foo-bar}{bar}-aaaa A: Also an option to (*SKIP)(*F) the good stuff and do a preg_replace() with the remaining: $str = preg_replace('~(?:{[-\w]+}|[-\w]+)(*SKIP)(*F)|.~' , "", $str); test at regex101; eval.in
{ "language": "en", "url": "https://stackoverflow.com/questions/25828554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: My table won't show the border i defined in css I'm trying to edit the borders of my table in css but the border's won't show. Here's the code : .midden { text-align: center; } .lijstje { list-style: inside; text-align: left; padding-left: 40%; } .naamkolom { background-color: lightgreen; font-weight: bold; border-radius: 25px; border-top: 2px chartreuse; } table { border: 25px green; } body { background-color: antiquewhite; } p { font-size: 25px; font-family: Georgia; } <h1 class="midden">Italiaanse Recepten</h1> <table> <tr> <td class="naamkolom">Recepten</td> <td class="naamkolom">Ingrediënten</td> <td class="naamkolom">Bereiding</td> </tr> <tr> <td>Spaghetti carbonara met andijvie</td> <td> <ul> <li>300 g spaghetti</li> <li>250 g champignons</li> <li>100 g Parmezaanse kaas</li> <li>300 g gerookte spekreepjes</li> <li>400 g gesneden andijvie</li> <li>3 eieren</li> </ul> </td> <td> <ol> <li>Kook de spaghetti volgens de aanwijzingen op de verpakking.</li> <li>Snijd ondertussen de champignons in plakjes. Rasp de Parmezaanse kaas.</li> <li>Verwarm een ruime hapjespan zonder olie of boter en bak de spekjes 3 min. op middelhoog vuur. Voeg de champignons en de andijvie in delen toe en bak nog 5 min. Schep regelmatig om. Breng op smaak met peper en eventueel zout.</li> <li>Doe ondertussen de eieren in een kom en klop met 2/3 van de kaas los tot saus.</li> <li>Giet de spaghetti af en doe terug in de pan. Voeg al roerend de saus toe. Blijf roeren tot de saus iets is ingedikt. Schep het andijviemengsel erdoor. Verdeel over de 4 borden en bestrooi met de rest van de kaas.</li> </ol> </td> </tr> <tr> <td>Pangrattato</td> <td> <ul> <li>ciabatta</li> <li>75 ml olijfolie</li> <li>2 tl chilivlokken (molentje)</li> <li>2 tenen knoflook</li> </ul> </td> <td> <ol> <li>Maal de ciabatta in de keukenmachine tot broodkruim</li> <li>Verhit de olijfolie in een grote koekenpan.</li> <li>Voeg het broodkruim en de chilivlokken, peper en eventueel zout toe en bak in 5 min. op middelhoog vuur krokant.</li> <li>Schep regelmatig om. Snijd ondertussen de knoflook fijn. Voeg de knoflook aan de pan toe en bak 2 min. mee op laag vuur.</li> <li>Neem de pan van het vuur en laat de pangrattato afkoelen.</li> </ol> </td> </tr> </table> <a href="Huiswerk.html">Terug naar startpagina</a> I really don't understand why the border isn't showing, since i can get the top columns to change color and the title to center, so the css file is working. I've also tried creating a selective class for the table and assigning that in the html file but that didn't work either. A: table { border: 25px solid green; } instead of table { border: 25px green; } A: You have to define the type of border, so in your case I guess you want a solid border. Here you have all css types of borders
{ "language": "nl", "url": "https://stackoverflow.com/questions/32487012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PIG Group by avoid Bag This is a basic PIG question. I have my data something like this 10 | Dog 15 | Cow 20 | Dog 15 | Elephant 15 | Dog 25 | Elephant I want to find the average weight of each animal and have the output as this : Dog | 12.5 Elephant | 20 Cow | 15 I am able to use GROUP by and get the result, but the result is a bag, something like this : {(Dog), (Dog) } | 12.5 {(Elephant), (Elephant)} | 20 {(Cow)} | 15 How can I extract just the individual animal ? I am using GROUP by like this. --animal_weight is derived through other means animal_by = GROUP animal_weight by (animal); results = FOREACH animal_by GENERATE animal_weight.animal as animal_name, AVG(animal_weight.weight) as kg; STORE results INTO '$output_4' USING PigStorage('|'); A: Use group instead of animal_weight.animal.Note that from your sample data,Dog should have an average of weight (10+20+15)/3 = 15 kg results = FOREACH animal_by GENERATE group as animal_name, AVG(animal_weight.weight) as kg; Output
{ "language": "en", "url": "https://stackoverflow.com/questions/46700084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to get data from child form into selected Parent DataGridView Cell I have been stumped on a programming issue. When I right click on a cell of a DataGridView object, a context menu will show. From that context menu, a user can click an option. That option will show a form. When the user is finished, the resultant of that form will be populated in the selected cell. Problem: How do I get the result from the child form into the selected cell? There are multiple DataGridView objects on the parent form that use the same functionality. Code: private void commandOperation(Object sender, EventArgs e) { if (sender == dec2HexToolStripMenuItem) { frmNumFormatConv form = new frmNumFormatConv(); if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK) { // Get data from the form into the selected cell!!! } } else { throw new Exception("Operational object unknown"); } } private void cellMouseDown(Object sender, DataGridViewCellMouseEventArgs e) { if (sender == dgvCircuit1TestSetup || sender == dgvCircuit2TestSetup) { if (e.Button == MouseButtons.Right) { ((DataGridView)sender).CurrentCell = ((DataGridView)sender).Rows[e.RowIndex].Cells[e.ColumnIndex]; itsGridContextMenu.Show((DataGridView)sender, new Point(e.X, e.Y)); } } } A: A very easy way is to put a public property in the popup form that will return the values you want (Say RtnValue). Then This is an example for popup form: public string RtnValue { set { textBox1.Text = value; } } This is your current code: frmNumFormatConv form = new frmNumFormatConv(); if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK) { dgvalue = form.RtnValue; // Get data from the form into the selected cell!!! }
{ "language": "en", "url": "https://stackoverflow.com/questions/24808329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why when I merge 2 pdf files with `gs` (ghostscript) the identify command cannot get the page count? This my gs command than merges 2 one-page pdf file: gs -dNOPAUSE -dSAFER -sDEVICE=pdfwrite -sOUTPUTFILE=/tmp/blahblahblah.pdf -dBATCH page1.pdf page2.pdf And this is the output: GPL Ghostscript 8.70 (2009-07-31) Copyright (C) 2009 Artifex Software, Inc. All rights reserved. This software comes with NO WARRANTY: see the file PUBLIC for details. Processing pages 1 through 1. Page 1 Processing pages 1 through 1. Page 1 Can't find (or can't open) font file /usr/share/ghostscript/8.70/Resource/Font/ArialMT. Can't find (or can't open) font file ArialMT. Can't find (or can't open) font file /usr/share/ghostscript/8.70/Resource/Font/ArialMT. Can't find (or can't open) font file ArialMT. Querying operating system for font files... Can't find (or can't open) font file /usr/share/ghostscript/8.70/Resource/Font/ArialMT. Can't find (or can't open) font file ArialMT. Didn't find this font on the system! Substituting font Helvetica for ArialMT. Loading NimbusSanL-Regu font from /usr/share/fonts/default/Type1/n019003l.pfb... 3397696 1943901 17192756 15861178 3 done. The font ArialMT is not found and Helvetica is substituted with it. I got the merged file from server by scp and opened it in my local system. The file is properly merged including 2 pages. So file has no problem. Now I use the below command in order to get the PDF page count: identify -format %n '/tmp/blahblahblah.pdf' This command cannot get the page count and gives the below error: identify: Postscript delegate failed `/tmp/blahblahblah.pdf': No such file or directory @ error/pdf.c/ReadPDFImage/664. NB: I should note that file exist in /tmp/blahblahblah.pdf path! Why I cannot get page count via identify? Sample files are attached in link below: 2 PDF sample file
{ "language": "en", "url": "https://stackoverflow.com/questions/40818839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to block ip Ranges using http modules? How to block Ip ranges using http modules with c# . I have a simple solution but its for single Ip and How can I read IPs from xml file in http modules so that if an IP is there in that file it will be blocked .Here is my code public class MyHandler :IHttpModule { public MyHandler(){} public bool IsReusable { get { return false; } } public void Init(HttpApplication context) { context.BeginRequest += new EventHandler(Application_BeginRequest); } private void Application_BeginRequest(object source, EventArgs e) { HttpContext context = (source as HttpApplication).Context; List<string> BlackListIp = new List<string>(); BlackListIp.Add("127.0.0.1"); if (BlackListIp.Contains(context.Request.UserHostAddress)) { context.Response.Write("<h1 style='color:red;'>Your IP is Blocked</h1>"); } } public void Dispose() { } } A: Just add the xml file inside app_data folder and read it using XDocument. You can event use Cache with FileDependency to improve performance.
{ "language": "en", "url": "https://stackoverflow.com/questions/10358813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Disable other checkboxes in a GroupBox when two are checked Private Sub AllBoxes_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged, CheckBox2.CheckedChanged, CheckBox3.CheckedChanged, CheckBox4.CheckedChanged, CheckBox5.CheckedChanged, CheckBox6.CheckedChanged Dim qty As Int16 = 0 Dim cb As CheckBox For Each cb In GroupBox8.Controls.OfType(Of CheckBox) If cb.Checked Then qty += 1 End If Next If qty = 2 Then For Each cb In GroupBox8.Controls.OfType(Of CheckBox) If Not cb.Checked Then cb.Enabled = False End If Next Else For Each cb In GroupBox8.Controls.OfType(Of CheckBox) cb.Enabled = True Next End If End Sub it just doesn't work. The groupbox's name is groupbox8 and it has 6 checkboxes on it. I need to select two checkboxes. A: You can simplify a lot your CheckedChanged event handler using a bit of Linq Private Sub AllBoxes_CheckedChanged(sender As Object, e As EventArgs) ' Get all checkboxes in the groupBox8 Dim checks = groupBox8.Controls.OfType(Of CheckBox)() ' Count how many are checked Dim cnt = checks.Where(Function(x) x.Checked).Count() If cnt < 2 Then ' Enable all, avoid an if and don't care if already enabled For Each c In checks c.Enabled = True Next Else ' Disable all except the two checked... For Each k In checks.Where(Function(x) Not x.Checked) k.Enabled = False Next End If End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/42454862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Cannot access XML Document using simplexml_load_file() I NEED HELP! I'm trying to generate XML document from my website database in hosting provider and accessing it from my home PC, right now I'm doing it in localhost environment. I use these codes and I got error message in browser. Please take a look at my codes... data.php for generating XML document <?php include ("koneksi-database.php"); header('Content-Type: text/xml'); echo "<?xml version='1.0'?>"; echo "<outbox>"; $query = "SELECT * FROM `tbstatus` WHERE `status` = '$status' ORDER BY `ID`"; $result = mysql_query($query); while ($data = mysql_fetch_array($result)) { echo "<data>"; echo "<trx>".$data['trx']."</trx>"; echo "<status>".$data['status']."</status>"; echo "<signature>".$data['signature']."</signature>"; echo "<time>".$data['time']."</time>"; echo "</data>"; } echo "</outbox>"; ?> read.php for reading the XML document in localhost print_r($dataxml = simplexml_load_file('data.php')); I also create index.php for running the script every 5 seconds. <html> <head> <script type="text/javascript"> var xmlhttp; function ajax() { if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp =new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { // do nothing } } xmlhttp.open("GET","read.php"); xmlhttp.send(); setTimeout("ajax()", 5000); } </script> </head> <body onload="ajax();"> <h1>Server is Running...</h1> </body> </html> finally this the error messages that i get from browser when I open read.php. Warning: simplexml_load_file() [function.simplexml-load-file]: data.php:9: parser error : Start tag expected, '<' not found in C:\xampplite\htdocs\simpul\baca.php on line 9 Warning: simplexml_load_file() [function.simplexml-load-file]: echo "<?xml version='1.0'?>"; in C:\xampplite\htdocs\simpul\baca.php on line 9 Warning: simplexml_load_file() [function.simplexml-load-file]: ^ in C:\xampplite\htdocs\simpul\baca.php on line 9 A: Your print_r($dataxml = simplexml_load_file('data.php')); is reading you raw PHP file, not the script execution result! data.php file have a PHP code that outputs a XML file, not a really XML file. You should use print_r($dataxml = simplexml_load_file('http://localhost/data.php')); for example. (Assuming that http://localhost/data.php is the url to access your file.) using only 'data.php' as parameter will get the raw file from server, not processed by PHP.
{ "language": "en", "url": "https://stackoverflow.com/questions/22752522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Referencing the current jQuery object in a chain? At DevDays in SF last year (before jQuery 1.4 was released), I thought they mentioned an upcoming feature in 1.4 that would allow you to reference the current jQuery object while in a chain. I've read through all of the 1.4 improvements and wasn't able to find it. Does anyone know how this can be done? Example Being able to access the current jQuery object would be helpful when working with methods that are in relation to the current object like .next(): // Current way var items = $(this).closest('tr'); items = items.add(items.next(':not([id])')); // Magical 1.4 way? Is there a "chain"-like object? var items = $(this).closest('tr') .add(chain.next(':not([id])')); A: I think this is the closest available, using .andSelf(): var items = $(this).closest('tr').next(':not([id])').andSelf(); This goes to the .next() call, but then adds the tr back to it. Everything is in the context of where the chain occurs, so either jumping around to add elements, or storing the original reference as you have it is as close as is currently available. These are the helpful functions for jumping around: http://api.jquery.com/category/traversing/miscellaneous-traversal/ John Resig posted this concept a while back, but to my knowledge, nothing closer to that has made it into jQuery core. You can however use the code posted on the blog there if you want. A: Possibly andSelf() http://api.jquery.com/andSelf/ This returns the previous selection, but you would then have to use :not([id]) on everything..
{ "language": "en", "url": "https://stackoverflow.com/questions/2647597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android Image Upload Fails I'm trying to upload an image from my phone to a server. So I get the image uri and create a NameValuePair with it. I then use the following Android code to get a connection and upload the pic. This was taken from previous stackoverflow question(I would link but can't find it even with Google...) public void post(String url, List<NameValuePair> nameValuePairs) { HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpPost httpPost = new HttpPost(url); try { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart(nameValuePairs.get(0).getName(), new FileBody(new File(nameValuePairs.get(0).getValue()))); Log.v("Uploading file",nameValuePairs.get(0).getValue()); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost); Log.v("Response", response.toString()); } catch (IOException e) { e.printStackTrace(); } } On the server side I have the following code. This is PHP, which I am a complete novice at. I know there is no validation in the code, but I want to get the upload working before I start worrying about everything else. <?php if($_FILES){ $name = $_FILES['image']['name']; move_uploaded_file($_FILES['image']['temp'],$name); echo "success!"; } else { echo "Nothing uploaded"; } ?> Here the name of the NameValuePair is 'image', which is used as the file name. Nothing gets uploaded, but a connection is made. Please help. Following the request I put print_r($Files) in the code. The respons from the server was: 09-05 23:23:35.745: VERBOSE/Response(13849): Array 09-05 23:23:35.745: VERBOSE/Response(13849): ( 09-05 23:23:35.745: VERBOSE/Response(13849): [image] => Array 09-05 23:23:35.745: VERBOSE/Response(13849): ( 09-05 23:23:35.745: VERBOSE/Response(13849): [name] => DSC_0100.jpg 09-05 23:23:35.745: VERBOSE/Response(13849): [type] => 09-05 23:23:35.745: VERBOSE/Response(13849): [tmp_name] => /tmp/phpXcY8L1 09-05 23:23:35.745: VERBOSE/Response(13849): [error] => 0 09-05 23:23:35.745: VERBOSE/Response(13849): [size] => 806873 09-05 23:23:35.745: VERBOSE/Response(13849): ) 09-05 23:23:35.745: VERBOSE/Response(13849): ) 09-05 23:23:35.745: VERBOSE/Response(13849):** A: On server side please add this code , print_r($_FILES); then check for array parameter 'error' then check error code from here http://php.net/manual/en/features.file-upload.errors.php if you want the file upload code for android then please tell me i can post here i hope this will help you. Thank you. A: move_uploaded_file($_FILES['image']['temp'],$name); replace this line with move_uploaded_file($_FILES['image']['tmp_name'],$name); The file's temporary file name is in "tmp_name", as i can see from your log output.
{ "language": "en", "url": "https://stackoverflow.com/questions/7309222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: RPN stacking method not working with converted string arrays I'm trying to make a program that processes a line of rpn expression through a stack method. The input is a string array that is converted from a string input. String[] collect = "8 6 + 2 /"; //the String line; //the inputed line collect = line.split(" "); //the conversion System.out.println(stackem(collect)); // calling the stack method for an output method The problem is that the output is always the operator ate the end of the line, so when I put in the code that checks for malformed expressions it always turns into the error. Basically my input would be like this: input: 8 6 + 2 / output: Error: "Expression is malformed" output (without the error code): / output (what's supposed to be the output): 7 This is the code for the stack method: public String stackem(String[] input) { Stack<String> stack = new Stack<String>(); int x, y; String result = ""; int get = 0; String choice; int value = 0; String p = ""; int output; try { for (int i = 0; i < input.length; i++) { if (input[i] == "+" || input[i] == "-" || input[i] == "*" || input[i] == "/" || input[i] == "^") { choice = input[i]; } else { stack.push(input[i]); continue; } switch (choice) { case "+": x = Integer.parseInt(stack.pop()); y = Integer.parseInt(stack.pop()); value = x + y; result = p + value; stack.push(result); break; case "-": x = Integer.parseInt(stack.pop()); y = Integer.parseInt(stack.pop()); value = y - x; result = p + value; stack.push(result); break; case "*": x = Integer.parseInt(stack.pop()); y = Integer.parseInt(stack.pop()); value = x * y; result = p + value; stack.push(result); break; case "/": x = Integer.parseInt(stack.pop()); y = Integer.parseInt(stack.pop()); value = y / x; result = p + value; stack.push(result); break; case "^": x = Integer.parseInt(stack.pop()); y = Integer.parseInt(stack.pop()); value = (int)Math.pow(y,x); result = p + value; stack.push(result); break; default: continue; } } output = Integer.parseInt(stack.pop()); } catch (Exception ex) { return "Error: Expression is malformed"; } return "Result: " + output; } Is there any way to fix this issue?
{ "language": "en", "url": "https://stackoverflow.com/questions/70252174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Paypal recurring payment IPN usage I successfully create a listener and it is working well if I am using the IPN simulator. However, when I am doing the payment request in the process of payment, I set the same listener url for the notify_url, nothing happens even the process working properly. How can I know if someone cancel his recurring payment directly from the Paypal or how do I setup up the listener whenever a recurring payment is made? Is it something wrong with my notify_url? This is what my notify_url look like: http://example.com/paypal_notification/ipn_callback No extra parameters. Is it correct? Thank you in advance. A: You should be getting an IPN when the profile is created, each time the recurring profile bills, and when the profile is cancelled. Check your IPN history in your account to make sure the IPN's are being sent out, and check to see if there is any type of error being returned to PayPal. Check your server access logs to see PayPal is calling your script and check your error logs to see if anything is being triggered. Try adding www. to your URL, and the ext to the end of your URL for the type of file it is. Also, there are some IPN troubleshooting tips I posted for IPN on this forum POST. A: The IPN will only be sent to the account on which the profile was created. Here's how I would do it. * *Store the Paypal ProfileID and e-mail address in a database. *Receive all of the IPN notifications yourself, and in the case of a failure, send an e-mail to the specific user based on their ProfileID, or perform other actions.
{ "language": "en", "url": "https://stackoverflow.com/questions/16235962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python: How can I find the heading of the road using Google Maps API? I wrote a program in python that takes in a starting point and end point and then uses google maps API to create a gif of the route using google street view. Everything works perfectly I just can't find a way to get the bearing/heading of the car. The resulting gifs is the correct path but the camera doesn't point at the road. https://www.dropbox.com/s/b17el2lmiyna7m6/finalproduct8fps.gif?dl=0 here is sample to show you what I mean, the camera isn't pointing at the road at all times, how can I get the heading of the vehicle?
{ "language": "en", "url": "https://stackoverflow.com/questions/45390991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Android lint custom check UCallExpression type of method receiver I'm writing custom lint check to ban some methods. So if someone calls banned method foo on instance of class A, lint should report error. I achieved this for static methods like this (inside visitCallExpression(UCallExpression): node.receiver as UReferenceExpression).getQualifiedName() From qualified name I can get the Class object and run my check but I can't get the qualified name for methods called on instantiated object. I can get the name of the class to which the objects belongs but not the qualified name. How do I get qualified name of class of method that is called on instance of that class? If I'm being unclear, here is an example. import android.view.Button; class ButtonSetTextIntClass { private Button button; public void bannedSetText (){ button.setText(123); } } And I need in visitCallExpression (UCallExpression) get qualified name/class of button. A: UCallExpression.receiverType does what you want: public class CustomDetector extends Detector implements SourceCodeScanner { @Nullable @Override public List<Class<? extends UElement>> getApplicableUastTypes() { return Collections.singletonList(UCallExpression.class); } @Nullable @Override public UElementHandler createUastHandler(@NotNull JavaContext context) { return new UElementHandler() { @Override public void visitCallExpression(@NotNull UCallExpression node) { node.getReceiverType(); // PsiType:Button } }; } } To extract qualified name you can use the following method: ((PsiClassType) node.getReceiverType()).resolve().getQualifiedName() // android.widget.Button A: I found a solution which works for both static and non-static methods and for Kotlin top level functions. Not sure if it is the best way to do it but at least it works. override fun visitCallExpression(node: UCallExpression) { (node.resolve()?.parent as? ClsClassImpl)?.stub?.qualifiedName } A: /** * eg: android.util.Log * ps. imports was initialized in visitImportStatement */ private fun getClassNameWithPackage(node: UCallExpression): String { var className = node.resolve()?.containingClass?.qualifiedName if (className != null) { return className } className = getClassName(node) ?: return "" for (import in imports) { if (import.contains(className)) { return import } } return "$packageName.$className" } /** * eg: Log */ private fun getClassName(node: UCallExpression): String? { return node.receiver?.javaPsi?.text ?: when (val uExpression = (node.methodIdentifier?.uastParent as UCallExpression?)?.receiver) { is JavaUSimpleNameReferenceExpression -> { uExpression.identifier } is KotlinUSimpleReferenceExpression -> { uExpression.identifier } is UReferenceExpression -> { uExpression.getQualifiedName() } else -> null } }
{ "language": "en", "url": "https://stackoverflow.com/questions/53847469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: sphinxsearch-0.9 in mediawiki-1.32.0 error 2019/01/14 12:04:51 [error] 21549#21549: *3558 FastCGI sent in stderr: "PHP message: PHP Fatal error: Class SphinxMWSearch contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods (SearchDatabase::doSearchTextInDB, SearchDatabase::doSearchTitleInDB) in /var/opt/www/extensions/SphinxSearch/SphinxMWSearch.php on line 15" while reading response header from upstream, client: 192.168.122.1, server: wiki.yuyizhi.org, request: "GET /index.php?title=Special:%E6%90%9C%E7%B4%A2&search=sphinx HTTP/1.0", upstream: "fastcgi://unix:/var/run/php-fpm/php5-fpm.sock:", host: "wiki.yuyizhi.org" FastCGI sent in stderr: "PHP message: PHP Fatal error: Class SphinxMWSearch contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods (SearchDatabase::doSearchTextInDB, SearchDatabase::doSearchTitleInDB) in /var/opt/www/extensions/SphinxSearch/SphinxMWSearch.php on line 15", client: 192.168.122.1, server: wiki.abc.com, request: "GET /api.php?action=opensearch&search=bai&namespace=0 HTTP/1.0", host: "wiki.abc.com" A: The SearchDatabase class that SphinxSearch extends was changed from REL1_31 to REL1_32. It now requires you to define doSearchTextInDB and doSearchTitleInDB methods. See REL1_31 https://doc.wikimedia.org/mediawiki-core/REL1_31/php/classSearchDatabase.html vs REL1_32 https://doc.wikimedia.org/mediawiki-core/REL1_32/php/classSearchDatabase.html This is sortof mentioned in the patch notes if you search for Search under deprecation (note this is a Backwards compatibility break instead) https://www.mediawiki.org/wiki/Release_notes/1.32#Compatibility: Overriding SearchEngine::{searchText,searchTitle,searchArchiveTitle} in extending classes is deprecated. Extend related doSearch* methods instead. If you are like me and not comfortable fixing the extension yourself, you will have to wait for one of the extension contributors to update the extension to work with REL1_32. Until then you will have to stay on REL1_31 if you wish to use the extension. A: Just adding these two empty functions to SphinxMWSearch.php under the definition of SphinxMWSearch class seems to do the trick. It makes it stop complaining and - as far as I can tell - search function is working fine. function doSearchTextInDB($term) { } function doSearchTitleInDB($term) { } Hopefully developers of this extension will come up with a proper fix soon.
{ "language": "en", "url": "https://stackoverflow.com/questions/54195774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android App actions issues when English Articles are used as a part of speech We have implemented android shortcuts. Testing of App actions on physical devices was fine, except for an issue with English Articles. When English Articles appear as a part of a statement, the statement is not recognized as an action, and Assistant does not redirected to the app. For example, 'add note to Express Scheduler' is recognized, while 'add a note to Express Scheduler' is not. My question is whether anybody have experienced similar issues? Please, see capabilities segment extracted from shortcuts.xml. I am using actions.intent.CREATE_THING and actions.intent.GET_THING BIIs. I've listed one example above: 'add note to Express Scheduler' is recognized, while 'add a note to Express Scheduler' is not. <capability android:name="actions.intent.CREATE_THING"> <intent> <url-template android:value="https://vijac.ca/schedule{?name,description}" /> <parameter android:name="thing.name" android:key="name" android:required="false" /> <parameter android:name="thing.description" android:key="description" android:required="false" /> </intent> </capability> <capability android:name="actions.intent.GET_THING"> <intent> <url-template android:value="https://vijac.ca/search{?name}" /> <parameter android:name="thing.name" android:key="name" /> </intent> </capability>enter code here Thank you! A: I think what may be happening is that you have a very generic name of the thing ("a note"), when it is expecting to handle specific names which normally don't need an article ("Pixel 4", "Stairway to Heaven"). You may want to try one of these to address the problem: * *The thing.name parameter for that BII allows for an inline inventory which is a way of setting allowable values and alises for those values. You can create an inventory item for note that has aliases such as "a note" and "note". *Consider using the actions.intent.CREATE_DIGITAL_DOCUMENT BII which indicates that it supports phrases such as "Create a note".
{ "language": "en", "url": "https://stackoverflow.com/questions/73200296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: htaccess redirect .PDF for Prevent Direct Access but visible in internal viewer I'm developing with a small web-based project with WordPress which contains a lot of PDF files. What I'm looking for is to close the direct access to PDF files, like in https://sciami.com/scm-content/uploads/2018/06/myfile.pdf and redirect the request to the attachment page in https://sciami.com/myfile. To do this, I wrote a code in .htaccess as below: RewriteCond %{REQUEST_URI} \.pdf$ [NC] RewriteRule ^scm-content/uploads/([0-9]+)/([0-9]+)/(.+)\.pdf$ /$3 [R=301,L] In this way all PDFs are redirected to related attachment page (and it works!). Inside the attachment page, there is a PDF viewer that shows related PDF file. But because of the rule written in the .htaccess, the PDF viewer doesn't show anything because the https://sciami.com/scm-content/uploads/2018/06/myfile.pdf URL necessary for show PDF is rewritten. My question is how to close the direct access to PDFs, while allowing them to be loaded within the viewer? The condition RewriteCond %{HTTP_REFERER} !^https://(www.)?sciami.com/ [NC] allows operation within the site, but prevents redirect from within the site. Every help is welcome.
{ "language": "en", "url": "https://stackoverflow.com/questions/51994257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Filter custom post types by Post Object Custom Field I have post types named "tour" and "country". "tour" post type has some custom fields and type of one of them is Post Object and filtered by Post Type "country". Now I want to show tours filtered by a specific country, for example: $located_tours = get_posts(array( 'numberposts' => 3, 'post_type' => 'tour', 'meta_key' => 'country', 'meta_value' => 'turkey' )); But the result for this query shows nothing. I know "country" I have used as meta_key is an object, but how can I use it correctly in my query? Anyone has any idea? Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/36809196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Laravel Controller beforeFilter not working as expected My controllers constructor looks like function __construct(MessageRepository $message) { $this->beforeFilter('canViewThisMessage', array('only', 'show')); $this->message = $message; $this->pagesize = 8; $this->pageTitle = 'messages'; } and I expect the filter to be applied on show action. Which looks like public function show($id) { $message = Message::findOrFail($id); return View::make('messages.show', compact('message')); } But the filter is applied on all actions, not just on show method! Why is this happening? A: I think instead of: $this->beforeFilter('canViewThisMessage', array('only', 'show')); you should use: $this->beforeFilter('canViewThisMessage', array('only' => ['show'])); or $this->beforeFilter('canViewThisMessage', array('only' => 'show')); looking at documentation
{ "language": "en", "url": "https://stackoverflow.com/questions/26127991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: html5shiv.js and respond.js without Bootstrap 3 <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> Whenever I search for these scripts on the internet they are always connected with Bootstrap 3. Should I use them in any responsive website using HTML5?
{ "language": "en", "url": "https://stackoverflow.com/questions/34074418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: setColorFilter not working with resource color If I use setColorFilter like this, it works and paint my image with the chosen color: int color = Color.parseColor("#FF0000"); viewHolder.Icon.setColorFilter(color); But if I try to use a resource color, it does nothing: viewHolder.Icon.setColorFilter(R.color.colorPrimary); where the resource is defined like this: <?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#FF5722</color> </resources> A: try this int actionBarBackground = getResources().getColor(R.color.actionBarBackground); and you set actionBarBackground in the method setColorFilter thats all A: Answer marked as "right" use getColor() method which is deprecated. That's why here is up-to-date answer: int color = ResourcesCompat.getColor(getResources(), R.color.my_color, null); A: please add PorterDuff.Mode.MULTIPLY See below example viewHolder.Icon.getDrawable().setColorFilter(getResources().getColor(R.color.blue), PorterDuff.Mode.MULTIPLY );
{ "language": "en", "url": "https://stackoverflow.com/questions/33577151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Joss eap 6.4 upgrade to 7.2 :javax.persistence.spi.PersistenceProvider: Provider org.eclipse.persistence.jpa.PersistenceProvider not a subtype Jboss eap 6.4 upgrade to 7.2 deploy ear error {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"WLS_DOM_SPS.ear\".FIRST_MODULE_USE" => "WFLYSRV0153: Failed to process phase FIRST_MODULE_USE of deployment \"WLS_DOM_SPS.ear\" Caused by: java.util.ServiceConfigurationError: javax.persistence.spi.PersistenceProvider: Provider org.eclipse.persistence.jpa.PersistenceProvider not a subtype"}} eclipse link module config : <?xml version="1.0" encoding="UTF-8"?> <module xmlns="urn:jboss:module:1.1" name="org.eclipse.persistence"> <resources> <resource-root path="javax.persistence_1.1.0.0_2-0.jar"/> <resource-root path="eclipselink-2.1.2_TMSModified1.jar"> <filter> <exclude path="javax/**" /> </filter> </resource-root> </resources> <dependencies> <module name="asm.asm"/> <module name="javax.api"/> <module name="javax.annotation.api"/> <module name="javax.enterprise.api"/> <module name="javax.persistence.api"/> <module name="javax.transaction.api"/> <module name="javax.validation.api"/> <module name="javax.xml.bind.api"/> <module name="org.antlr"/> <module name="org.apache.commons.collections"/> <module name="org.dom4j"/> <module name="org.javassist"/> <module name="org.jboss.as.jpa.spi"/> <module name="org.jboss.logging"/> <module name="org.jboss.vfs"/> </dependencies> </module> jboss eap 6.4 can deploy success. Don't know where the problem is. javax.persistence.jar-javax.persistence.spi.PersistenceProvider package javax.persistence.spi; import java.util.Map; import javax.persistence.EntityManagerFactory; public interface PersistenceProvider { EntityManagerFactory createEntityManagerFactory(String var1, Map var2); EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo var1, Map var2); ProviderUtil getProviderUtil(); } eclipselink-org.eclipse.persistence.jpa.PersistenceProvider // // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package org.eclipse.persistence.jpa; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.persistence.EntityManagerFactory; import javax.persistence.spi.ClassTransformer; import javax.persistence.spi.LoadState; import javax.persistence.spi.PersistenceUnitInfo; import javax.persistence.spi.ProviderUtil; import org.eclipse.persistence.exceptions.PersistenceUnitLoadingException; import org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl; import org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider; import org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl; import org.eclipse.persistence.internal.jpa.deployment.JPAInitializer; import org.eclipse.persistence.internal.jpa.deployment.PersistenceInitializationHelper; import org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor; import org.eclipse.persistence.internal.jpa.deployment.SEPersistenceUnitInfo; import org.eclipse.persistence.internal.weaving.PersistenceWeaved; public class PersistenceProvider implements javax.persistence.spi.PersistenceProvider, ProviderUtil { protected PersistenceInitializationHelper initializationHelper = null; public PersistenceProvider() { this.initializationHelper = new PersistenceInitializationHelper(); } public EntityManagerFactory createEntityManagerFactory(String emName, Map properties) { ClassLoader classloader = this.initializationHelper.getClassLoader(emName, properties); return this.createEntityManagerFactory(emName, properties, classloader); } protected EntityManagerFactory createEntityManagerFactory(String emName, Map properties, ClassLoader classLoader) { Map nonNullProperties = properties == null ? new HashMap() : properties; String name = emName; if (emName == null) { name = ""; } JPAInitializer initializer = this.initializationHelper.getInitializer(classLoader, (Map)nonNullProperties); EntityManagerSetupImpl emSetupImpl = null; boolean isNew = false; String uniqueName; String sessionName; SEPersistenceUnitInfo factory; try { factory = initializer.findPersistenceUnitInfo(name, (Map)nonNullProperties, this.initializationHelper); if (factory == null) { return null; } if (initializer.isPersistenceUnitUniquelyDefinedByName()) { uniqueName = name; } else { uniqueName = initializer.createUniquePersistenceUnitName(factory); } sessionName = EntityManagerSetupImpl.getOrBuildSessionName((Map)nonNullProperties, factory, uniqueName); synchronized(EntityManagerFactoryProvider.emSetupImpls) { emSetupImpl = EntityManagerFactoryProvider.getEntityManagerSetupImpl(sessionName); if (emSetupImpl == null) { if (EntityManagerFactoryProvider.initialEmSetupImpls != null) { emSetupImpl = (EntityManagerSetupImpl)EntityManagerFactoryProvider.initialEmSetupImpls.remove(uniqueName); if (emSetupImpl != null) { emSetupImpl.changeSessionName(sessionName); factory.setClassLoader(classLoader); } } if (emSetupImpl == null) { emSetupImpl = initializer.callPredeploy(factory, (Map)nonNullProperties, this.initializationHelper, uniqueName, sessionName); } emSetupImpl.predeploy(emSetupImpl.getPersistenceUnitInfo(), (Map)nonNullProperties); EntityManagerFactoryProvider.addEntityManagerSetupImpl(sessionName, emSetupImpl); isNew = true; } } } catch (Exception var18) { throw PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(classLoader, var18); } if (!isNew) { if (!uniqueName.equals(emSetupImpl.getPersistenceUnitUniqueName())) { throw PersistenceUnitLoadingException.sessionNameAlreadyInUse(sessionName, uniqueName, emSetupImpl.getPersistenceUnitUniqueName()); } boolean undeployed = false; synchronized(emSetupImpl) { if (emSetupImpl.isUndeployed()) { undeployed = true; } emSetupImpl.predeploy(emSetupImpl.getPersistenceUnitInfo(), (Map)nonNullProperties); } if (undeployed) { return this.createEntityManagerFactory(emName, properties, classLoader); } } factory = null; try { EntityManagerFactoryImpl factory = new EntityManagerFactoryImpl(emSetupImpl, (Map)nonNullProperties); if (emSetupImpl.shouldGetSessionOnCreateFactory((Map)nonNullProperties)) { factory.getServerSession(); } return factory; } catch (RuntimeException var15) { if (factory != null) { factory.close(); } else { emSetupImpl.undeploy(); } throw var15; } } public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map properties) { Map nonNullProperties = properties == null ? new HashMap() : properties; EntityManagerSetupImpl emSetupImpl = null; boolean isNew = false; ClassTransformer transformer = null; String uniqueName = PersistenceUnitProcessor.buildPersistenceUnitName(info.getPersistenceUnitRootUrl(), info.getPersistenceUnitName()); String sessionName = EntityManagerSetupImpl.getOrBuildSessionName((Map)nonNullProperties, info, uniqueName); synchronized(EntityManagerFactoryProvider.emSetupImpls) { emSetupImpl = EntityManagerFactoryProvider.getEntityManagerSetupImpl(sessionName); if (emSetupImpl == null) { emSetupImpl = new EntityManagerSetupImpl(uniqueName, sessionName); isNew = true; emSetupImpl.setIsInContainerMode(true); transformer = emSetupImpl.predeploy(info, (Map)nonNullProperties); EntityManagerFactoryProvider.addEntityManagerSetupImpl(sessionName, emSetupImpl); } } if (!isNew) { if (!uniqueName.equals(emSetupImpl.getPersistenceUnitUniqueName())) { throw PersistenceUnitLoadingException.sessionNameAlreadyInUse(sessionName, uniqueName, emSetupImpl.getPersistenceUnitUniqueName()); } boolean undeployed = false; synchronized(emSetupImpl) { if (emSetupImpl.isUndeployed()) { undeployed = true; } transformer = emSetupImpl.predeploy(emSetupImpl.getPersistenceUnitInfo(), (Map)nonNullProperties); } if (undeployed) { return this.createContainerEntityManagerFactory(info, properties); } } if (transformer != null) { info.addTransformer(transformer); } EntityManagerFactoryImpl factory = new EntityManagerFactoryImpl(emSetupImpl, (Map)nonNullProperties); if (emSetupImpl.shouldGetSessionOnCreateFactory((Map)nonNullProperties)) { factory.getServerSession(); } return factory; } public ProviderUtil getProviderUtil() { return this; } public LoadState isLoadedWithoutReference(Object entity, String attributeName) { return entity instanceof PersistenceWeaved ? this.isLoadedWithReference(entity, attributeName) : LoadState.UNKNOWN; } public LoadState isLoadedWithReference(Object entity, String attributeName) { Iterator setups = EntityManagerFactoryProvider.getEmSetupImpls().values().iterator(); while(setups.hasNext()) { EntityManagerSetupImpl setup = (EntityManagerSetupImpl)setups.next(); if (setup.isDeployed()) { Boolean isLoaded = EntityManagerFactoryImpl.isLoaded(entity, setup.getSession()); if (isLoaded != null) { if (isLoaded && attributeName != null) { isLoaded = EntityManagerFactoryImpl.isLoaded(entity, attributeName, setup.getSession()); } if (isLoaded != null) { return isLoaded ? LoadState.LOADED : LoadState.NOT_LOADED; } } } } return LoadState.UNKNOWN; } public LoadState isLoaded(Object entity) { return entity instanceof PersistenceWeaved ? this.isLoadedWithReference(entity, (String)null) : LoadState.UNKNOWN; } } The above is the interface and implementation of PersistenceProvider. Can't see any mismatch
{ "language": "en", "url": "https://stackoverflow.com/questions/60862948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook SDK (Require "Like" for access) I only want people that like'd our Facebook page to access a specific section of the site. But i'm relatively new with the Facebook SDK. Is there a way to check whether someone liked our page? If not possible with SDK are there other reliable ways to do so? A: Like-gating is not allowed by the Facebook platform policies (chapter 4.5). See * *https://developers.facebook.com/policy/#properuse Only incentivize a person to log into your app, enter a promotion on your app’s Page, or check-in at a place. Don’t incentivize other actions.
{ "language": "en", "url": "https://stackoverflow.com/questions/30936120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to produce and consume JSON messages between Django services using Redis as a message queue? I am trying to find a way to enable communication between two Django services using Redis as a message queue. One service would produces JSON data, publish it to the queue and the other one would consume the message. Something similar to what I want to achieve is described here using Spring Boot and RabbitMQ: https://www.javainuse.com/spring/spring-boot-rabbitmq-consume Any articles or suggestions would mean a lot. A: I think there are two things to you think about: * *if you want to use redis with django celery (Celery beat). *if you want to use just redis as M.Q with django. Below are the references to help you with each case: For Case 1: check out the link below * *https://enlear.academy/hands-on-with-redis-and-django-ed7df9104343 For Case 2: check out the link below *How can I publish a message in Redis channel asynchronously with python? (I recommand this one best : https://stackabuse.com/working-with-redis-in-python-with-django/) -- it covers all you need about using redis for caching
{ "language": "en", "url": "https://stackoverflow.com/questions/68880693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: xsl 1.0 Group by with comma separated items I have a XML similar to this <profiles> <profile> <customer>customer a </customer> <collateral> <summary>summary a</summary> <related> <solutions>sol1,sol2</solutions> </related> <collateral> </profile> <profile> <customer>customer b </customer> <collateral> <summary>summary b</summary> <related> <solutions>sol1</solutions> </related> <collateral> </profile> <profile> <customer>customer c </customer> <collateral> <summary>summary c</summary> <related> <solutions>sol2,sol3</solutions> </related> <collateral> </profile> </profiles> Desired output <div id="#sol1"> customer a,summary a customer b, summary b </div> <div id="#sol2"> customer a,summary a customer c,summary c </div> .............. Iam aware of Muenchian way of grouping, but not sure how I can accomplish, if I have comma separated groub-by element values. Any help will be appreciated. A: While this is straight-forward in XSLT 2.0, in XSLT a two-pass transformation can produce the wanted results: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ext="http://exslt.org/common" exclude-result-prefixes="ext"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:key name="kSolByVal" match="solution" use="."/> <xsl:template match="node()|@*" name="identity"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="/"> <xsl:variable name="vrtfPass1"> <xsl:apply-templates/> </xsl:variable> <xsl:apply-templates select= "ext:node-set($vrtfPass1) /*/*/*/* /solutions/solution [generate-id() = generate-id(key('kSolByVal', .)[1]) ]" mode="pass2"/> </xsl:template> <xsl:template mode="pass2" match="solution"> <div id="#{.}"> <xsl:apply-templates mode="pass2" select="key('kSolByVal', .)/../../../.."/> </div> </xsl:template> <xsl:template match="profile" mode="pass2"> <xsl:if test="position() = 1"> <xsl:text>&#xA;</xsl:text> </xsl:if> <xsl:value-of select= "concat(customer, ', ', */summary, '&#xA;')"/> </xsl:template> <xsl:template match="solutions"> <solutions> <xsl:apply-templates select="." mode="split"/> </solutions> </xsl:template> <xsl:template match="solutions" name="split" mode="split"> <xsl:param name="pText" select="."/> <xsl:if test="string-length($pText)"> <xsl:variable name="vText1" select="concat($pText, ',')"/> <xsl:variable name="vPart" select= "substring-before($vText1, ',')"/> <solution> <xsl:value-of select="$vPart"/> </solution> <xsl:call-template name="split"> <xsl:with-param name="pText" select="substring($pText, string-length($vPart)+2)"/> </xsl:call-template> </xsl:if> </xsl:template> </xsl:stylesheet> when this transformation is applied on the provided XML document (corrected for well-formedness): <profiles> <profile> <customer>customer a </customer> <collateral> <summary>summary a</summary> <related> <solutions>sol1,sol2</solutions> </related> </collateral> </profile> <profile> <customer>customer b </customer> <collateral> <summary>summary b</summary> <related> <solutions>sol1</solutions> </related> </collateral> </profile> <profile> <customer>customer c </customer> <collateral> <summary>summary c</summary> <related> <solutions>sol2,sol3</solutions> </related> </collateral> </profile> </profiles> the wanted, correct result is produced: <div id="#sol1"> customer a , summary a customer b , summary b </div> <div id="#sol2"> customer a , summary a customer c , summary c </div> <div id="#sol3"> customer c , summary c </div> Explanation: * *We carry out the transformation in two passes. Pass2 is applied on the result of applying Pass1 on the provided XML document. *Pass 1 is essentially the identity rule overriden for any solutions element. The processing of a solutions element consists in recursive splitting of its string value. The final result of Pass1 is the following: -- <profiles> <profile> <customer>customer a </customer> <collateral> <summary>summary a</summary> <related> <solutions> <solution>sol1</solution> <solution>sol2</solution> </solutions> </related> </collateral> </profile> <profile> <customer>customer b </customer> <collateral> <summary>summary b</summary> <related> <solutions> <solution>sol1</solution> </solutions> </related> </collateral> </profile> <profile> <customer>customer c </customer> <collateral> <summary>summary c</summary> <related> <solutions> <solution>sol2</solution> <solution>sol3</solution> </solutions> </related> </collateral> </profile> </profiles> .3. We then apply templates (in mode="pass2") on the result of Pass1. This is a typical and traditional Muenchian grouping.
{ "language": "en", "url": "https://stackoverflow.com/questions/7896730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to unload dynamic text once its loaded in Actionscript 3? I'm enlisting your help on how to unload text that dynamically loaded through a text file in Actionscript 3.0. I have managed to load the data to my stage, but I want that when the user hits the back button to go home, the data vanishes. At the moment, the data is still appearing even when you hit the back button (whose instance is page3home in the code below.) Below is my code: import flash.display.Loader; var myTextLoader:URLLoader = new URLLoader(); var myTextField_txt:TextField = new TextField(); var myTextUnloader:Loader=new Loader(); var textStyle:TextFormat = new TextFormat(); textStyle.font = "Verdana"; textStyle.size = 14; myTextField_txt.wordWrap=true; myTextField_txt.autoSize=TextFieldAutoSize.LEFT; myTextField_txt.multiline = true; myTextField_txt.width = 480; myTextField_txt.height = 300; myTextField_txt.x = 50; myTextField_txt.y = 80; myTextLoader.addEventListener(Event.COMPLETE, onLoaded); function onLoaded(e:Event):void { myTextField_txt.text = e.target.data; addChild(myTextField_txt); myTextField_txt.setTextFormat(textStyle); } myTextLoader.load(new URLRequest("myText.txt")); up_btn.addEventListener(MouseEvent.CLICK, scrollUp); function scrollUp(e:MouseEvent):void { myTextField_txt.scrollV--; } down_btn.addEventListener(MouseEvent.CLICK, scrollDown); function scrollDown(e:MouseEvent):void { myTextField_txt.scrollV++; } page3home.addEventListener(MouseEvent.CLICK, fl_ClickToGoToAndStopAtFrame_11); function fl_ClickToGoToAndStopAtFrame_11(event:MouseEvent):void { gotoAndStop(1); } A: To remove a DisplayObject ( the text field in your case ) from its parent DisplayObjectContainer, you can use the removeChild() method : myTextField_txt.parent.removeChild(myTextField_txt); Then to free the associated memory, you can add : myTextField_txt = null; You can also remove all event listeners added to your URLLoader object like this : myTextLoader.removeEventListener(Event.COMPLETE, onLoaded); Hope that can help.
{ "language": "en", "url": "https://stackoverflow.com/questions/32925889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can Tensorflow/Deep Learning be used for Gradient Boosted Trees, Logistic regression? Tensorflow and deep learning has mostly been used for Image Processing (Classification, Identification), NLP, Voice and text processing. I have used Spark MLLIB and Mahout in the past? Tensorflow has examples of Deep Neural Network - https://www.tensorflow.org/tutorials/wide_and_deep. Can logistic regression, Gradient Boosted Trees etc, be modeled in Tensorflow or a DL Framework? A: Yes, of course. In fact you can find a lot of examples: There are some ready implementations like tf.contrib.learn.LinearClassifier in https://www.tensorflow.org/tutorials/wide Or something like this: https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/2_BasicModels/logistic_regression.py where you use tf.matmul and appropriate activations. There is even something with gradient boosting: https://arogozhnikov.github.io/2016/07/05/gradient_boosting_playground.html
{ "language": "en", "url": "https://stackoverflow.com/questions/45498952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Join one array with multiple index php How to join 2 arrays with multiple index into 1 array ? I have array like this Array ( [0] => Array ( [wd[wd5][amount]] => 1.00 [wd[wd5][address]] => 1BitcoinAddress [wd[wd5][currency]] => BTC ) [1] => Array ( [wd[wd7][amount]] => 1.00 [wd[wd7][address]] => 1BitcoinAddress [wd[wd7][currency]] => BTC ) ) I want to convert/change/merge that array into something exactly like this array( 'wd[wd5][amount]' => 1.00, 'wd[wd5][address]' => '1BitcoinAddress', 'wd[wd5][currency]' => 'BTC', 'wd[wd7][amount]' => 0.0001, 'wd[wd7][address]' => '1BitcoinAddress', 'wd[wd7][currency]' => 'BTC' ); how do I do that ? A: Using call_user_func_array and array_merge <?php $array = [ [ "[wd[wd5][amount]]" => 1.00, "[wd[wd5][address]]" => "1BitcoinAddress", "[wd[wd5][currency]]" => "BTC" ], [ "[wd[wd7][amount]]" => 1.00, "[wd[wd7][address]]" => "1BitcoinAddress", "[wd[wd7][currency]]" => "BTC" ] ]; $result = call_user_func_array('array_merge', $array); echo "<pre>"; print_r($result); A: Loop the array using foreach and create an new array. $new_array = array(); foreach($array as $value){ foreach($value as $k=>$v){ $new_array[$k] = $v; } } print_r($new_array); Output: Array ( [wd[wd5][amount]] => 1.00 [wd[wd5][address]] => 1BitcoinAddress [wd[wd5][currency]] => BTC [wd[wd7][amount]] => 1.00 [wd[wd7][address]] => 1BitcoinAddress [wd[wd7][currency]] => BTC ) A: you can do this like: $result = array(); foreach($array as $item) { $result = array_merge($result, $item); } here $result is a new blank array, and $array is the array to merge. A: You can do it using RecursiveIteratorIterator and RecursiveArrayIterator. Though I'm liking @BilalAkbar's answer abit more now for the simplicity. <?php $array = [ [ 'wd[wd5][amount]' => 1.00, 'wd[wd5][address]' => '1BitcoinAddress', 'wd[wd5][currency]' => 'BTC', ], [ 'wd[wd7][amount]' => 1.00, 'wd[wd7][address]' => '1BitcoinAddress', 'wd[wd7][currency]' => 'BTC' ], ]; $result = []; foreach (new RecursiveIteratorIterator( new RecursiveArrayIterator($array) ) as $key => $value) { $result[$key] = $value; } print_r($result); /* Array ( [wd[wd5][amount]] => 1 [wd[wd5][address]] => 1BitcoinAddress [wd[wd5][currency]] => BTC [wd[wd7][amount]] => 1 [wd[wd7][address]] => 1BitcoinAddress [wd[wd7][currency]] => BTC ) */ https://3v4l.org/0fCKj A: Use array_merge to merge combine the arrays. http://php.net/manual/en/function.array-merge.php <?php $arrayWithSubarrays = array( array( "[wd[wd5][amount]]" => 1.00, "[wd[wd5][address]]" => "1BitcoinAddress", "[wd[wd5][currency]]" => "BTC" ), array( "[wd[wd7][amount]]" => 1.00, "[wd[wd7][address]]" => "1BitcoinAddress", "[wd[wd7][currency]]" => "BTC" ) ); // merge each array explicitly: $mergedArray1 = array_merge($arrayWithSubarrays[0],$arrayWithSubarrays[1]); // or merge as many as you have in the array: $mergedArray2 = array(); foreach($arrayWithSubarrays as $array) { $mergedArray2 = array_merge($mergedArray2, $array); } // (mergedArray1 contains the same data as mergedArray2) A: Here answer, but you have 2 solution one different key then below answer. otherwise only save array last values beacause every time 3 keys same. hope you understand. <?php $a = array ( array ( 'wd[wd[amount]]' => '1.00', '[wd[wd5][address]]' => '1BitcoinAddress', '[wd[wd5][currency]]' => 'BTC' ), array ( 'wd[wd[amount1]]' => '1.00', '[wd[wd5][address1]]' => '1BitcoinAddress', '[wd[wd5][currency1]]' => 'BTC' ) ); $total = count($a); $p = array(); $q = array(); $pq = array(); for($i=0;$i<$total;$i++){ $tarray = $a[$i]; foreach($tarray as $k=>$v){ array_push($p,$k); array_push($q,$v); } } $pq = array_combine($p,$q); print_r($pq); ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/46567674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I sync my maven artifacts to jcenter? I have deploy my fist version to the maven central repository. Now I want sync this to JCenter / Bintray. Is this possible and how can I do this? A: Yes, all you need to do is just download your artifacts from JCenter. On a related note, I'd suggest doing it the other way around - publish to JCenter and sync to Central. It should be easier for you. I am with JFrog, the company behind Bintray and [artifactory], see my profile for details and links.
{ "language": "en", "url": "https://stackoverflow.com/questions/30415303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ICE Faces fileInput file path and file name properties I'd like to utilize an ICE Faces fileInput control to fill in the file path & file name for the input to an input field on a web page based on file that the user selects. How can I capture these properties without actually performing any file transfer operations? A: I believe that the real answer is that you can't. The file path won't be sent by the browser for security reasons. The file name will be sent, however I don't believe it gets sent without an actual upload. The closest you could come, afaik, would be to forcibly kill the connection just when the upload starts. That would net you the filename with little actual transferred data, but it doesn't sound like it would be useful to you. Alternatively, a signed Java applet might get you closer to a solution that you'd want.
{ "language": "en", "url": "https://stackoverflow.com/questions/9361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to download a file from a VDI (citrix workspace) Artifactory through Python I have a question regarding VDI, Artifactory, and Python. I wanted to download an artifact that I have tested inside the VDI with the command: curl https://artifactory-aaaa.company.com/artifactory/artifacts/browse/tree/General/thedirectory/results/filename.xml --output filename.xml It outputs an XML file, just what I wanted. I tried doing the same with the Python requests module on my computer (download.py): import requests r = requests.get('https://artifactory-aaaa.company.com/artifactory/artifacts/browse/tree/General/thedirectory/results/filename.xml') with open("filename.xml", "wb") as file: file.write(r.content) and it returns an error : urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x03A4CA50>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond then requests.exceptions.ConnectionError: HTTPSConnectionPool(host='artifactory-scanner.asml.com', port=443): Max retries exceeded with url: /artifactory/artifacts/browse/tree/General/thedirectory/results/filename.xml (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x03A4CA50>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond')) To access these file I am required to connect to a VPN. I am connected to the VPN and are able to get the data inside the VDI. But during my Python run, it does not connect. Anybody know what seems to be the problem here? A: Based on the error snippet shared during the artifact download from the Artifactory application, it looks like there is a connectivity issue from the client(your computer) to Artifactory. You can validate the connectivity using the telnet from your computer to connect to the Artifactory IP/port. Also, you can validate the Artifactory request logs to check whether the request is reaching the application or not.
{ "language": "en", "url": "https://stackoverflow.com/questions/70923881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Data selection/Row selection I have a scenario where I have to write a SQL query where I consider only the negative values for selected date. how to achieve the output what i want is to convert all non negative numbers to zero for a particular date. In this case 2021. A: You seem to be looking for a conditional sum. The logic is to put a case expression within the aggregate function, like so: select sum(case when "2020" < 0 then "2020" else 0 end) result_2020, sum(case when "2021" < 0 then "2021" else 0 end) result_2021 from mytable It is quite unusal to have columns with all-digits names such as 2020, so I wonder whether what you are showing is your actual sample data or the results of an intermediate query (in which case, further optimizations may be possible). Edit The above answers the original version of the question. This answers the edited question: You can use a case expression to turn positive numbers for date 2021 to 0: select fab, date, case when output > 0 and date = 2021 then 0 else output end output from mytbale A: Say if you have a table like below I think you are looking for something like this SELECT id, year, (case when (a>0 and year = 2021) then 0 else a end) as a_filtered, (case when (b>0 and year = 2021) then 0 else b end) as b_filtered FROM `table_name` WHERE 1 The output will be the following.
{ "language": "en", "url": "https://stackoverflow.com/questions/62053347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP batch extract DB row BLOBs to files We are in the midst of a data migration , and the project needs from one particular table BLOB data saved to files, and sent to the vendor, due to their structure I am able to achieve this one at a time, but needed to create a batch process, as there are 50,000 rows/potential files. my current code is $sql = "SELECT a.guid AS file_name, a.attachment AS file_blob" ." FROM attachment a"; $squery = oci_parse($link, $sql); oci_execute($squery); while ($row = oci_fetch_array($squery, OCI_ASSOC | OCI_RETURN_LOBS)) { header('Content-type: octet-stream;'); header('Content-disposition: attachment;filename='.$row['FILE_NAME']); print $row['FILE_BLOB']; } oci_free_statement($squery); I do understand that I would rather be saving the data rather than streaming it to the browser, I just am not wrapping my head around how to achieve this, should i be looking at php file I/O fputs()? End result is I would like the process to batch write binary files based on the query to a folder EDIT Thank you for your direction and help, based on that I ended up coming up with two separate ways to achieve this first i did the following getcwd() to verify where the server was pointing to, and did an absolute path if needed $basedir = '/path/to/host/www/blobdoc/'; set permissions on the blobdoc folder then used either of the following scripts in the while loop $filename=''; $filename=$basedir.$row['FILE_NAME']; file_put_contents( $filename, $row['FILE_BLOB']); $filename=''; $filename=$basedir.$row['FILE_NAME']; $File = @fopen( $filename, 'w' ); if( $File ) { if( FALSE === fwrite( $File, $row['FILE_BLOB'] )) return FALSE; fclose( $File ); return TRUE; } A: Instead of: print $row['FILE_BLOB']; Use something like: file_put_contents( $filename, $row['FILE_BLOB']); //save locally You need to write the blob to a file. If you want to force a download of that file then you need to make use of the correct headers in combinarion with readfile, like so: $file = '/var/www/html/file-to-download.zip'; header('Content-Description: File Transfer'); header('Content-Type: application/force-download'); header('Content-Length: ' . filesize($filename)); header('Content-Disposition: attachment; filename=' . basename($file)); readfile($file);
{ "language": "en", "url": "https://stackoverflow.com/questions/6387098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Efficient way to get median in a unindexed table I am trying to find median salary in this table. Is there an aggregate function like AVG() to find a median in an unindexed table efficiently? Thanks. id | Salary ----------- 1 300 2 250 7 180 8 150 9 150 10 160 11 180 15 140 A: There is no MEDIAN() function in MySQL but there is a somewhat simple way to calculate it as demonstrated on this website: https://www.eversql.com/how-to-calculate-median-value-in-mysql-using-a-simple-sql-query/ Assuming your table is named salaries: SET @rowindex := -1; SELECT AVG(salary) FROM (SELECT @rowindex:=@rowindex + 1 AS rowindex, salaries.salary AS salary FROM salaries ORDER BY salaries.salary) AS s WHERE s.rowindex IN (FLOOR(@rowindex / 2) , CEIL(@rowindex / 2)); Explanation: * *Let's start with the internal subquery - the subselect assigns @rowindex as an incremental index for each salary that is selected, and sorts the salaries. *Once we have the sorted list of salaries, the outer query will fetch the middle items in the array. If the array contains an odd number of items, both values will be the single middle value. *Then, the SELECT clause of the outer query returns the average of those two values as the median value. A: select avg(Salary) from ( select *, ROW_NUMBER() over (order by Salary desc) as desc_salary, ROW_NUMBER() over (order by Salary asc) as asc_salary from Table_Name ) as a where asc_salary in (desc_salary,desc_salary+1, desc_salary-1)
{ "language": "en", "url": "https://stackoverflow.com/questions/64930655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Google Analytics API - Integration With Symfony2 I am trying to gain access to Google Analytics API through OAuth2. What i did: * *Open developers console > APIs and Auth > Credentials *Create a new Client ID *Generate p12 key *Copy the key on the server *Open google analytics page > admin > Account > User Management *Add the email from generated Client ID, something like: xxxxxxxx-xxxxxxxxxxxxxxx@developer.gserviceaccount.com *Give to this email Read and Analyze permissions *Then when I go back to developers console > permission. The new email is added on Service accounts with Edit permissions *Recheck if Google Analytics is enabled and data is going in. Now I had installed widop/google-analytics-bundle and configure the bundle: widop_google_analytics: client_id: "xxxxxxxx-xxxxxxxxxxxxxxx@developer.gserviceaccount.com" profile_id: "ga:12345678" private_key_file: "mykey.p12" http_adapter: "widop_http_adapter.curl" And the query I try to create is: $profileId = 'ga:12345678'; $query = new Query($profileId); $query->setStartDate(new \DateTime('-2months')); $query->setEndDate(new \DateTime()); $query->setMetrics(array('ga:visits' ,'ga:bounces')); $query->setDimensions(array('ga:browser', 'ga:city')); $query->setSorts(array('ga:country', 'ga:browser')); $query->setFilters(array('ga:browser=~^Firefox')); $query->setSegment('gaid::10'); $query->setStartIndex(1); $query->setMaxResults(10000); $query->setPrettyPrint(false); $query->setCallback(null); $clientId = 'xxxxxxxx-xxxxxxxxxxxxxxx@developer.gserviceaccount.com'; $privateKeyFile = 'mykey.p12'; $httpAdapter = new CurlHttpAdapter(); $client = new Client($clientId, $privateKeyFile, $httpAdapter); $token = $client->getAccessToken(); $service = new Service($client); $response = $service->query($query); return $response; As a response I get this error: User does not have sufficient permissions for this profile. When I open developers console > overview > 1 hour (tab) I had notice that requests are going in. From all that - I assume that authentication and query is OK but the user has no permissions to get any kind of data which is weird because I had granted Read and Analyze permissions to xxxxxxxx-xxxxxxxxxxxxxxx@developer.gserviceaccount.com What could by the reason for that exception? A: I do not know if you already solved this issue. The solution for me was use the view ID instead of account ID on the analytics account. The view ID is on the third column in settings, on Google Analytics administration panel. Sorry for my english.
{ "language": "en", "url": "https://stackoverflow.com/questions/29490459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Merge two directories keeping larger files Consider for example mkdir dir1 mkdir dir2 cd dir1 echo "This file contains something" > a touch b echo "This file contains something" > c echo "This file contains something" > d touch e cd ../dir2 touch a echo "This file contains something" > b echo "This file contains something" > c echo "This file contains more data than the other file that has the same name but is in the other directory. BlaBlaBlaBlaBlaBlaBlaBlaBla BlaBlaBlaBlaBlaBlaBlaBlaBla BlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBla. bla!" > d I would like to merge dir1 and dir2. If two files have the same name, then only the one which size is the largest must be kept. Here is the expected content of the merged directory a # Comes from `dir1` b # Comes from `dir2` c # Comes from either `dir1` or `dir2` d # Comes from `dir2` e # Comes from `dir1`(is empty) A: Assuming that no file name a newline: find . -type f -printf '%s %p\n' \ | sort -nr \ | while read -r size file; do if ! [ -e "dest/${file#./*/}" ]; then cp "$file" "dest/${file#./*/}"; fi; done The output of find is a list of "filesize path": 221 ./dir1/a 1002 ./dir1/b 11 ./dir2/a Then we sort the list numeric: 1002 ./dir1/b 221 ./dir1/a 11 ./dir2/a And fianlly we reach the while read -r size filename loop, where each file is copied over to the destination dest/${file#./*/} if they don't already exists. ${file#./*/} expands to the value of the parameter file with the leading directory removed: ./abc/def/foo/bar.txt -> def/foo/bar.txt, which means you might need to create the directory def/foo in the dest directory: | while read -r size file; do dest=dest/${file#./*/} destdir=${dest%/*} [ -e "$dest" ] && continue [ -e "$destdir" ] || mkdir -p -- "$destdir" cp -- "$file" "$dest" done A: I cannot comment on the other answer due to not enough reputation, but I was getting a syntax error due to missing fi. I also got an error where the target directory needed to be created before copying. So: find . -type f -printf '%s %p\n' | sort -nr | while read -r size file; do if ! [ -e "dest/${file#./*/}" ]; then mkdir -p "$(dirname "dest/${file#./*/}")" && cp "$file" "dest/${file#./*/}"; fi; done
{ "language": "en", "url": "https://stackoverflow.com/questions/40370154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the best way to instruct user to capture a clear or better image of a document.? I am working on an app where user needs to click an image of a document and upload and server will do the further processing of doing OCR and extracting specific data from it. OCR and data extraction completely depends on the image quality. So what is the best way, i can instruct user to take a near to perfect image of document at run-time. Factors i am considering. 1) Light available while capturing image (Can't use the light sensor because it is present on front side of phone whereas document will be on bottom side) 2) Document angle. (Tried edge detection using openCV but not properly works on white document with light color background surface. Any Edge detection tutorial for run-time document detection over custom camera surface will also be a great help) 3) Distance from document. Processing the image after capturing (Transforming the document to a rectangle using openCV) is not always giving a great result with OCR because of character distortion. So please suggest some way to instruct the user to take a better image of straight document from a perfect distance and better lightening conditions. And also after capturing best way to judge the image quality. A: If proportions of document is known, you can draw appropriate inner (for min document size) and outer (for max document size) bounding rectangles on preview (as shown on pict) and control that user positioned document within outer and over inner bounding rect. That is also helps to control right document angle. Also You can control tilt and orientation of smartphone as described in answers for this questions. Then process preview image (or even its small copy) on-the-fly with lightweight quality estimation algorithms and inform user about low quality and its reason (e.g. low brightness, you can estimate brightness of outer rectangle region, for example, as described in this question) and, may be, block "take snapshot" control. A: You can use classifier (Machine Learning techniques) to reject low quality images using various features which can differentiate between low and good quality or images captured from long distance by detecting the document in the image.
{ "language": "en", "url": "https://stackoverflow.com/questions/45791594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How do I change the data type in an HDF5 file from MATLAB? I have a HDF5 datafile that has an array of int32 data values. I wish to change the data stored in that array to different values which are of a different format (double). for example I can query the data type with the following: finf=h5info('file.hdf5'); finf.Datasets(1).Datatype ans = Name: '' Class: 'H5T_INTEGER' Type: 'H5T_STD_I32LE' Size: 4 Attributes: [] If I try to recreate the data in the same node location it gives me the following error that the data set already exists: t=double(h5read([filepath filename],'/t')); % more t calculations here.... h5create('file.hdf5','/t',size(t),'DataType','double'); Error using h5create>create_dataset (line 159) The dataset '/t' already exists. Error in h5create (line 69) create_dataset(options); I've looked in the Matlab docs for a function for deleting a data set in an hdf5 file but can't find any references. Any one have any ideas? A: It is not possible to either delete a dataset or change its datatype. From section 5.3.2 of the HDF5 manual: The datatype is set when the dataset is created and can never be changed. This is due to how space is assigned in an HDF5 file. While it's not possible to delete a dataset (for the same reasons), it can be "unlinked" and be made inaccessible, but this does not reclaim the used space. If you really need to change the datatype, you have two choices: the first is to unlink the old dataset and create a new one in its place. The new dataset can have the same name as the old one. However, if space is a concern, you may prefer to just create an entirely new HDF5 file, and copy the old data into the new one. A: According to This post which is a similar problem there is no mechanism for deleting a dataset in an HDF5 file. It also indicates that it is possible to Modify in place.
{ "language": "en", "url": "https://stackoverflow.com/questions/17994790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Plotting multiple probability distributions in a single graph in R I tried to plot probability distributions from different sources in a single plot. I used the following codes. require(ggplot2) require(ggfortify) p<- ggdistribution(dbeta, seq(0,1,0.01), shape1 = 1.777409 , shape2 = 2.7947, fill ='blue') p<- ggdistribution(dbeta, seq(0,1,0.01), shape1 = 1.934973 , shape2 = 2.553981, fill ='red', p=p) ggdistribution(dbeta, seq(0,1,0.01), shape1 = 0.93427 , shape2 = 1.777248, fill ='green', p=p) Is it possible to use point values (min, max, median and interquartile range) instead of shape1 and shape 2 to plot the distributions?
{ "language": "en", "url": "https://stackoverflow.com/questions/74240982", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error: Can't set headers after they are sent Node.js and ExpressJS I am using Node.js and ExpressJS to save a mongoose model. I am getting the error of Error: Can't set headers after they are sent. I think it has to do with the line res.redirect("/dashboard/it/model"); conflicting with setRedirect({auth: '/login'}), from my route, the code in the setRedirect is below labeled. The setRedirect is from a middleware called middleware-responder that came as part of the template I am using to create Stripe user accounts. I can not remove it as far as I know. my GitHub repo I have committed all files that are not test files and are relevant (no unneeded views ect than what is already there) Save Model if(type=="aps"){ var newAccessPoint = { name: name, manufacturer: manufacturer, model: model, range: range, bands: bands, channel: channel, poe: poe, notes: notes, signout: signout, author:author }; // Create a new access point and save to DB AP.create(newAccessPoint, function(err, newlyCreated){ if(err){ console.log(err); } else { //redirect back to models page res.redirect("/dashboard/it/model"); } }); } Route app.post('/dashboard/it/model/new', setRender('dashboard/it/modelCreate'), setRedirect({auth: '/login'}), isAuthenticated, dashboard.getDefault, (req, res) => { setRedirect code exports.setRedirect = function(options){ return function(req, res, next){ if(req.redirect){ req.redirect = _.merge(req.redirect, options); } else { req.redirect = options; } next(); }; }; setRender code exports.setRender = function(view){ return function(req, res, next){ req.render = view; next(); }; }; A: That's happening because you are trying to send a response to the client when you already closed the connection. Hard to tell by the way you are showing us your code but it seems like you are redirecting to options and then in the same request you are redirecting to dashboard/it/model A: I pull your code from github. I think the error message was clear. in your getDefault() middleware you are rendering a response so the server start sending data to your client and just after you try to redirect him to another url. Thats why when your comment out that middleware all work nicely.
{ "language": "en", "url": "https://stackoverflow.com/questions/46778762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sqlite3.Binary gives TypeError: buffer object expected I have a list which I extracted from a txt file as follows: authors = re.match('#@(.*)', line) if authors: authors_list = authors.group(1).split(",") Now I need to insert these into my database, which should be done as follows: for a in authors_list: c.execute("INSERT INTO authors(Name) VALUES (?)", (a)) But when I do that I get the following error: ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 17 supplied. So I did some research and found that I should change my variable a into a tuple (a, ) as such: c.execute("INSERT INTO authors(Name) VALUES (?)", (a,)) And I also tried this: c.execute("INSERT INTO authors(Name) VALUES (?)", ((a,))) But got the following error: ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings. So I did more research and found that I should use sqlite3's Binary function. So I tried the following: c.execute("INSERT INTO authors(Name) VALUES (?)", (sqlite3.Binary((a,)))) And got the following error: TypeError: buffer object expected I keep going back and forth between all three errors no mater what combination I try. Any help would be appreciated. I don't know what I'm doing wrong. A: You are passing in a tuple, not a bytestring: sqlite3.Binary((a,)) Create a tuple with the result of sqlite3.Binary(), having passed in just a: (sqlite3.Binary(a),) The whole statement is then run as: c.execute("INSERT INTO authors(Name) VALUES (?)", (sqlite3.Binary(a),)) However, if this is supposed to be text, you'd normally decode the bytes to a string instead of trying to insert binary data: c.execute("INSERT INTO authors(Name) VALUES (?)", (a.decode('utf8'),)) This does assume that your text is encoded using the UTF-8 codec; adjust the decoding as needed to match your data.
{ "language": "en", "url": "https://stackoverflow.com/questions/29613718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: react conditional component rendering I'm currently trying to create a React component to upload and crop an image using Croppie library. I've found this code sample import "croppie/croppie.css" import { Button, Grid } from "@material-ui/core" import * as React from "react" import Croppie from "croppie" export function CroppieExample() { const [image, setImage] = React.useState("") const [croppie, setCroppie] = React.useState<Croppie | null>(null) function handleImage(image: string) { setImage(image) const el = document.getElementById("image-helper") if (el) { const croppieInstance = new Croppie(el, { enableExif: true, viewport: { height: 250, width: 250, }, boundary: { height: 280, width: 400, } }); croppieInstance.bind({ url: image, }); setCroppie(croppieInstance) } } function handleSubmit(event: any) { event.preventDefault() if (croppie !== null) { croppie.result({type: 'base64', size: { width: 480, height: 480 }}).then((blob) => { console.log(blob) } ) } } return ( <form onSubmit={handleSubmit}> <Grid container spacing={2}> {image === "" && ( <Grid item xs={12}> {/* Your image upload functionality here */} <ImageUpload image={image} setImage={handleImage} /> </Grid> )} {image !== "" && ( <Grid item container justify="center" xs={12}> <div id="image-helper"></div> </Grid> )} <Grid container item xs={12} justify="flex-end"> <Button color="primary" variant="contained" type="submit"> Submit </Button> </Grid> </Grid> </form> ) } I've a question regarding the conditional part of this piece of code: In order to work, a Croppie instance must be attached to the div element "image-helper". The handleImage event is in charge of the croppieInstance creation. But by the time it is called, it seems that is not rendered so no croppie instance can be created. Is my assumption right? If it's the case, what would be the React way to correct the code? Thank you for your help A: Yes your analysis is right. The code snippet is egregious. The correct way in React to initialize any code when DOM elements are finally available is via a callback ref. const initImageHelper = useCallback( (element) => { if (element) { const croppieInstance = new Croppie(element, settings); croppieInstance.bind({ url: image }); setCroppie(croppieInstance); } }, [image] ); {image !== "" && ( <Grid item container justify="center" xs={12}> <div id="image-helper" ref={initImageHelper}></div> </Grid> )}
{ "language": "en", "url": "https://stackoverflow.com/questions/67413783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: clean-webpack-plugin only accepts an options object I'm getting Error: clean-webpack-plugin only accepts an options object. See: https://github.com/johnagan/clean-webpack-plugin#options-and-defaults- My Webpack.config.js file looks like this: const path = require('path'); const webpack = require('webpack'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); var plugins = [ new CleanWebpackPlugin(['dist'], {}), new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new CopyWebpackPlugin([{ from: './src/images/', to: './images/' }]), new HtmlWebpackPlugin({ inject: false, template: 'src/index.html' }) ]; var config = { entry: [ './src/js/main.js' ], output: { path: path.join(__dirname, 'dist'), publicPath: '/', filename: 'js/bundle.js', }, plugins: plugins.concat([ new ExtractTextPlugin('css/bundle.css'), //new webpack.optimize.UglifyJsPlugin(require('./uglifyjs.json')) ]), devServer: { inline: true, port: 8080 }, module: { loaders: [{ test: /\.jsx?$/, exclude: /node_modules/, include: path.join(__dirname, 'src'), loader: 'babel', query: { presets: ['react', 'es2015'] }}, { test: /.s?css$/, include: path.join(__dirname, 'src'), loader: ExtractTextPlugin.extract('style', [ 'css?sourceMap', 'postcss', 'sass?sourceMap' ]) }, { test: /\.css$/, include: path.join(__dirname, 'node_modules'), loader: 'style!css' } ] }, postcss: function() { return [ require('autoprefixer')({ browsers: ['last 2 versions'] }) ]; } } module.exports = config; A: Like @AKX mentioned, newest version of clean-webpack-plugin doesn't accept array argument anymore. The path which should be clearing is reading from webpack's output.path. In your example code it's here: output: { path: path.join(__dirname, 'dist'), // rest of code }, You should be very carefull, because someones still use pattern like this: output: { path: __dirname, filename: './dist/bundle.js' }, Above configuration will cause removing all files in your project! If you need to clear only some files from webpack's output.path you should set cleanOnceBeforeBuildPatterns field in object passed into CleanWebpackPlugin constructor. A: As you can see from the page the error message links, CleanWebpackPlugin does not accept two arguments as you're passing in: new CleanWebpackPlugin(['dist'], {}), Instead, just try new CleanWebpackPlugin(), if you don't need to pass in any options. You may be seeing this problem if you're, say, following an older tutorial or such which uses a different version of the plugin, and the interface has changed meanwhile.
{ "language": "en", "url": "https://stackoverflow.com/questions/55190450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Some more advanced recursion I've been looking around for awhile now, and I haven't found anything that helped me. I have to write a program that uses one method (the main method) to read in the size of/and elements of an array. Then I must write a recursive method titled "forwardsEqualBackwards" which returns true if the elements of the array can be read the same way regardless of whether the array is read forwards or backwards (it's a a test to see whether or not it's a palindrome) and false otherwise. A: pseudocode: bool forwardsEqualBackwards(array a, int length, int indexToLookAt=0) { if (indexToLookAt >= length-indexToLookAt-1) return true; //reached end of recursion if (a[indexToLookAt] == a[length-indexToLookAt-1]) return forwardsEqualBackwards(a,length, indexToLookAt+1); //normal recursion here else return false; } forwardsEqualBackwards("",0); //returns true forwardsEqualBackwards("a",1); //returns true forwardsEqualBackwards("otto",4); //returns true forwardsEqualBackwards("otsto",5); //returns true forwardsEqualBackwards("otstou",5); //returns false A: bool method(int start, int end) { if(start<=end) { if(Array[start]!=array[end]) return false; return method(start+1, end-1) } return true; }
{ "language": "en", "url": "https://stackoverflow.com/questions/13620830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Simplify and summarize data table in R One of my data set is as follows name alias (list of alias) x c("R","V","Q") y "Z" q c("A", "R", "M") w c("C","A","R") I would like to first simplify the table as follows name alias x "R" x "V" x "Q" y "Z" q "A" q "R" q "M" w "C" w "A" w "R" and later modify the data to get alias name "R" c(x,q,w) "V" x "Q" x "Z" y "A" c(q,w) "M" q "C" w How can I achieve this in R? Here is the actual data set > \dput(head(cases)) structure(list(caseid = c(7703415, 7758128, 7858259, 8802954, 8829620, 8847200), tcount = c(2L, 2L, 3L, 10L, 4L, 2L), helplinks = c("character(0", "c(\"60107\", \"56085\", \"57587\", \"3000020\"", "character(0", "character(0", "c(\"60107\", \"3000023\", \"3000020\", \"60107\", \"56085\", \"57587\"", "character(0")), .Names = c("caseid", "tcount", "helplinks"), row.names = c(NA, 6L), class = "data.frame") > head(cases) caseid tcount helplinks 1 7703415 2 character(0 2 7758128 2 c("60107", "56085", "57587", "3000020" 3 7858259 3 character(0 4 8802954 10 character(0 5 8829620 4 c("60107", "3000023", "3000020", "60107", "56085", "57587" 6 8847200 2 character(0 A: New answer Use cSplit from my "splistackshape" package: cSplit(cases, "helplinks", ",", "long")[, helplinks := gsub( 'character\\(0|c\\(|\\"', "", helplinks)][, list( caseid = list(caseid)), by = helplinks] # helplinks caseid # 1: 7703415,7858259,8802954,8847200 # 2: 60107 7758128,8829620,8829620 # 3: 56085 7758128,8829620 # 4: 57587 7758128,8829620 # 5: 3000020 7758128,8829620 # 6: 3000023 8829620 Old answer I'm assuming you're starting with something like this: df <- data.frame( name = c("x", "y", "q", "w"), alias = I(list(c("R","V","Q"), "Z", c("A", "R", "M"), c("C","A","R"))) ) df # name alias # 1 x R, V, Q # 2 y Z # 3 q A, R, M # 4 w C, A, R If that's the case, here's one approach using listCol_l from my "splitstackshape" package in conjunction with "data.table". library(splitstackshape) listCol_l(df, "alias")[, list(name = list(name)), by = alias_ul] # alias_ul name # 1: R x,q,w # 2: V x # 3: Q x # 4: Z y # 5: A q,w # 6: M q # 7: C w You don't really need "splitstackshape" for that, so if you want to remove the self-promotion part of my answer and just use "data.table", you could do: library(data.table) as.data.table(df)[, list( alias = unlist(alias)), by = name][, list( name = list(name)), by = alias] A: First we clean up the "character(0"'s. Then we read in those character values that were once lists but now need to be scan-ned. Then we apply a function that makes a dataframe from every line: good.case <- cases[ grepl("c\\(", cases$helplinks),] lapply( split(good.case, row.names(good.case) ), function(d){ vec <- scan(text=gsub("c\\(|[, ]", "", d$helplinks) ,what="") do.call( data.frame, list(caseid=d$caseid, alias=vec) ) } ) #------- #Read 4 items #Read 6 items $`2` caseid alias 1 7758128 60107 2 7758128 56085 3 7758128 57587 4 7758128 3000020 $`5` caseid alias 1 8829620 60107 2 8829620 3000023 3 8829620 3000020 4 8829620 60107 5 8829620 56085 6 8829620 57587 expanded <- lapply( split(good.case, row.names(good.case) ), function(d){ vec <- scan(text=gsub("c\\(|[, ]", "", d$helplinks) ,what="") do.call( data.frame, list(caseid=rep(d$caseid, length(vec)), alias=vec) ) } ) #Read 4 items #Read 6 items Now we bind the dataframes together: do.call(rbind, expanded) #--------------- caseid alias 2.1 7758128 60107 2.2 7758128 56085 2.3 7758128 57587 2.4 7758128 3000020 5.1 8829620 60107 5.2 8829620 3000023 5.3 8829620 3000020 5.4 8829620 60107 5.5 8829620 56085 5.6 8829620 57587 But only half the way there I suppose. No point in pursuing further with Ananda's 5 caret answer sitting there.
{ "language": "en", "url": "https://stackoverflow.com/questions/27031776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to convert NSDictionary to custom object I have a json object: @interface Order : NSObject @property (nonatomic, retain) NSString *OrderId; @property (nonatomic, retain) NSString *Title; @property (nonatomic, retain) NSString *Weight; - (NSMutableDictionary *)toNSDictionary; ... - (NSMutableDictionary *)toNSDictionary { NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; [dictionary setValue:self.OrderId forKey:@"OrderId"]; [dictionary setValue:self.Title forKey:@"Title"]; [dictionary setValue:self.Weight forKey:@"Weight"]; return dictionary; } In string this is: { "Title" : "test", "Weight" : "32", "OrderId" : "55" } I get string JSON with code: NSMutableDictionary* str = [o toNSDictionary]; NSError *writeError = nil; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:str options:NSJSONWritingPrettyPrinted error:&writeError]; NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; Now I need to create and map object from JSON string: NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; NSError *e; NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&e]; This returns me filled NSDictionary. What should I do to get object from this dictionary? A: Assuming that your properties names and the dictionary keys are the same, you can use this function to convert any object - (void) setObject:(id) object ValuesFromDictionary:(NSDictionary *) dictionary { for (NSString *fieldName in dictionary) { [object setValue:[dictionary objectForKey:fieldName] forKey:fieldName]; } } A: this will be more convenient for you : - (instancetype)initWithDictionary:(NSDictionary*)dictionary { if (self = [super init]) { [self setValuesForKeysWithDictionary:dictionary];} return self; } A: Add a new initWithDictionary: method to Order: - (instancetype)initWithDictionary:(NSDictionary*)dictionary { if (self = [super init]) { self.OrderId = dictionary[@"OrderId"]; self.Title = dictionary[@"Title"]; self.Weight = dictionary[@"Weight"]; } return self; } Don't forget to add initWithDictionary's signature to Order.h file In the method where you get JSON: NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; NSError *e; NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&e]; Order *order = [[Order alloc] initWithDictionary:dict]; A: If the property names on your object match the keys in the JSON string you can do the following: To map the JSON string to your Object you need to convert the string into a NSDictionary first and then you can use a method on NSObject that uses Key-Value Coding to set each property. NSError *error = nil; NSData *jsonData = ...; // e.g. [myJSONString dataUsingEncoding:NSUTF8Encoding]; NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingOptionsAllowFragments error:&error]; MyObject *object = [[MyObject alloc] init]; [object setValuesForKeysWithDictionary:jsonDictionary]; If the keys do not match you can override the instance method of NSObject -[NSObject valueForUndefinedKey:] in your object class. To map you Object to JSON you can use the Objective-C runtime to do it automatically. The following works with any NSObject subclass: #import <objc/runtime.h> - (NSDictionary *)dictionaryValue { NSMutableArray *propertyKeys = [NSMutableArray array]; Class currentClass = self.class; while ([currentClass superclass]) { // avoid printing NSObject's attributes unsigned int outCount, i; objc_property_t *properties = class_copyPropertyList(currentClass, &outCount); for (i = 0; i < outCount; i++) { objc_property_t property = properties[i]; const char *propName = property_getName(property); if (propName) { NSString *propertyName = [NSString stringWithUTF8String:propName]; [propertyKeys addObject:propertyName]; } } free(properties); currentClass = [currentClass superclass]; } return [self dictionaryWithValuesForKeys:propertyKeys]; } A: The perfect way to do this is by using a library for serialization/deserialization many libraries are available but one i like is JagPropertyConverter https://github.com/jagill/JAGPropertyConverter it can convert your Custom object into NSDictionary and vice versa even it support to convert dictionary or array or any custom object within your object (i.e Composition) JAGPropertyConverter *converter = [[JAGPropertyConverter alloc]init]; converter.classesToConvert = [NSSet setWithObjects:[Order class], nil]; @interface Order : NSObject @property (nonatomic, retain) NSString *OrderId; @property (nonatomic, retain) NSString *Title; @property (nonatomic, retain) NSString *Weight; @end //For Dictionary to Object (AS IN YOUR CASE) NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; [dictionary setValue:self.OrderId forKey:@"OrderId"]; [dictionary setValue:self.Title forKey:@"Title"]; [dictionary setValue:self.Weight forKey:@"Weight"]; Order *order = [[Order alloc]init]; [converter setPropertiesOf:order fromDictionary:dictionary]; //For Object to Dictionary Order *order = [[Order alloc]init]; order.OrderId = @"10"; order.Title = @"Title; order.Weight = @"Weight"; NSDictionary *dictPerson = [converter convertToDictionary:person]; A: Define your custom class inherits from "AutoBindObject". Declare properties which has the same name with keys in NSDictionary. Then call method: [customObject loadFromDictionary:dic]; Actually, we can customize class to map different property names to keys in dictionary. Beside that, we can bind nested objects. Please have a look to this demo. The usage is easy: https://github.com/caohuuloc/AutoBindObject
{ "language": "en", "url": "https://stackoverflow.com/questions/21329793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: How am I supposed to use the -audiodev option in QEMU? There is a thread Fwd: How am I supposed to use the -audiodev option?, but unfortunately it does not contain an answer. I use QEMU on Windows, and when I run my image in QEMU qemu-system-arm.exe , I get: dsound: Could not initialize DirectSound dsound: Reason: No sound driver is available for use, or the given GUID is not a valid DirectSound device ID sdl: SDL_OpenAudioDevice for playback failed sdl: Reason: WASAPI can't find requested audio endpoint: Element not found. sdl: SDL_OpenAudioDevice for playback failed sdl: Reason: WASAPI can't find requested audio endpoint: Element not found. audio: Failed to create voice `lm4549.out' So, I want to disable audio completely, and get rid of those messages. So, I add this (found via https://unix.stackexchange.com/questions/564844/disable-sound-when-using-spice-with-kvm-libvirt) to my command line: -audiodev id=none,driver=none This then results with: audio: Device lm4549: audiodev default parameter is deprecated, please specify audiodev=none As recommended in that thread, I tried: C:\bin\qemu\qemu-system-arm.exe -audio-help Environment variable based configuration deprecated. Please use the new -audiodev option. Equivalent -audiodev to your current environment variables: (Since you didn't specify QEMU_AUDIO_DRV, I'll list all possibilities) -audiodev id=dsound,driver=dsound -audiodev id=sdl,driver=sdl -audiodev id=none,driver=none Ok, I then try this instead of the above: audiodev=none ... and I get: qemu-system-arm.exe: audiodev=none: drive with bus=0, unit=0 (index=0) exists Ok, I try this: -audiodev=none ... and I get: qemu-system-arm.exe: -audiodev=none: invalid option So ... how do I set audio device to none in QEMU?
{ "language": "en", "url": "https://stackoverflow.com/questions/75317906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to replace a sentence with space on the basis of a pattern if it occurs in the middle of a sentence Suppose I have a line like this: aaaa ---- bbbb I want to erase the ----bbbb part, but I want to keep the aaaa part as it is in the file. How can I do it? A: Using sed: s='aaaa ---- bbbb' echo "$s"|sed 's/--* bb*/foo/' aaaa foo
{ "language": "en", "url": "https://stackoverflow.com/questions/22602632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use API Key in Google Speech grpc Java library How do I use an API Key in Google Speech grpc Java or any other library. For HTTP request I am able to see that we can append key=API_KEY as mentioned in https://cloud.google.com/docs/authentication/api-keys. But for the given libraries (https://cloud.google.com/speech/docs/reference/libraries#client-libraries-install-java) all examples show how to use the Credential file. Please help. A: Use metadata with a key of X-Goog-Api-Key. See this other answer. If you have API restrictions, you may need additional headers. For example, an iOS example mentioned a bundle id restriction.
{ "language": "en", "url": "https://stackoverflow.com/questions/46112170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Check size(variable) of all string in List using Java Stream I have a list of strings (given below), each string required to be in a specific size(Variable). for e.g. {"abc","xyz","def"} this list elements has a fixed size of 3 and i would like to check if this size is not exceed to X=3 or 4. Requirement is to return a boolean if that size exceed or lower the size. I refereed Java Stream docs couldn't find any relevant information. Does Java Stream API is useful to solve this or should i solve it in classical way. A: You can use the allMatch method like this: int correctSize = 3; List<String> myStrings = List.of("abc", "xyz", "def"); boolean allAreCorrectSize = myStrings.stream() .allMatch(s -> s.length() == correctSize); A: Here both implementation, both can be used * *Using Stream API public static boolean isValidUsingStreamAPI(List<String> list){ int correctSize=3; return list.stream().allMatch(f->f.length()==correctSize); } *Classic Way public static boolean isValidClassic(List<String> list){ int correctSize=3; for(String s:list){ if(s.length()!=correctSize)return false; } return true; }
{ "language": "en", "url": "https://stackoverflow.com/questions/62535954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: html2canvas is not working in Safari browser: Taking Screenshot I just want to take a screenshot of any HTML element ( "container" div in my case ). it works fine in Chrome and Firefox browsers but not in Safari. Following is how I am doing it: <!doctype HTML> <HTML> <head> <script type="text/javascript" src="assets/HTML_canvas/html2canvas.js"></script> </head> <body> <h1>Take screenshot of webpage with html2canvas</h1> <div class="container" id='container' > <div style="background-color: blue; height: 50px; width: 50px;">DIV 1</div> <div style="background-color: red; height: 50px; width: 50px;">DIV 2</div> <div style="background-color: green; height: 50px; width: 50px;">DIV 3</div> </div> <input type='button' id='but_screenshot' value='Take screenshot' onclick='screenshot();'><br/> <!-- Script --> <script type='text/javascript'> function screenshot(){ html2canvas(document.getElementById('container')).then(function(canvas) { document.body.appendChild(canvas); }); } </script> </body> </html> it shows the following error in the Safari browser: and here is the specific part of code of html2canvas.js (it is by-default file I have just used). A: we just have to enable the CORS in safari-mac browser. So, we'll do it by modifying our function screenshot() as follows: function screenshot(){ html2canvas(document.getElementById('id-screenshot'),{ allowTaint: true, useCORS : true, }).then(function(canvas) { console.log("canvas: " + canvas); document.getElementById('test-s').appendChild(canvas); }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/70800095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to make multiple tkinter buttons to press together while as user presses any one of them? how to make multiple tkinter buttons to press together while as user presses any one of them? To be clear i want multiple tkinter buttons look like pressed at the same time user presses any one of them . i tried this: from tkinter import * from tkinter import ttk class one_for_all: def __init__(self): self.root = Tk() self.root.title("One For All, All For One") self.frame = ttk.Frame(self.root, padding="3 3 12 12") self.frame.grid(row=0, column=0) self.root.rowconfigure(0, weight=1) self.root.columnconfigure(0, weight=1) self.btn1 = ttk.Button(self.frame, text="btn1", command=lambda : self.push_all(1)) self.btn2 = ttk.Button(self.frame, text="btn2", command=lambda : self.push_all(2)) self.btn3 = ttk.Button(self.frame, text="btn3", command=lambda : self.push_all(3)) self.btn4 = ttk.Button(self.frame, text="btn4", command=lambda : self.push_all(4)) self.btn1.grid(row=0, column=0, sticky="nsew") self.btn2.grid(row=0, column=1, sticky="nsew") self.btn3.grid(row=1, column=0, sticky="nsew") self.btn4.grid(row=1, column=1, sticky="nsew") for child in self.frame.winfo_children(): child.grid_configure(padx=5, pady=5) def push_all(self, caller): if caller != 1: self.btn1.configure(command=lambda : None) self.btn1.event_generate("<ButtonPress-1>") self.btn1.event_generate("<ButtonRelease-1>") self.btn1.configure(command=lambda: self.push_all(1)) if caller != 2: self.btn2.configure(command=lambda : None) self.btn2.event_generate("<ButtonPress-1>") self.btn2.event_generate("<ButtonRelease-1>") self.btn2.configure(command=lambda: self.push_all(2)) if caller != 3: self.btn3.configure(command=lambda : None) self.btn3.event_generate("<ButtonPress-1>") self.btn3.event_generate("<ButtonRelease-1>") self.btn3.configure(command=lambda: self.push_all(3)) if caller != 4: self.btn4.configure(command=lambda : None) self.btn4.event_generate("<ButtonPress-1>") self.btn4.event_generate("<ButtonRelease-1>") self.btn4.configure(command=lambda: self.push_all(4)) def mainloop(self): self.root.mainloop() if __name__ == "__main__": one_for_all().mainloop() but it looks like only button 4 is stimulated by other buttons not all 4 :( Note: i just started the tkinter without any prior experience of GUI Thanks in Advance. A: You can do something like this: from tkinter import Tk, Button class MainWindow(Tk): def __init__(self): super().__init__() self.buttons = list() for i in range(4): button = Button(self, text=f'Button {i}') button.bind('<ButtonPress-1>', self.press) button.bind('<ButtonRelease-1>', self.release) button.pack(fill='both') self.buttons.append(button) def press(self, event=None): for btn in self.buttons: btn.config(relief='sunken') def release(self, event=None): for btn in self.buttons: btn.config(relief='raised') if __name__ == '__main__': MainWindow().mainloop() It will visually make them appear to be clicked at once. You can simply inherit from Tk and it will reduce the code written a bit since instead of self.root it would simply be just self and the features would be inherited and other stuff, for example, don't need to define mainloop as it is already inherited. Also: I strongly suggest following PEP 8 - Style Guide for Python Code. Function and variable names should be in snake_case, class names in CapitalCase. Have two blank lines around function and class declarations. I strongly advise against using wildcard (*) when importing something, You should either import what You need, e.g. from module import Class1, func_1, var_2 and so on or import the whole module: import module then You can also use an alias: import module as md or sth like that, the point is that don't import everything unless You actually know what You are doing; name clashes are the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/69440204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Receiving "error: conflicting types for 'function'" I am creating a program to convert from binary, decimal, hex, and oct to any one of those options. For hex, I need a way to format values greater than 9 into one of A, B, C, D, E, F. Since this will be repeated in several functions, I decided to make the following function: char hexRepresentation(double n){ if(n > 9){ if(n==10) return 'A'; if(n==11) return 'B'; if(n==12) return 'C'; if(n==13) return 'D'; if(n==14) return 'E'; if(n==15) return 'F'; } return (char)n; } However, when I try to compile, I receive the error conflicting types for 'hexRepresentation' I'm utterly new at C, coming from Java, and am banging my head against a wall over what should be the simplest things to implement. Any help would be greatly appreciated! A: You don't get a declaration kind-of error because in C, when you do not forward declare a function most compilers assume an extern function that returns an int type. Actually the compiler should warn you about this (most do). Then later on when the compiler actually reaches the function implementation it finds a different return type, in this case a char, and then throws the "conflicting type" error. Just forward declare all the functions to avoid this kind of errors. About what would be the best way somthing like following code woudl yield a similar result: if (n > 9) { return('A' + (n - 10)); } A: Whatever you are doing in the code posted, you are not using double datatype at all, within the function. And from the function return type, it appears you will never see the return value >127. This code highlights some issues:(This is just illustrative) char hexRepresentation(double n){ if(n > 9){//comparing (double>int). Bad. if(n==10) return 'A'; if(n==11) return 'B'; if(n==12) return 'C';//You wrote if(double == int). Bad. if(n==13) return 'D'; if(n==14) return 'E'; if(n==15) return 'F'; } return (char)n; //again unsafe downgrade from 8 bytes double to 1 byte char. } Even if you fix your compiler error, you may not get the desired results always, due to such dangerous usage of datatype in the function. To know why its bad, look here: http://www.cygnus-software.com/papers/comparingfloats/Comparing%20floating%20point%20numbers.htm I would use fabs(n) instead of n everywhere in that function body. And the error "conflicting types for 'hexRepresentation'" will be shown when there exists a prior declaration or definition of the same named function hexRepresentation before this function definition. Also, if you do not declare a function and it only appears after being called, it is automatically assumed to be int by the compiler. So, declare and define your function before main() or declare before main() and define the function anywhere else in the file, but, with the same function prototype. Do: char hexRepresentation(double); //Declaration before main main() { ... } char hexRepresentation(double n){//Definition after main ... } Or char hexRepresentation(double n){ //Declaration and definition before main ... } main() { ... } A: Just create one stack ( for char) which has push and pop functions. I am not returning the value just printing it there in the same function. (have implemented for integral values only) #define max 100 char a[max]; void hex(int n) { while(n>0) { int rem = n%16; if (rem<10) push(rem+'0'); elsif(rem >=10 && rem <16) { switch(rem) { case 10: push('A');break; case 11: push('B');break; case 12: push('C');break; case 13: push('D');break; case 14: push('E');break; case 15: push('F');break; } else n=n/16; } } i=0; while(top>-1) a[i++]=pop(); i=0; while(a[i]!='\0') printf("%c",a[i++]); } Is it helpful ?
{ "language": "en", "url": "https://stackoverflow.com/questions/12992505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Using sed inside php script is causing unexpected T_STRING error I'm adding a line to my php script: exec('sed -i 1i'MAILTO=""' /var/spool/cron/' '.$clientName.'); But it shows me an error: PHP Parse error: syntax error, unexpected T_STRING in /home/admin/myproject.pl/newclient/main.php on line 368 Parse error: syntax error, unexpected T_STRING in /home/admin/myproject.pl/newclient/main.php on line 368 A: I think the error says it quite well. You have a syntax error. Perhaps this is what you wanted? exec('sed -i \'1i MAILTO=""\' /var/spool/cron/'.$clientName);
{ "language": "en", "url": "https://stackoverflow.com/questions/9743989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to center align a number in a diamond? I'm trying to center align this 1 in the diamond, but I can't figure out how to. Is this even possible? Please help... .num { width: 0; height: 0; border: 15px solid transparent; border-bottom-color: pink; position: relative; top: -15px; text-align: center; color: white; font-weight: bold; vertical-align: center; } .num:after { text-align: center; content: ''; position: absolute; left: -15px; top: 15px; width: 0; height: 0; border: 15px solid transparent; border-top-color: pink; } <div class="num">1</div> A: Use clip-path .num { background:pink; display:inline-flex; font-size:20px; width:80px; height:80px; align-items:center; justify-content:center; clip-path:polygon(50% 0,100% 50%,50% 100%,0 50%); } <div class="num">1</div> A: Or if you don't want to play with clips than you can use the following: <div class="num"><span>1</span></div> CSS .num { width: 0; height: 0; border: 15px solid transparent; border-bottom-color: pink; position: relative; top: -15px; text-align: center; color: white; font-weight: bold; vertical-align: center; } .num span { width: 20px !important; height: 40px !important; position: absolute; margin-left: -10px; vertical-align: center; margin-top: 5px; z-index: 1 } .num:after { text-align: center; content: ''; position: absolute; left: -15px; top: 15px; width: 0; height: 0; border: 15px solid transparent; border-top-color: pink; } But be aware: this only works if you have fix sizes. If you use percentage, than you have to always calculate the margins/paddings.
{ "language": "en", "url": "https://stackoverflow.com/questions/68577859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Am I able to complement a virtual function of subclasses? i have a question. Lets say i have this virtual function in main class: virtual void h_w() { cout << "Hello, wolrd!" << endl; } And Im doing with the same function that: void h_w() { cout << "Today is: " << math.rand(); << endl; } Am I allowed to do that? I mean, can i change body of main function like I want in subclasses? Thanks. A: Assuming you mean you want something like this: class base { public: virtual void h_w() { std::cout << "Hello world!\n"; } }; class derived : public base { public: void h_w() { std::cout << "Today is: " << rand() << "\n"; } }; int main() { std::unique_ptr<base> b = std::make_unique<derived>(); b->h_w(); } ...then yes, C++ supports that. In fact, this is pretty much a canonical demonstration of virtual functions, at least if you change names to (for example) "animal" as the base class and "duck" as the derived class, and have them print out something like "generic animal" and "duck" respectively. For the record, it's probably worth noting that most example based on animals are more or less broken in various ways, such as animals simply not following simple sets of rules like we expect code to. A better example, would be something like a base class defining a generic interface to a database that allows things like reading a record, writing a record, and finding a set of records that satisfy some criteria. The derived class could then (for example) provide an implementation to carry out those "commands" in terms of some specific type of database--perhaps SQL, or perhaps some simple key/value storage engine, but the client doesn't know or care, beyond minor details like performance. As to why this is better: first of all, because it corresponds much more closely to things you're likely to really do with a computer. Second, because we can define databases to really follow our rules and fulfill the obligations we set. With animals, we're stuck with all sorts of exceptions to any meaningful rule we might try to make, as well as the simple fact that (of course) being able to make a Duck say "quack" and a dog say "bow wow" isn't really very useful (and in the rare case that it is useful, we probably just want to save/retrieve its sound as some sort of blob, not define an entire new type to encode something better stored as data).
{ "language": "en", "url": "https://stackoverflow.com/questions/41452414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Is there a way to work with arrays and use Protege I am trying to perform the functions on arrays such as inverse of and transpose on matrices and use it along with Protege so as to calculate the forces and deflections using reasoner. We can perform the calculations using SWRL rules in ontology but it does not support array as data type. But we have Postgres and MongoDB which supports arrays. Is there any way to work with arrays and use inverse operation in ontology? Suppose inverse operation is done by database such as Postgres then how to display the array elements in ontology? Can MongoDB be used here? If yes how do we connect to Protege 5.2. I understand WebProtege can be used along MongoDB but the current version of WebProtege does not support reasoning part. Also Ontop plugin does not support connectivity with MongoDB. Kindly clarify if I am missing some thing in meeting the objective of working with arrays in ontology.
{ "language": "en", "url": "https://stackoverflow.com/questions/44526428", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Associating ViewPager with navigation tabs Is there any way to associate each fragment in the ViewPager with a certain navigation tab? So when we flip right/left ,the right tab will be highlighted. Thank you. A: Use TabLayout from the Material Design support library. See the "Tabs" paragraph in the blog post that introduces the library: However, if you are using a ViewPager for horizontal paging between tabs, you can create tabs directly from your PagerAdapter’s getPageTitle() and then connect the two together using setupWithViewPager(). This ensures that tab selection events update the ViewPager and page changes update the selected tab.
{ "language": "en", "url": "https://stackoverflow.com/questions/31140863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Keep XML namespaces after split or grep I have a huge xml-file (several GB) which I can split with xml_split or I can extract the relevant subbnode with xml_grep. I run out of RAM if I try to read the whole XML. But when I try to parse one of the splitted files, or the grep:ed file, I get the error "Namespace prefix xx on yy is not defined" thousands of times. Is there a way to copy the namespace-definition from the original file to the splitted or grep:ed files? Or have I misunderstood the errors? I'm very new to XML and I find XML::TWIG useful. Here is the grep-command I use: xml_grep --root 'SubInformation' --cond 'SubInformationName[string()="Blah"]' Infile.xml > Outfile.xml A: Which tool are you using to parse the result of the split (or the grep)? xmllint (from libxml2) complains, but xmlwf (from expat) doesn't. So I think any expat-based tool would be ok with the XML, but not libxml2-based ones. It looks like xml_split and xml_grep could declare the namespaces though. At least it should be an option. I'll have a look at it. In the meantime, here is a quick'n dirty way to post-process the result you get with xml_grep: xml_grep --root 'SubInformation' --cond 'SubInformationName[string()="Blah"]' Infile.xml | perl -MXML::Twig -e'XML::Twig->new( start_tag_handlers => { xml_grep => sub { $_->set_att( "xmlns:m" => "http://m.org") }, SubInformation => sub { $_->flush } })->parse( \*STDIN)' > Outfile.xml replace xmlns:m and "http://m.org" with the appropriate values. Let me think of a way to do this in a generic way for the result of xml_split. Can I assume that the namespace declarations are not too tricky (ie that the prefix(es) are declared just once)? Edit: Here is a way to add the namespace declarations to the files resulting from xml_split, call it as add_ns Infile after you have run xml_split on Infile.xml: #!/usr/bin/perl use strict; use warnings; use XML::Twig; my $root= shift @ARGV; my( $base, @files)= sort glob( "$root-*.xml"); my %ns= ns_for_file( $base); foreach my $file (@files) { add_ns( $file, %ns); } sub ns_for_file { my( $base)= @_; my %ns; XML::Twig->new( start_tag_handlers # get namespace declarations from the root and bail => { 'level(0)' => sub { %ns= ns_for_tag( $_); $_[0]->finish_now(); } }, ) ->parsefile( $base); return %ns; } # get all namespace declarations from the root element sub ns_for_tag { my( $e)= @_; return map { $_ => $e->att( $_) if m{^xmlns:} } $e->att_names; } sub add_ns { my( $file, %ns)= @_; XML::Twig->new( start_tag_handlers => { 'level(0)' => sub { $_->set_att( %ns); } }, twig_handlers => { _all_ => sub { $_->flush; } }, keep_spaces => 1, ) ->parsefile_inplace( $file); } A: To process large XML files, you can also use a pull parser. See XML::LibXML::Reader.
{ "language": "en", "url": "https://stackoverflow.com/questions/22708031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can I remove the JSON-LD schema that Yoast adds to my WordPress site? I would like to remove the JSON-LD schema that Yoast applies to my WordPress site so that I can add my own. I have already added my own, and Google Structured Data Testing says that it is OK, but basically I have 3 separate JSON-LD schemas instead of two because of Yoast. You can see what I mean here: https://search.google.com/structured-data/testing-tool/u/0/#url=http%3A%2F%2Fwww.yogabearpc.com Yoast has added the WebSite schema and it seems unnecessary or even damaging? A: I wanted to disable this because of the sitelinks searchbox and the fact that I don't have a search function that works globally, just on the blog. Having the search box enabled for me would have undesirable effects. The easier option may just be to prevent Google using the sitelinks searchbox without having to touch the functions files. You can prevent Google using sitelinks searchbox on your site by using the following meta: <meta name="google" content="nositelinkssearchbox" /> If you want to disable Yoast's JSON-LD all together then here's a snippet from my blog and the code I use on my site: SOURCE How to disable Yoast SEO Schema JSON-LD completely function bybe_remove_yoast_json($data){ $data = array(); return $data; } add_filter('wpseo_json_ld_output', 'bybe_remove_yoast_json', 10, 1); Login to your WordPress dashboard and head over to the editor within the tab menu appearance, find your functions file (normally named functions.php) and add the code below just before the PHP tag is closed at the bottom. A: Simplest way to completely disable the Yoast SEO schema JSON-LD Add this line to functions.php file: add_filter( 'wpseo_json_ld_output', '__return_empty_array' ); Source A: If you want to disable just Organization or just Website, add this to your theme's functions.php file: function bybe_remove_yoast_json($data){ if ( (isset($data['@type'])) && ($data['@type'] == 'Organization') ) { $data = array(); } return $data; } add_filter('wpseo_json_ld_output', 'bybe_remove_yoast_json', 10, 1); A: Unless the data Yoast produces is wrong, there is no harm in having it. Quite the contrary, having more structured data is better than having less. If having it is "unnecessary" depends on your definition of what is necessary. Some consumers might be interested in it, others not. My guess is that Yoast adds a WebSite entity because of Google’s sitelinks searchbox rich snippet result, which allows Google users to search your site directly from the Google search result.
{ "language": "en", "url": "https://stackoverflow.com/questions/38619924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: JQuery not rendering HTML I am using $.get() in my ASP.NET MVC 3 application to get a response from database asynchronously. I get the response returning correctly and based on the response I generate my HTML in a string variable and finally append it to a div already on my markup page. In debug mode it shows me the complete HTML created but it doesn't get rendered in browser. Here is my sample code $.get("/Modules/FetchModuleActionsByModuleID", { ModuleID: ModuleID }, function (response) { if (response.replace(/"/g, '') != '{d:[]}' && response.replace(/"/g, '') != '{d:null}' && response.replace(/"/g, '') != '' && response != '') { var actions = eval('(' + response + ')'); var moduleHtml=""; if (actions.length > 0) { for (i = 0; i < actions.length; i++) { moduleHtml += "<div class='moduleFieldSetting'>"; moduleHtml += "<span class='pdRL10x2 fl'><input type='checkbox' name='" + ModuleName + "_Actions' value='" + actions[i].ActionID + "' /></span>"; moduleHtml += "<span>" + actions[i].ActionName + "</span>"; moduleHtml += "<div class='clear'></div>"; moduleHtml += "</div>"; } moduleHtml += "<div class='fr mt15'>"; moduleHtml += "<span class='fr'><input type='button' class='inpuButtonAdd' value='Save' /> "; moduleHtml += "<input type='button' class='inpuButtonAdd' value='Cancel' /> "; moduleHtml += "</span>" moduleHtml += "</div>"; moduleHtml += "</div>"; moduleHtml += "<div class='clear'></div>"; moduleHtml += "</div>"; moduleHtml += "</div>"; moduleHtml += "<div class='clear'></div>"; $("#divModuleDetails").append(moduleHtml); //appending to div } } }); What could be causing this? A: look at this line: moduleHtml += "</span>" i think the problem is script still printing only a span but maybe nothing :) anyway checkout below script optimization i think it should work ;) $.get("/Modules/FetchModuleActionsByModuleID", { ModuleID: ModuleID }, function (response) { if (response.replace(/"/g, '') != '{d:[]}' && response.replace(/"/g, '') != '{d:null}' && response.replace(/"/g, '') != '' && response != '') { var actions = eval('(' + response + ')'); var moduleHtml; if (actions.length > 0) { for (i = 0; i < actions.length; i++) { moduleHtml += "<div class='moduleFieldSetting'>" + "<span class='pdRL10x2 fl'><input type='checkbox' name='" + ModuleName + "_Actions' value='" + actions[i].ActionID + "' /></span>" + "<span>" + actions[i].ActionName + "</span>" + "<div class='clear'></div>" + "</div>"; } moduleHtml += "<div class='fr mt15'>" +"<span class='fr'><input type='button' class='inpuButtonAdd' value='Save' /> " + "<input type='button' class='inpuButtonAdd' value='Cancel' /> " +"</span>" + "</div>" + "</div>" + "<div class='clear'></div>" + "</div>" + "</div>" + "<div class='clear'></div>"; $("#divModuleDetails").append(moduleHtml); //appending to div } } });
{ "language": "en", "url": "https://stackoverflow.com/questions/6449748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: The Intercept of a categorical multiple regression R is not the mean value? Let's say I have 2 (categorical) variables and one continuous: library(tidyverse) set.seed(123) ds <- data.frame( depression=rnorm(90,10,2), schooling_dummy=c(0,1,2), sex_dummy=c(0,1) ) When I regress depression on sex (0 or 1), the intercept is 10.0436, what is the mean of sex = 0. Ok! ds %>% group_by(sex_dummy) %>% + summarise(formatC(mean(depression),format="f", digits=4)) # A tibble: 2 x 2 sex_dummy `formatC(mean(depression), format = "f", digits = 4)` <dbl> <chr> 1 0 10.0436 2 1.00 10.1640 The same thing happens when I regress depression on schooling. The intercept value is 10.4398. The mean of schooling = 0 is the same. ds %>% group_by(schooling_dummy) %>% + summarise(formatC(mean(depression),format="f", digits=4)) # A tibble: 3 x 2 schooling_dummy `formatC(mean(depression), format = "f", digits = 4)` <dbl> <chr> 1 0 10.4398 2 1.00 9.7122 3 2.00 10.1593 Now, when I compute a model with both variables, why the intercept is not the mean when both groups = 0? The regression **intercept is 10.3796, but the mean when sex = 0, and schooling is = 0 is 10.32548: ds %>% group_by(schooling_dummy,sex_dummy) %>% + summarise(formatC(mean(depression),format="f", digits=5)) # A tibble: 6 x 3 # Groups: schooling_dummy [?] schooling_dummy sex_dummy `formatC(mean(depression), format = "f", digits = 5)` <dbl> <dbl> <chr> 1 0 0 10.32548 2 0 1.00 10.55404 3 1.00 0 9.59305 4 1.00 1.00 9.83139 5 2.00 0 10.21218 6 2.00 1.00 10.10648 When I predict the model when both are 0: predict(mod3, data.frame(sex_dummy=0, schooling_dummy=0)) 1 10.37956 This result is related to depression (of course...) but still not What I was expecting, since: (Reference: https://www.theanalysisfactor.com/interpret-the-intercept/) What is the same for this previous forum post I aware of my variables are categorical and I'm adjusting my script, as you can reproduce using this code below: Thanks library(tidyverse) set.seed(123) ds <- data.frame( depression=rnorm(90,10,2), schooling_dummy=c(0,1,2), sex_dummy=c(0,1) ) mod <- lm(data=ds, depression ~ relevel(factor(sex_dummy), ref = "0")) summary(mod) ds %>% group_by(sex_dummy) %>% summarise(formatC(mean(depression),format="f", digits=4)) mod2 <- lm(data=ds, depression ~ relevel(factor(schooling_dummy), ref = "0")) summary(mod2) ds %>% group_by(schooling_dummy) %>% summarise(formatC(mean(depression),format="f", digits=4)) mod3 <- lm(data=ds, depression ~ relevel(factor(sex_dummy), ref = "0") + relevel(factor(schooling_dummy), ref = "0")) summary(mod3) ds %>% group_by(schooling_dummy,sex_dummy) %>% summarise(formatC(mean(depression),format="f", digits=5)) predict(mod3, data.frame(sex_dummy=0, schooling_dummy=0)) A: Two errors in your thinking (although your R code works so it's not a programming error. First and foremost you violated your own statement you have not dummy coded schooling it does not have only zeroes and ones it has 0,1 & 2. Second you forgot the interaction effect in your lm modeling... Try this... library(tidyverse) set.seed(123) ds <- data.frame( depression=rnorm(90,10,2), schooling_dummy=c(0,1,2), sex_dummy=c(0,1) ) # if you explicitly make these variables factors not integers R will do the right thing with them ds$schooling_dummy<-factor(ds$schooling_dummy) ds$sex_dummy<-factor(ds$sex_dummy) ds %>% group_by(schooling_dummy,sex_dummy) %>% summarise(formatC(mean(depression),format="f", digits=5)) # you need an asterisk in your lm model to include the interaction term lm(depression ~ schooling_dummy * sex_dummy, data = ds) The results give you the mean(s) you were expecting... Call: lm(formula = depression ~ schooling_dummy * sex_dummy, data = ds) Coefficients: (Intercept) schooling_dummy1 schooling_dummy2 10.325482 -0.732433 -0.113305 sex_dummy1 schooling_dummy1:sex_dummy1 schooling_dummy2:sex_dummy1 0.228561 0.009778 -0.334254 and FWIW you can avoid this sort of accidental misuse of categorical variables if your data is coded as characters to begin with... so if your data is coded this way: ds <- data.frame( depression=rnorm(90,10,2), schooling=c("A","B","C"), sex=c("Male","Female") ) You're less likely to make the same mistake plus the results are easier to read...
{ "language": "en", "url": "https://stackoverflow.com/questions/48621624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How I count the words and expressions in a text? I want to count how much times some given words or phrases appears in a text, but I want use some string similarity algorithms. Every word or expression has an value, so I will set the relevancy of the text according to the number of words found, etc. I guess that the String class from Java cannot offer this. I will need to iterate all the text for each word or expression I want to find? Is there a library for text handling? Example: find texts that has "videogame", "i have a videogame" and something like this, evaluating similar expressions. I guess if I iterate for each word or expression I need to evaluate, I cannot find the similar words and it will be more slower. A: but I want use some String similarity algorithms. Take a look at Lucene. Allows you to index some text and look for works using a similarity algorithm. I would think you want to split each words and index them using lucene. Then for all the words you are interested for you can search the index. You can do things like Automobile~ which will do a fuzzy search. Here is a rough algo: for each word in STRING.split(' ') index word for each word in your list search for word and look for number of occurrences A: The inverted index that Denniss said is what you are looking for. You'll need to define your Document very well if you want a powerfull engine. For phrase matches, your Document should have the position of the word (the key of the Map) in this Document. Once you got all the words you were looking for, you can know if this words were together in the original document. For example: doc1: "Hello World" doc2: "Hello Beautiful World" inverted index { "Beautifull": [(doc2, 2)], "Hello": [(doc1, 1)(doc2, 1)], "World": [(doc1, 2)(doc2, 3)], } query: "Hello World" Both documents have the words "Hello" and "World", but doc1 has them together (position 1 and 2) and doc2 doesn't (position 1 and 3). If you want to find similar words, you'll need a new structure. First, you need to define what is similar. Levenshtein distance is what you need for that. To implement it, you'll need a whole new struture like an automata: Levenshtein automaton. Full-text search is a huge area. Implementing a search engine is hard and many libraries and applications already do it. (I work for Indextank.com a realtime full-text search engine. If you need a search engine running in a couple of minutes, try us out) A: What you are looking for is porbably an Inverted File data structure. I learned this in database class and here is a link to the lecture. http://dl.dropbox.com/u/8950924/16Sp11-Search.pdf Basically the idea is to have a Map data structure Map<String, List<Document>> invertedIndex; where string is the word and List<Document> is the documents containing that word. If you read more into that pdf, you can even find a way to rank the document.
{ "language": "en", "url": "https://stackoverflow.com/questions/6848869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Not able to serve media files in django I am trying to create an online music player. I was trying to play a song in django. But it was not able to play since it was not able to detect the audio file. I have set up the media in django as I read on the internet but it's not working. Here is the screenshot of my project directory: detect and music are two apps. I am currently working with music app. Settings.py(included this at last of file). STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] MEDIA_ROOT = os.path.join(BASE_DIR,"media") MEDIA_URL = '/media/' urls.py: from django.conf.urls import * from django.contrib import admin from detect import views from music import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^music/$',views.play,name = 'play') ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) views.py: from django.shortcuts import render from django.http import HttpResponse def play(request): return render(request,'music/song.html',{}) song.html: <html> <audio id="Player" autoplay> <source src="{{MEDIA_URL}}/audio/test.mp3"/> </audio> </html> A: Pass MEDIA_URL like to render like this render(request,'music/song.html',{'MEDIA_URL': settings.MEDIA_URL}) and make sure to include from django.conf import settings in your views.py.
{ "language": "en", "url": "https://stackoverflow.com/questions/40386006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Joomla ZOO item counter I'm using joomla 3, zoo component. In the backend of the system i have this code to display numbers of items in the every zoo application installed: <?php echo $application->getItemCount(); ?> What i need is to edit this code to display only numbers of items that are "published". I'm not sure how to do this as i'm not a php coder. Any suggestions, please? A: You could try fetching the data from the database. Check out the doc here. Here is some sample code witch should help $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('COUNT(*)'); $query->from($db->quoteName('#__tablename')); $query->where($db->quoteName('published') . ' = 1'); $row = $db->loadRow(); print_r($row); You will need to find the table where the data is stored and replace __tablename accordingly (and maybe change the column name "published" if needed)
{ "language": "en", "url": "https://stackoverflow.com/questions/25761764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What extension for underlining html in visual studio code editor? I need something like this (i have in bracket editor) but I don't know its come from which extension. A: There is a extension for that. Simply search for "highlight-matching-tag" in the extension tab or download it here: https://marketplace.visualstudio.com/items?itemName=vincaslt.highlight-matching-tag I recommend to set a custom setting like this: "highlight-matching-tag.style": { "borderWidth": "1px", "borderColor": "orange", "borderStyle": "solid" }
{ "language": "en", "url": "https://stackoverflow.com/questions/47964749", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to create a new metastore? I want to configure Unity Catalog and one step is creating a metastore in the region where I create databricks workspace (I am on Azure). I created a workspace with a premium pricing tier and I am the admin. Following the documentation, I should go to the Data tab to create metastore. However, when I open the Data tab, I don't see "Create Metastore" button. The same in SQL persona: Could you guide me how to make a new metastore? If a metastore is already created in the region, how can I find it? A: In order to do this sort of management, you should access the Databricks account portal at the tenant level: Databricks Account From there, you can create and manage the metastores, as well as assign a metastore with a Databricks Workspace, which is what you have created. Take into account that for most of what you have described, you must be an account admin for the Databricks Account. As per the official docs (source): The first Azure Databricks account admin must be an Azure Active Directory Global Administrator at the time that they first log in to the Azure Databricks account console. Upon first login, that user becomes an Azure Databricks account admin and no longer needs the Azure Active Directory Global Administrator role to access the Azure Databricks account. The first account admin can assign users in the Azure Active Directory tenant as additional account admins (who can themselves assign more account admins). Additional account admins do not require specific roles in Azure Active Directory. A: You must be an Azure Databricks account admin to getting started using Unity Catalog this can be done for first time using Azure Active Directory Global Administrator of your subscription. As per official documentation: The first Azure Databricks account admin must be an Azure Active Directory Global Administrator at the time that they first log in to the Azure Databricks account console. Upon first login, that user becomes an Azure Databricks account admin and no longer needs the Azure Active Directory Global Administrator role to access the Azure Databricks account. The first account admin can assign users in the Azure Active Directory tenant as additional account admins (who can themselves assign more account admins). Additional account admins do not require specific roles in Azure Active Directory. How to identify your Microsoft Azure global administrators for your subscriptions? The global administrator has access to all administrative features. By default, the person who signs up for an Azure subscription is assigned the global administrator role for the directory. Only global administrators can assign other administrator roles. Login into the Azure Databricks account console via Global admin and then account admin can assign users in the Azure Active Directory tenant. For more details, refer to Azure Databricks - Get started using Unity Catalog and also refer to MS Q&A thread - How to access Azure Databricks account admin? addressing similar issue. A: Configure your Unity Catalog Metastore Go to + New add click on new notebook and open. If you already have catalogs with data .then use below command to check, # Show all catalogs in the metastore. display(spark.sql("SHOW CATALOGS")) If you don't have catalog . create utility catalog : # Create a catalog. spark.sql("CREATE CATALOG IF NOT EXISTS catalog_name") # Set the current catalog. spark.sql("USE CATALOG catalog_name") for more information refer this offical_document and Notebook.
{ "language": "en", "url": "https://stackoverflow.com/questions/75483215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ProductName hides System.Windows.Forms.Control.ProductName I have a property ProductName in my Form. I am getting warning while compiling the code. FormInventory.ProductName hides inherited member 'System.Windows.Forms.Control.ProductName'. Use the new keyword if hiding was intended. below is my code public partial class FormInventory : Form, IInventoryView { public FormInventory() { } public string ProductName { get { return this.textProductName.text; } set { this.textProductName.text = value; } } } textProductName is a textbox. I know that ProductName hides the base class's property Forms.Control.ProductName. My question is * *Is it possible to suppress the warning without Renaming my FormInventory.ProductName property *I am currently in the beginning of the development, if i hide this property with the new modifier will there be any problem at the time of releasing the product, because base property Forms.Control.ProductName returns the product name of the assembly containing the control. Where as my FormInventory.ProductName returns a user entered value. *Where will we be using this Forms.Control.ProductName, because i have never used it before. I have searched and found Similar questions * *Entity Framework hides inherited member Warning *Use new keyword if hiding was intended these questions doesn't solve my problem but helped me in understanding the cause for the warning. A: If ProductName is a form field that you intend displaying on the form, why not instead abstract all the fields of property into a separate Product entity. This should ease the maintenance of your app (and bring it more in line with patterns like MVC / MVVM), e.g. public class Product { public string ProductName{ get; set; } public int ProductSize{ get; set; } // etc } public partial class FormInventory : Form { public FormInventory() { } public Product Product { get; set; } } Edit : IMO, the architecture presented by Rod Cerata's blog looks OK, but I believe it would be improved via encapsulation of a "ViewModel" for your Employee. Have a look at EmployeePresenter.cs - you get lots of repetitive scraping code like this: _model.EmployeeID = _view.EmployeeID; _model.Lastname = _view.Lastname; _model.Firstname = _view.Firstname; _model.EmployeeType = _view.EmployeeType; _model.Salary = _view.Salary; _model.TAX = _view.TAX; IMO would be improved by creating a new EmployeeViewModel class (which would be more or less the same as EmployeeModel, plus any 'screen' specific fields e.g. Title, "mode" (Edit, New, Read Only etc), and then using a tool like AutoMapper, which would reduce the code above. A: 1. Yes, simply use the new keyword, like public new string ProductName { get; set; } 2. No, it simply returns the name of the assembly. 3. Its used for debugging and some "reflection". I say "reflection" because it's more like a human-made reflection. So, it's safe to go forward this way. But why don't you simply change it to MyCompanyProductName? Regards A: Using the 'new' keyword will suppress the warning. When you do this, the result of calling the ProductName property depends on Type of the variable that is used to referenced the form... for example, if you're calling the property from another class: // Notice that we're only creating one object and // assigning it to two different variables. FormInventory explicitlyNameForm = new FormInventory(); Form referenceToBaseForm = explicitlyNameForm; // Acting on the child reference (FormInventory) will // operate on YOUR implementation of ProductName explicitlyNameForm.ProductName = "Some Value"; // But acting on the parent reference (Form) will // operate on the .NET implementation of ProductName referenceToBaseForm.ProductName = "Some Other Value"; The end result will probably be what you want... the compiler knows which implementation to use based on how you've declared your variable. And since all references within the .NET framework reference the Form class, not your new class, there is no risk of affecting anything that happens within the .NET framework with respect to this property. However, as the others have suggested, it may cause less confusion if you're able to rename the property.
{ "language": "en", "url": "https://stackoverflow.com/questions/11733253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: vector in C++ can only read the last element I add several element to the vector, but when I visit them, they are all the one which is added at last. I can't understand. here is my code: while(true){ cin>>shape; if(shape=='X') break; if(shape=='C'){ cin>>x>>y>>r; Circle c(x,y,r); shapes[sum] = &c; //cout<<shapes[sum]->getArea()<<endl; sum++; }else if(shape=='R'){ cin>>x1>>y1>>x2>>y2; Rectangle rec(x1,y1,x2,y2); shapes[sum] = &rec; //cout<<shapes[sum]->getArea()<<endl; sum++; } else if(shape=='T'){ cin>>x1>>y1>>x2>>y2>>x3>>y3; Triangle tr(x1,y1,x2,y2,x3,y3); shapes[sum] = &tr; //cout<<shapes[sum]->getArea()<<endl; sum++; } } for(int j=0; j<sum; j++){ showArea(shapes[j]); } I found that at last, all the element in the vector is same, they are the element which is added at last. A: Your vector stores pointer. And you store inside it pointer of local variables: } else if(shape=='T'){ cin>>x1>>y1>>x2>>y2>>x3>>y3; Triangle tr(x1,y1,x2,y2,x3,y3); // <= Create local variable, automatic allocation shapes[sum] = &tr; // <= store its address //cout<<shapes[sum]->getArea()<<endl; sum++; } // <= automatic dealocation of tr, ie tr doesn't exist anymore // shapes[sum - 1] stores address of no more existing variable => Undefined behavior you should do: } else if(shape=='T'){ cin>>x1>>y1>>x2>>y2>>x3>>y3; Triangle *tr = new Triangle(x1,y1,x2,y2,x3,y3); // manual allocation shapes.push_back(tr); //cout<<shapes[sum]->getArea()<<endl; sum++; } BUT you have to deallocate with delete when you don't need anymore objects in vector sum isn't necessary: you have to use push_back to avoid Undefined Behavior, and after, you can use shapes.size() to retrieve size of vector. Indeed, accessing to an element of vector which is out of bound (ie when you do vector[n], n is equal or greater than vector.size()) is undefined behavior. Modern way of doing this: use of shared_ptr or unique_ptr
{ "language": "en", "url": "https://stackoverflow.com/questions/40848059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Is ~~ a short-circuit operator? From the Smart matching in detail section in perlsyn: The smart match operator short-circuits whenever possible. Does ~~ have anything in common with short circuit operators (&&, ||, etc.) ? A: The meaning of short-circuiting here is that evaluation will stop as soon as the boolean outcome is established. perl -E "@x=qw/a b c d/; for (qw/b w/) { say qq($_ - ), $_ ~~ @x ? q(ja) : q(nein) }" For the input b, Perl won't look at the elements following b in @x. The grep built-in, on the other hand, to which the document you quote makes reference, will process the entire list even though all that's needed might be a boolean. perl -E "@x=qw/a b c/; for (qw/b d/) { say qq($_ - ), scalar grep $_, @x ? q(ja) : q(nein) }" A: Yes, in the sense that when one of the arguments is an Array or a Hash, ~~ will only check elements until it can be sure of the result. For instance, in sub x { ... }; my %h; ...; %h ~~ \&x, the smart match returns true only if x returns true for all the keys of %h; if one call returns false, the match can return false at once without checking the rest of the keys. This is similar to the && operator. On the other hand, in /foo/ ~~ %h, the smart match can return true if it finds just one key that matches the regular expression; this is similar to ||.
{ "language": "en", "url": "https://stackoverflow.com/questions/5909430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Site doesn't scroll smoothly (HTML + CSS) I'm creating a site using HTML and CSS for a school project (there's no JS involved). I use a Smooth Scrolling addon on Google Chrome, but the page doesn't scroll smoothly like every other page on the Internet does. Instead, it scrolls in blocky chunks down the page. JSFiddle: Here <div id="header" class="shadow2"> <div id="header-container"> <a href="index.html"> <div id="logo"></div> </a> (the first few lines of code just for the JSFiddle link) Interestingly, the preview in JSFiddle scrolls smoothly :/ Thanks in advance :) A: Tested on Chrome, and it scrolls just fine. Scrolling is controlled by your mouse settings, so maybe something changed with your scroll wheel?
{ "language": "en", "url": "https://stackoverflow.com/questions/25759264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Run separate nodejs file from PhantomJS / CasperJS I'm trying to execute a nodejs script from CasperJS. This should be possible from the PhantomJS childprocess library. But it doesn't seem to be working for me. It's not giving any errors, but it's not executing the node script either. Because that script sends out a push notification. When I run the script directly from command then it works fine. But not from my CasperJS script. var childProc = require("child_process"); var casper = require('casper').create({ viewportSize: {width: 800, height: 400} }); var utils = require("utils"); casper.start('http://www.google.com', function() { this.echo('Home page opened'); this.echo(this.getTitle()); childProc.execFile('C:\\Google Drive\\nodejs\\push.js', [], null, function (err, stdout, stderr){}); this.exit(); }); Anyone any idea what I'm doing wrong? A: You have two problems: * *You forgot to add the command for execution *You're exiting too early, because execFile is an asynchronous function. Try: casper.start('http://www.google.com', function() { this.echo('Home page opened'); this.echo(this.getTitle()); childProc.execFile('C:\\Google Drive\\nodejs\\push.js', [], null, function (err, stdout, stderr){ utils.dump(arguments); casper.echo("Exiting..."): casper.exit(); }); }).run(function(){/* This prevents CasperJS from exiting */});
{ "language": "en", "url": "https://stackoverflow.com/questions/32186199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Map Projection is not working as expected when zoom level is not the same I want to show the user location on top of the drawer that I have in my app instead of center of the map since the drawer covers part of the map : fun centerMap(height: Int, drawerHeight: Int) { LocationDataProvider.location?.let { val length = ((height - drawerHeight) / 2) + (drawerHeight - (height / 2)) val point = googleMap.projection.toScreenLocation(LatLng(it.lat, it.lng)) Log.d("Ali", "${point.y.toString()}, ${point.x.toString()}") val newY = point.y + length val newLatLng = googleMap.projection.fromScreenLocation(Point(point.x, newY)) moveCamera(newLatLng) } } LocationDataProvider.location returns center of the map. Here is moveCamera method : fun moveCamera(location: LatLng) { val cameraUpdate: CameraUpdate = CameraUpdateFactory.newLatLngZoom( location, 18F ) googleMap.animateCamera(cameraUpdate) googleMap.setOnCameraMoveStartedListener(this@MapController) } In my logic CenterMap method is called every 5 seconds.The problem is first it zooms somewhere over ocean and then immediately in 5 seconds, it zooms on the desired location (top of the drawer). Here is the log result of centerMap method every 5 seconds ("${point?.y.toString()}, ${point?.x.toString()}"): D/Ali: 468, 1344 D/Ali: -18826752, 4133 D/Ali: 418, 542 D/Ali: 419, 539 ... As you see as a result of first log, it moves over ocean, from the second log it moves to desired location, and from there, it will be on desired location. I concluded that when zoom level is not 18f, projection is not working as expected, so if I use following method, and then use projection, it works as expected : fun centerMap() { LocationDataProvider.location?.let { moveCamera(LatLng(it.lat, it.lng)) } } That means moveCamera method will be called twice, but is there any solution that projection works as expected without considering zoom level? A: Seems you can use map padding GoogleMap.setPadding(): public void setPadding (int left, int top, int right, int bottom) Sets padding on the map. This method allows you to define a visible region on the map, to signal to the map that portions of the map around the edges may be obscured, by setting padding on each of the four edges of the map. Map functions will be adapted to the padding. For example, the zoom controls, compass, copyright notices and Google logo will be moved to fit inside the defined region, camera movements will be relative to the center of the visible region, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/74178336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP - Failed to Open Stream Error (no such file or directory) I have following directory structure for the project: Home.php simply includes either of the two views i.e. login or invoice depending upon the session variables. if (!isset($_SESSION['username'])) { include 'views/login.php'; } else { include 'views/invoice.php'; } I include my constants file which contain database connection strings and other constants along with a autoloader file which register a autoload function to include all the classes. include 'includes/constants.php'; include 'includes/autoloader.php'; It works without issues but when i use the same in get_data.php file it gives following error: Warning: include(includes/constant.php): failed to open stream. No such file or directory. Same error for autoloader.php too.
{ "language": "en", "url": "https://stackoverflow.com/questions/31386167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Yajra laravel datatables oracle disable escaping string How to disable escaping string in yajra/laravel-datatables-oracle? version: "dev-master" http://take.ms/hKGEI A: I found the answer to your question. After updating yajra/laravel-datatables-orakle package to version 7.* - All columns escaped by default to protect from XSS attack. To allow columns to have an html content, use rawColumns api. doc
{ "language": "en", "url": "https://stackoverflow.com/questions/41888450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Software PDR - how to explain the code by PDR ( preliminary design review) with clock/diagram I am trying to write PDR for the first time. I have the follwoing important blocks/parts which I want to demonstrate in the PDR by blocks or diagarm (e.g UML). * *A job's queue which I add a new job (estimation job). *The job "contains" a function (device_estimation) which call another function (send_msg). Bothe functions belongs to the same class. How should I descript those three parts (the job, and the 2 functions) by special blocks / diagram? p.s I use Visio A: You could use a sequence diagram in this case. It's easy to show call structures like in your case.
{ "language": "en", "url": "https://stackoverflow.com/questions/36691536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Openpyxl - I can't set cell format and sum values correctly in time format (h:mm) openpyxl version 3.0.7, python version 3.8.8 I’m trying to format cells as hours:minutes. From reading the openpyxl doc’s re formatting numbers: https://openpyxl.readthedocs.io/en/stable/_modules/openpyxl/styles/numbers.html FORMAT_DATE_TIME3 should do what I need. It uses BUILTIN_FORMATS(20) which is 'h:mm'. However, my implementation of the code does not have the expected results on the spreadsheet. The values come out as expected, but not with the formatting. I want the cells to be formatted as h:mm, so when I add 1:02 and 1:58 I get 3:00 ( for 3 hours). I've tried 2 different ways to format a cell (meth 1 & meth 2), with a sum formula for meth 1 column but I'm not quite there. Any help would be appreciated, Thanks. from openpyxl import Workbook from openpyxl import load_workbook from openpyxl.styles import numbers wb = Workbook() ws = wb.active ws['A3'] = "Meth 1" ws['A4'] = "1:02" ws['A5'] = "1:58" ws['A4'].number_format = numbers.FORMAT_DATE_TIME3 ws['A5'].number_format = numbers.FORMAT_DATE_TIME3 print('A4 number format = ', ws['A4'].number_format) print('A5 number format = ', ws['A5'].number_format) cell = ws.cell(row=7, column=1, value='= SUM(A{}:A{})'.format(4, 5)) cell.number_format = numbers.FORMAT_DATE_TIME3 ws['C3'] = "Meth 2" cell = ws.cell(row=4, column=3, value="1:02".format(numbers.FORMAT_DATE_TIME3)) cell.number_format = numbers.FORMAT_DATE_TIME3 cell = ws.cell(row=5, column=3, value="1:58") cell.number_format = numbers.FORMAT_DATE_TIME3 wb.save(filename = 'hours_mins.xlsx') I have printed the number format to verify it is the format required A4 number format = h:mm A5 number format = h:mm excel output produced: A: You have entered the times as strings. As such, the formatting for numbers has no effect. You need to enter either datetime.time objects or datetime.timedelta objects in order for the formatting to have an effect, though openpyxl by default will try and set it correctly. eg. ws["A4"] = datetime.time(hours=1, minutes=2)
{ "language": "en", "url": "https://stackoverflow.com/questions/68739858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I include formulas in a struct somehow? I am trying to create a struct which uses a formula to automatically create data in one of the struct fields when the other two values are entered. For example, I want to create a 2D rectangular room with Length and Width which are values that are entered. I would then like to include the formula Area = Length * Width in the struct. Have tried and just get a syntax error : syntax error: unexpected =, expecting semicolon or newline or } // CURRENT CODE type room struct { L int W int A int } // WOULD LIKE IT TO BE type room struct { L int W int A int = room.L*room.H } A: Since A is invariant, this would be a good fit for a function, not a field. type room struct { L int W int } func (r *room) area() int { return r.L * r.W } A: If you would like to keep A as a Field, you can optionally preform the computation in a constructor. type room struct { L int W int A int } func newRoom(length, width, int) room { return room{ L: length, W: width, A: length * width, } } A: If you think about what you're after, you'll see that basically your desire to "not add unnecessary code" is really about not writing any code by hand, rather than not executing any code: sure, if the type definition type room struct { L int W int A int = room.L*room.H } could be possible in Go, that would mean the Go compiler would have make arrangements so than any code like this var r room r.L = 42 is compiled in a way to implicitly mutate r.A. In other words, the compiler must make sure that any modification of either L or W fields of any variable of type room in a program would also perform a calculaton and update the field A of each such variable. This poses several problems: * *What if your formula is trickier—like, say, A int = room.L/room.W? First, given the casual Go rules for zero values of type int, an innocent declaration var r room would immediately crash the program because of the integer division by zero performed by the code inserted by the compiler to force the invariant being discussed. Second, even if we would invent a questionable rule of not calculating a formula on mere declarations (which, in Go, are also initializations), the problem would remain: what would happen in the following scenario? var r room r.L = 42 As you can see, even if the compiler would not make the program crash on the first line, it would have to arrange for that on the second. Sure, we could add another questionable rule to sidestep the problem: either somehow "mark" each field as "explicitly set" or require the user to provide an explicit "constructor" for such types "armed" with a "formula". Either solution stinks in its own way: tracing write field access incurs performance costs (some fields now have a hidden flag which takes up space, and each access of such fields spends extra CPU counts), and having constructors goes again one of the cornerstone principles of the Go design: to have as little magic as possible. *The formula creates a hidden write. This may not be obvious until you start writing "harder-core" Go programs for tasks it shines at—highly concurrent code with lots of simultaneously working goroutines,—but when you do you're forced to think about shared state and the ways it's mutated and—consequently—on the ways such mutations are synchronized to keep the program correct. So, let's suppose we protect access to either W or L with a mutex; how would the compiler make sure mutation of A is also proteted given that mutex operations are explicit (that is, a programmer explicitly codes locking/unlocking operations)? *(A problem somewhat related to the previous one.) What if "the formula" does "interesting things"—such as accessing/mutating external state? This could be anything from accessing global variables to querying databases to working with a filesystems to exchanges over IPC or via networking protocols. And this all could be very innocently-looking, like A int = room.L * room.W * getCoefficient() where all the nifty details are hidden in that getCoefficient() call. Sure, we, again, could work-around this by imposing an arbitrary limit on the compiler to only allow explicit access to the fields of the same enclosing type and only allow them to participate in simple expressions with no function calls or some "whitelisted" subset of them such as math.Abs or whatever. This clearly reduces the usefulness of the feature while greatly complicating the language. *What if "the formula" has non-linear complexity? Suppose, the formula is O(N³) with regard to the value of W. Then setting W on a value to 0 would be processed almost instantly but setting it to 10000 would slow the program down quite noticeably, and both of these outcomes would result form a seemingly not too different statements: r.W = 0 vs r.W = 10000. This, again, goes agains the principle of having as little magic as possible. *Why would we ony allow such things on struct types and not on arbitrary variables—prodived they are all in the same lexical scope? This looks like another arbitrary restriction. And another—supposedly—the most obvious problem is what should happen when the programmer goes like var r room r.L = 2 // r.A is now 2×0=0 r.W = 5 // r.A is now 2×5=10 r.A = 42 // The invariant r.A = r.L×r.W is now broken ? Now you can see that all the problems above may be solved by merily coding what you need, say, with the following approach: // use "unexported" fields type room struct { l int w int a int } func (r *room) SetL(v int) { r.l = v updateArea() } func (r *room) SetW(v int) { r.w = v updateArea() } func (r *room) GetA() int { return r.a } func (r *room) updateArea() { r.a = r.l * r.w } With this approach, you may be crystal-clear about all the issues above. Remember that the programs are written for humans to read and only then for machines to execute; it's paramount for proper software engeneering to keep the code as much without any magic or intricate hidden dependencies between various parts of of it as possible. Please remember that Software engineering is what happens to programming when you add time and other programmers. © Russ Cox See more.
{ "language": "en", "url": "https://stackoverflow.com/questions/58577649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring AOP - proxying object returned from method In this example: public class ConnectionPool { public java.sql.Connection getConnection() { ... } } @Bean @Scope("singleton") public ConnectionPool connectionPool(...) throws Exception { return new ConnectionPoolImpl(...); } I want to monitor calls to java.sql.Connection.close() on Connection objects returned from getConnection(). I tried adding @Lookup to the getConnection() method but it had no effect. How do I get Spring to proxy the java.sql.Connection object? A: You can create proxy for the ConnectionPool and return the proxy in the bean creation method @Bean @Scope("singleton") public ConnectionPool connectionPool(...) throws Exception { ConnectionPoolImpl delegate = new ConnectionPoolImpl(...); ConnectionPoolCallHandler callHandler = new ConnectionPoolCallHandler(delegate); ConnectionPool proxy = Proxy.newProxyInstance( ConnectionPool.getClass().getClassLoader(), new Class[]{ConnectionPool.class}, callHandler); // return new ConnectionPoolImpl(...); return proxy; } and public class ConnectionPoolCallHandler implements InvocationHandler { private ConnectionPoolImpl delegate; public ConnectionPoolCallHandler(ConnectionPoolImpl delegate) { this.delegate=delegate; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //all invoked methods should call //appropriate methods of delegate passing all parameters //plus your additional tracking logic here } } A: @Pointcut("within(java.sql.Connection.close(..)") public void closeAspect() {} @Around("closeAspect()") public void logAround(ProceedingJoinPoint joinPoint) throws Throwable { joinPoint.getThis();//Will return the object on which it(close function) is called //Do whatever you want to do here joinPoint.proceed(); //Do whatever you want to do here }
{ "language": "en", "url": "https://stackoverflow.com/questions/43983439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Classify each case in dataframe with significant groups (or clusters) in stratified data I am needing to cluster (perhaps k-means) a dependent variable (Value) considering stratification by two independents (Country; Year); and at the end classify each df case (example top, middle and bottom). df structure: df <- structure(list(Country = c("B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "E", "E", "E", "E", "E", "E", "E", "E", "E", "E"), Year = c(2019L, 2019L, 2019L, 2019L, 2019L, 2020L, 2020L, 2020L, 2020L, 2020L, 2019L, 2019L, 2019L, 2019L, 2019L, 2020L, 2020L, 2020L, 2020L, 2020L), Value = c(64, 48, 20, 49, 43, 39, 32, 56, 36, 32, 70, 45, 36, 40, 34, 72, 49, 54, 26, 16)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -20L)) What I have done so far: library(tidyverse) df %>% group_by(Country, Year, .add = TRUE) %>% group_split() %>% map_df( ~ .x %>% mutate(cluster = kmeans(.x[, c('Value')], 3)$cluster)) However, I am concerned that group stratification is not being incorporated. In my real df the message is returned: Warning: did not converge in 10 iterations
{ "language": "en", "url": "https://stackoverflow.com/questions/73534229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ignoring leading whitespace when manipulating standard one-dimensional arrays We have to read from a file in this case called small.txt. The contents of the file look like the following: NOT 11010011 AND 10010010 11001110 OR 10011001 11100101 CONVERT 10010110 LSHIFT 11001101 3 WRONG 01010100 10101010 Every word indicates the beginning of a new line in this file. The problem I'm having is getting my code to read in the last (3rd column). Each column is ten spaces in length. The following are the rules I have to follow: Based on the commands in the file, perform operations on the operands following the command. Each command is independent from another, so one command cannot affect another. The commands are all binary commands, but you can’t use C++’s built in commands for this. This means no: “~, &, |, << (when used as a binary operator)”. You can of course use && and ||, these are different. << Can be used for cout as always, just not as a binary operator. you cannot use strings to read in the operands. I have tried: inputFile.ignore(20, '\n') but if that is the right way. I'm not using it correctly. Here is my code: /* ==================================================================== SUMMARY Read commands which will require the program to perform some operation on either one or two bit patterns, determine the result of the operation, and output accordingly. NOT: Takes 1 operand and performs a bitwise logical NOT. At each position, if the operand has a 0, the result will contain a 1. If the operand has a 1, the result will contain a 0. Eg. operand 11010011 result 00101100 In logical operations, a 1 represents TRUE and a 0 FALSE. AND: Takes 2 operands and performs a bitwise logical AND. At each position, if both operand 1 and operand 2 contain a 1, the result will be a 1. Otherwise the result is 0. Eg. operand 1 10010010 operand 2 11001110 result 10000010 OR: Takes 2 operands and performs a bitwise logical OR. At each position, if either operand 1 or 2 or both contain a 1, the result will contain a 1. Otherwise the result will contain a 0 (inclusive OR). Eg. operand 1 10011001 operand 2 11100101 result 11111101 CONVERT: Takes 1 operand and converts it to a base 10 integer. Note: we will let every bit in these binary numbers represent part of a positive binary integer, i.e. there is no "sign" bit. Thus we can only represent positive integers in the range from 0 thru (28 - 1). Eg. operand 10010110 result = (1 * 2**7) + (0 * 2**6) + (0 * 2**5) + (1 * 2**4) + (0 * 2**3) + (1 * 2**2) + (1 * 2**1) + (0 * 2**0) = 150 in base 10 LSHIFT: Logical Shift to Left Takes 1 operand and an integer N as input. The bit values are shifted N positions to the left. Data "pushed off" the left end is lost. Zeroes replace the lost bits. Eg. operand 1 11001101 N = 3 result 01101000 You may assume N is valid, i.e. 0 <= N <= 8 ====================================================================== ASSUMPTIONS The binary operands will contain exactly 8 bits, where a bit is a binary digit. A byte contains 8 bits. Check for invalid command names. Assume that the binary operands are all correctly given in the data file. ====================================================================== INPUT From the data file binaryData.txt. ======================================================================= OUTPUT Echo print all input values. Then output in a suitable fashion the results of the operation performed, and any necessary error messages. */ /* ========================================================================================*/ /* HEADER FILES */ #include <iomanip> // needed for output manipulation #include <iostream> // needed for standard I/O routines #include <fstream> #include <string> // needed for reading data from files using namespace std; /* ====================================================================================*/ /* FUNCTION /* ================================================================== */ /* NAMED GLOBAL CONSTANTS */ const int ARRAY_SIZE = 8; // array size /* =========================================================================== */ /* MAIN FUNCTION */ int main (){ int numbers[ARRAY_SIZE]; // array with 8 elements int secondArray[ARRAY_SIZE]; // array two with 8 elements int thirdArray[ARRAY_SIZE]; // array three with 8 elements int count = 0; // loop counter variable ifstream inputFile; // input file stream object // open the file inputFile.open ("small.txt"); // exit if a fatal error occurs opening the file if( !inputFile ){ cout << "Error: Data file could not be opened \n"; system ("pause"); return (EXIT_FAILURE); } // end of not in file if statement // read the array string word; while(inputFile){ // stores the word read in by the file inputFile >> word; if(word == "NOT"){ cout << word << " "; // This allows you to be able to read in each number one by one for(int i = 0; i < ARRAY_SIZE; i++){ char letter(20); inputFile >> letter; letter = letter - '0'; numbers[i] = static_cast<int>(letter); if (letter == 0){ numbers[i] = letter + 1; } else{ numbers[i] = letter - 1; } } // end of first for loop for(int i = 0; i < ARRAY_SIZE; i++){ cout << numbers[i]; } // end of second for loop } // end of if word == not check if(word == "AND"){ cout << "\n\n" << word << " "; // This allows you to be able to read in each number one by one for(int i = 0; i < ARRAY_SIZE; i++){ //inputFile.ignore(20, '\n'); char letter; inputFile.ignore(10) >> letter; letter = letter - '0'; secondArray[i] = static_cast<int>(letter); } // end of first for loop for(int i = 0; i < ARRAY_SIZE; i++){ cout << secondArray[i]; } // end of second for loop } // end of if word == not check } // end of while inputFile loop inputFile.clear ( ); inputFile.close ( ); cout << endl; system ("pause"); return (0); } // end of main function A: Your code has already consumed the first two columns from the stream and the position of the stream is past those columns. In turn, it isn't necessary to call ignore to move the stream position past those columns. Besides ignore ifstream provides some additional functions that you may find useful.
{ "language": "en", "url": "https://stackoverflow.com/questions/13353821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JNI Global reference to PacketWriter in smack library, how to identify the cause JNI Global referece? I am using smack library to connect to Facebook XMPP server. In my local enviroment debug mode, memory leak sometimes happened. I have: * *checked the heap dump, *found that JNI Global reference always referred to PacketWriter object in smack library, *PacketWriter contains one thread to do output work Question: what caused the JNI Global reference? (of course no JNI used in the server) Is the JNI Glabal reference caused by debug mode of the server? I already checked the question: How to identify the cause of a JNI global reference memory leak?. This is smack source code view: Update the heap dump is very big, I post the screenshot of VisualVM about heap http://sphotos-a.ak.fbcdn.net/hphotos-ak-ash3/21927_384581804957834_1241962037_n.jpg
{ "language": "en", "url": "https://stackoverflow.com/questions/13707491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: rails/ruby "and return false" syntax I've seen this code in a rails tutorial I'm doing def access_denied redirect_to login_path, :notice => "Please log in to continue" and return false end Before learning rails, I did a large amount of ruby research and none of the books I read covered this "and return false" syntax going on here. I can't find any mention of it in the rails syntax, is anyone able to provide a link or any explanation that would clear this up? I don't understand the need for the "and" in here as I thought ruby would always return the last evaluated expression. A: redirect_to login_path, :notice => "Please log in to continue" is a normal expression in Ruby that does not return false (or nil, see the source code), so program execution continues (to check the second part after AND) and return false can be executed. A: The and is there only for you to be able to write the return false at the same line as the previous statement. It's equivalent of doing this: redirect_to login_path, :notice => "Please log in to continue" return false it's not exactly the same because with the "and" it would only return false if the redirect_to method returns something that isn't nil or false but as it almost always returns something that is not nil nor false then the right side of the statement is always executed (and false is returned). The and in Ruby is just an alias to && and behaves exactly like it with only one difference, it has a lower precedence than all other pieces of the statement, so first it evaluates whatever is on it's left and then gets applied. Ruby also has the or which is the same as || but with a lower precedence in expressions. A: This kind of construct used to be used with a filter, when filter return values were expected. The false would halt normal request processing. So if a controller looked like this: class FooController < ActionController::Base before_filter :access_denied # etc. end None of the controller's actions would run; this method was likely designed to be called from a filter, like: def check_access return access_denied unless current_user.has_access end These days filter return values are ignored. It could be used as a normal method in an action to stop processing the action and return after the redirect, so no other logic/rendering/etc. is run inside the controller. A: Documentation on operators: Under the "Defined?, And, Or, and Not" section Using and is useful for chaining related operations together until one of them returns nil or false. You can use it like you showed in your question or you can also use it to short-circuit the line of code. # Short circuit example blog = Blog.find_by_id(id) and blog.publish! The blog only gets .publish! called on it if the find_by_id was successful. In your example: def access_denied redirect_to login_path, :notice => "Please log in to continue" and return false end They are just using it to write the code more compactly on one line. However, it is also useful for a controller action where you may be rendering based on conditionals and you don't want to get Rails "multiple renders" warning: def show if something render :partial => 'some_partial' end render :partial => 'some_other_partial' end Rails will give you a warning if something returns true since you have multiple render statements being evaluated in the action. However, if you changed it to if something render :partial => 'some_partial' and return end it would allow you to stop the action execution.
{ "language": "en", "url": "https://stackoverflow.com/questions/8825396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Is there a way to compare four sets of lists and retrieve the exact value? I have a small large problem. Basically, I have some sets of lists that I need to compare and extract the value from it. brand = ["brand_1", "brand_2"] search_type = [4, 10] brand_search = ["brand_1", "brand_2","brand_3"] value_search = ["value1", "value_2","value_3"] I hope that I can explain myself. I would like to search the brand_search to find if there's a match with brand then I need to extract exactly the value_search so that I can use the search_type to retrieve a part of the value_search. I think this is very tricky and sketchy to do. I tried many methods but failed to extract specifically the value_search. A: Your question isn't very clear, but I'm guessing this is what you want. Use enumerate() to iterate through brand_search along with the indexes. When you find a match, get the corresponding element of value_search. for i, item in enumerate(brand_search): if item in brand: value = value_search[i] print(value[search_type[0]:search_type[1]])
{ "language": "en", "url": "https://stackoverflow.com/questions/73410600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do I compare a char array from a class with another char array using the overload == operator? I have a class called Airplane with a private data member thats a char array. // char array variable in my class char* name{nullptr}; my goal is to compare for equality this variable and an input variable of type const char []. my overload function looks like this: bool Airplane::operator==(const char input_name[]) const{ if (this->name == input_name) { return true; } return false; } By overloading the == operator, I want to be able to do the following: Airplane plane("hello"); if (plane == "hellooo") { // do something } I want to be able to create a class with a text variable like "hello" and then be able to == it to any random text I want to compare equality. Right now my code just doesnt work, it runs and then ends in the console with no errors. basically I need to compare to char arrays, one within the class the overload function is built in, and another given as input by the user. Thank you for any help. A: As @PaulMcKenzie has rightly said, char* is not an array. I suggest using std::string instead of char* as well as in overload as follows: const bool Airplane::operator==(const std::string& str_to_be_compared) const { return this->(whatever variable stores the name of the plane) == str_to_be_compared; }
{ "language": "en", "url": "https://stackoverflow.com/questions/63145955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hiding/Reshowing jQuery Dialogues I'm trying to open a jQuery dialog using AJAX. The content of the dialog is loaded from a querystring and contains server controls inside a form tag. I have a GridView where a link in each row spawns the dialog. The first time, the dialog loads fine, but subsequently I need to open another dialog on the page, then the first dialog will load. I can't open the same dialog subsequent times. Inspecting the DOM in Firebug shows multiple 'containers' at the end of the page. I have a GridView where one column contains a link and an empty div. I've simplified the control IDs because they're mangled by ASP.NET, but this is my code: $('#linkId').click(function() { $('#panelId').dialog({ autoOpen: true, height: 600, width: 680, modal: true, show: 'blind', hide: 'blind', title: 'More Information', open: function () { $(this).load(url).parent().appendTo("form"); }, close(){ // I've also tried using these (not both at the same time) $(this).dialog('destroy').remove();// dialog never opens again $(this).dialog('disable').remove();// dialog never opens again } }); return false; }); }); I've tried adding the included functions to the close event, but I get the same effect. Otherwise, when the dialog eventually opens, everything works perfectly (despite there being multiple dialog containers at the end of the page). A: From the jq dialog api documentation: "If you want to reuse a dialog, the easiest way is to disable the "auto-open" option with: $(foo).dialog({ autoOpen: false }) and open it with $(foo).dialog('open'). To close it, use $(foo).dialog('close'). A more in-depth explanation with a full demo is available on the Nemikor blog"
{ "language": "en", "url": "https://stackoverflow.com/questions/7207058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Providing a common interface to SVN and CVS SVN and CVS are two very different systems that aim to address the same basic issue - source control. They both work in distinct ways, so it's probably difficult to deal with them exactly the same. What I'm wondering is, would it be conceivable to develop a programming library or API that exposes the same interface, but under the hood, can be set up to work with either an SVN or CVS repository? I'm aiming to develop such a library in either .NET or Java (most likely .NET), but I wanted to get some thoughts on how feasible this would be, and if there's a better way to approach the problem. The context of this is: I'm building a web-based service that will involve source control hosting, and I want to support both SVN and CVS so as to serve the largest amount of developers possible. A: Personally I would ignore CVS for a new product. My feeling would be that the enormous extra effort to coerce it into looking like SVN would be better spent on other other stuff. I don't know your market, so I might be wrong, but that's got to be worth thinking about. A: The MSSCCI API does something very similar: http://alinconstantin.homeip.net/webdocs/scc/msscci.htm The MSSCCI tries to make all source controls look the same from the perspective of the IDE. A: viewvc lets you browse svn and cvs repositories. maybe there is an existing product which will already do what you want?
{ "language": "en", "url": "https://stackoverflow.com/questions/313082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }