text
stringlengths
64
81.1k
meta
dict
Q: Phonegap Plugin not working (cordova-plugin-purchase) My first Phonegap App. Everything working well except for plugins. I'm trying to install the cordova-plugin-purchase Plugin. https://github.com/j3k0/cordova-plugin-purchase I've followed the instructions. And when I run "phonegap plugins" in the console it shows the plugin as being installed. According to the documentation, there is suppose to be a "store" object that I can reference. I set up the following code to test if it's working: try { store.register({ id: "my.reverse.item.example", alias: "example name", type: store.CONSUMABLE }); } catch(err) { alert(err); } On my real project, I have the real info in when registering the product, but I can't even get that far. In my TryCatch it returns the following alert: "Can't find variable: store". So it seems that the plugin isn't even installed correct. I'm not to phonegap plugins, so there's probably something very basic that I'm missing. Do I have to include a link to the plugin JS in my index.html file? A: I ended up figuring out the problem. It seems to be that I didn't include the cordova.js file in my index.html. I don't see why I needed to do that since I've read over and over that you don't need to manually add the cordova files to your html files. So the plugin works now and I can receive the store data that I setup using the cordova-plugin-purchase plugin tutorials. Another thing to note once you actually have the plugin installed correctly: The Bundle Identifier in Xcode needs to match the bundle ID for the In App purchases you are trying to connect to.
{ "pile_set_name": "StackExchange" }
Q: Installation Error - D/InstallAppProgress(): Installation error code: -25 I am trying to install my APK, which has been signed by my Production key (the same one I have always used for my app in the Play Store). When I try to install a test build (again, signed with the production key), I can't install over the original (can install if I delete the current production build first). I am worried that when I update my app the next time that this is going to cause issues. I get this error (this is the only relevant line in the logcat, no other output that has anything): D/InstallAppProgress(14669): Installation error code: -25 I have updated the ADT since building with my previous release, and generate the APK for release directly out of the IDE (using the Android Tools right-click menu from the main project). I am not changing permissions or anything. I have changed some internal libraries (using the new Support Lib for instance). A: Check the version number in your Manifest. If the version is less than the one on the device, you will not be able to over-install. You can install it using adb by using the -r flag. See here http://developer.android.com/tools/help/adb.html
{ "pile_set_name": "StackExchange" }
Q: Angular 9 Redirect if query param not provided I have a route that should only be accessible to a user when they click a link from an email and are redirected with a valid query parameter in the url. If the parameter is not provided, I want to redirect to a 404 page not found component, like follows. this.route.queryParams.subscribe(params => { if (params.myParam) { //do something } else { // redirect to 404 } }) The issue I have is that query params is initialized to an empty object in ngOnInit(). I have utilized rjxs to wait until the parameter is accessible like this this.route.queryParamMap.pipe( filter(paramMap => paramMap.has('myParam')), map(paramMap => paramMap.get('myParam')), take(1) ).subscribe(myParam => doSomething(myParam)); But I'm not very well versed in rxjs operators, and now I'm stuck on how to actually redirect if paramMap has finished initializing and the parameter isn't found. A: this is a problem in many apps, as the params and query params are implemented as behavior subjects, get around this by waiting for the NavigationEnd event, where the query params will definitely already be set... const navEnd$ = this.router.events.pipe(filter(e => e instanceof NavigationEnd)); navEnd$.pipe(withLatestFrom(this.route.queryParams)).subscribe( ([navEnd, queryParams]) => { if (queryParams.myParam) { // do the thing } else { // navigate } } )
{ "pile_set_name": "StackExchange" }
Q: foreach not working when I using sort on an array I'm using sort to sort an array alphabetically that's done like this: $Consumer[] = "Norman"; $Consumer[] = "Food"; $Consumer[] = "Clothes"; $Consumer[] = "Chips"; But when I use this code to output the array, it won't work. $cat = sort($Consumer); foreach ($cat as $value) { echo '<option value="'.$value.'">'.$value.'</option>'; } It works if I remove the sort. What am I doing wrong here and how do I set this right? A: sort function returns boolean value so you are overwriting your data. It modifies your $Consumer variable by reference. Try with: sort($Consumer); foreach ($Consumer as $value) { echo '<option value="'.$value.'">'.$value.'</option>'; } A: sort acts by reference As indicated in the docs sort acts by reference and returns a boolean bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) so $cat is a boolean (true or false). The following is a working example of your code: $Consumer[] = "Norman"; $Consumer[] = "Food"; $Consumer[] = "Clothes"; $Consumer[] = "Chips"; sort($Consumer); foreach ($Consumer as $value) { echo '<option value="'.$value.'">'.$value.'</option>'; }
{ "pile_set_name": "StackExchange" }
Q: Using .viewControllers in swift I am trying to send data from one VC1 (it's a collection view) to a tab bar view controller. Here is my prepareForSegue code. override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { var segue = segue.destinationViewController as UITabBarController var whereToGo = segue.viewControllers[0] as PlayerFromRosterViewController var selectedIndex = self.collectionView.indexPathForCell(sender as UICollectionViewCell) whereToGo.selectedIndexPassingForDisplay = selectedIndex?.row } However, I get an error that says "'[AnyObject]?' does not have a member named 'subscript'" on the line where I'm declaring whereToGo. I'm relatively new to swift, so errors are hard for me. Can anyone help me figure out where I'm going wrong? Thanks! A: I think you are confusing tab bar controller and segue. The tab bar controller has a property viewControllers that contains the view controllers associated with the various tab bar items. A segue (UIStoryboardSegue) does not have this property. So why did the compiler not complain? Because you redefined the segue variable that is passed into the method! You can simply fix this by calling your tab bar controller something else. var tabBarController = segue.destinationViewController as UITabBarController var playerController = tabBarController.viewControllers.firstObject as PlayerFromRosterViewController Try to strive for very clear and explicit variable names.
{ "pile_set_name": "StackExchange" }
Q: Can Flash controllers make a card readonly? It is said in this answer here that Some of them have a controller chip that will permanently lock them to read only if they detect a write error, as a preservation measure. Is it possible for a flash controller to permanently lock a SD card into readonly such that it cannot even be formatted? A: Yes! For SD Cards writing 1 to CSD Register's Bit 12 and 13 can enable write protection, permanent or temporary. Regarding the Q&A you have referenced over here. I am not sure or I can confirm but while working with SD Card's I read on some material that when SD card starts to detect that it's life cycle is getting over,It puts itself into Read Only mode so you dont put up your valuables over there and can read all the stuff that you have stored on it. I have just READ, I haven't confirmed it because I don't remember the source neither have I tested it practically. So take it with a pinch of salt.
{ "pile_set_name": "StackExchange" }
Q: Anatomically correct Zerg Overlord Zerg Overlords are flying alien creatures that aid their broods by managing lesser members of the swarm, transporting units within their carapaces, and alerting a hive about any danger they perceive with their heightened senses. They are also quite large: An inprisoned overlord, with a human close to it for size comparison. The overlord's head is to the right (notice glowing eyes). Some images (which I cannot paste here due to copyrights and etc. suggest they may reach sizes at least twice as large as the one in the image. Last but not least, they are able to survive in space for an indefinite amount of time. For this question I'd like to ignore their capacity for interplanetary travel, though. How close to a Zerg Overlord can an anatomically-correct creature evolve to be? P.s.: in the Starcraft series of games, the Zerg are capable of controlling and speeding up their own evolution. I would like to leave that out of the question as well. I am more than satisfied with the most basic Overlord. A: It is difficult to say if a Zerg Overlord can evolve in real life - there is such variety of life on Earth that it certainly seems almost anything is possible. Perhaps an analysis of some close living creatures may yield some results: Portuguese Man-Of-War: This is not a jellyfish found in Australia, this is actually a small series of Polyps / organisms living integrated together in a colony. The 'sail' is an inflated gas bag of carbon monoxide and nitrogen, and can be 30cm long and 15cm high above the water (actually quite large if you see one). They float on water and suspend stinging tentacles for food. Ants, such as the Red Harvester Ant: can communicate with each other using a complex system of pheromones. These airborne/surface chemical compounds can convey quite complex messages allowing the colony to react to new circumstances. Arachnids such as Scorpions: Many arachnid species carry their young on themselves to increase their chances of survival. Their carapaces have coatings and hairs designed for the purpose of carrying large amounts of their young. It may be possible for all the above attributes of creatures (although we are talking about creatures from several different species type) to combine to form your Overlord, however there are some significant obstacles to overcome: Atmospheric floating: Currently no large organisms have achieved this feat. To evolve this must be quite challenging as in over 200 million years on Earth we do not have a large floating creature yet. Size: Insects are limited in size due to oxygen being unable to penetrate their interior as they have no lungs. A circulatory system and lung system is required to convey oxygen throughout. The larger your organism though, the more problems you have, in weight, nutrients and complexity. Space: Space is a hostile environment for which currently no large organisms we know of is existent and able to survive both high levels of radiation and vacuum. However, you never know. Given billions not just hundreds of millions of years of evolution it may be possible that a creature that large, who has those attributes, and survives in space, could evolve. It may be that 'life finds a way...'. A: So the problem with the Zerg when it comes getting something close to there size is that there aren't any know insects that have achieved the size of something that big. I know studies have shown that insects have achieved the size of 2-3 meters or (6.5 - 9.8 feet) in times of Anicent Earth, scary but still not close to a Overlord from StarCraft. An Overlord is Overlords retain the thick outer shell of the Gargantis, and it changed little in the assimilation process. Their exoskeletons are strong enough to resist a lightning strike. Overlords: with the correct growth stimuli, [they] can carry other zerg within hollows in their hides. In this form they become deep-space transports; the importance of their function is underlined by the sheer number of overlords found accompanying zerg forces. As spacefaring creatures, an overlord's carapace pressurizes and seals whenever the creature flies through vacuum. Two species of unidentified symbiotic organisms seem to regulate these functions, though Dominion scientists have been unable to obtain any living samples—these organisms die within seconds if removed from their host overlord. Due to their need to support many different strains of zerg at once, overlords can sometimes exhibit spontaneous adaptive mutations in order to improve their own efficiency. Definition taken from http://starcraft.wikia.com/wiki/Overlord. However exoskeleton animals developed in the ocean and then started to come onto land. So if were trying to get a creature that is close to be anatomically correct of I would suggest the Lion Jelly Fish in terms of size when it would be close. The largest recorded specimen found washed up on the shore of Massachusetts Bay in 1870, had a bell with a diameter of 2.3 metres (7 ft 6 in) and tentacles 37.0 m (121.4 ft) long. Lion's mane jellyfish have been observed below 42°N latitude for some time in the larger bays of the east coast of the United States. So my idea would be to have this jellyfish mutate in the water and develop an exoskeleton from mutation. This works as well since I believe Overlords use helium-filled gas sacs and a weak telekinetic psi-ability for lift and motive power. This helium is generated through an efficient respiratory system distributed throughout the overlord's carapace. The excess helium is stored in thick sacs that contract and expand through rudimentary pulses, allowing overlords to regulate altitude and propulsion at will. They move quite slowly however (if you are looking for it to float that is) Lion's Mane Jellyfish Size Compassion for all Zerg A: Giant tardigrade. https://www.mnn.com/earth-matters/animals/stories/tardigrade-new-species-teach-us https://www.newscientist.com/article/dn14690-water-bears-are-first-animal-to-survive-space-vacuum/ Tiny invertebrates called ‘water bears’ can survive in the vacuum of space, a European Space Agency experiment has shown. They are the first animals known to be able to survive the harsh combination of low pressure and intense radiation found in space. Water bears, also known as tardigrades, are known for their virtual indestructibility on Earth. The creatures can survive intense pressures, huge doses of radiation, and years of being dried out. … After 10 days of exposure to space, the satellite returned to Earth. The tardigrades were retrieved and rehydrated to test how they reacted to the airless conditions in space, as well as ultraviolet radiation from the Sun and charged particles from space called cosmic rays. The vacuum itself seemed to have little effect on the creatures. But ultraviolet radiation, which can damage cellular material and DNA, did take its toll. In one of the two species tested, 68% of specimens that were shielded from higher-energy radiation from the Sun were revived within 30 minutes of being rehydrated. Many of these tardigrades went on to lay eggs that successfully hatched. But only a handful of animals survived full exposure to the Sun’s UV light, which is more than 1000 times stronger in space than on the Earth’s surface. The captive creature there has a very tardigradoid build, I think. 8 legs? Ask the girl on the ladder; she has a better angle. In any case, the spaceworthiness is the highest bar and tardigrades can do that. Your creatures can be scaled up tardigrades.
{ "pile_set_name": "StackExchange" }
Q: Unit testing where a dependency has a static configuration method C# I have a class that inherits a simple logging interface. One of the implementations of this interface uses log4net. Log4net has a static configuration method that is required to be called in you are using XML configuration. The line is: log4net.Config.XmlConfigurator.Configure(); Documentation usually states to put this in a global event, but I want to keep all log4net code encapsulated into this one class. So I simply used static variables to track if log4net has been configured, and if it hasn't I call this method: //This is static as I only ever want one instance private static log4net.ILog _logger; private static bool _isConfigured; public Log4NetLogger() { if(!_isConfigured) { //This is needed to initialise the Log4Net logger log4net.Config.XmlConfigurator.Configure(); _isConfigured = true; _logger = log4net.LogManager.GetLogger(_defaultLogger); } } The problem is I have no idea how to test this. I'd like to be able to test that the Configure() method is only ever called once. The static variables and the static method combined with the logic being part of the constructor makes this tricky. It feels like it's my code that's poor, is there a way that I can write this code so that the configuration call is only ever called once, and then, how do I test it? A: You could use a C# "Static Constructor" to achieve your objective. //This is static as I only ever want one instance private static log4net.ILog _logger; static Log4NetLogger() { //This is needed to initialise the Log4Net logger log4net.Config.XmlConfigurator.Configure(); _logger = log4net.LogManager.GetLogger(_defaultLogger); } Since, by the spec, it runs at most once (per App Domain), you shouldn't need to test it. You would have to, however, handle exceptions more carefully since errors in static constructors are harder to understand.
{ "pile_set_name": "StackExchange" }
Q: No new line before form First my code: <?php echo 'Hello <FORM ACTION="uebung3.php" METHOD="post"> <P> <LABEL FOR="vorname">Vorname: </LABEL> <INPUT TYPE="text" NAME="vorname"> <LABEL FOR="nachname">Nachname: </LABEL> <INPUT TYPE="textarea" NAME="nachname"> <LABEL FOR="email">E-Mail: </LABEL> <INPUT TYPE="text" NAME="email"> <INPUT TYPE="radio" NAME="geschlecht" VALUE="Maskulin"> Maskulin <INPUT TYPE="checkbox" NAME="geschlecht" VALUE="Feminin"> Feminin <input type="password" for="pw" NAME="PW"> <INPUT TYPE="submit" VALUE="Absenden"> <INPUT TYPE="reset" VALUE="Zurücksetzen"> </P> </FORM> '; ?> So if i run that on my xampp-Server, it shows a "Hello" and the Form in a new line. What must I do that all this is written in one line? Thanks A: You need to remove the <p> element and display the form inline. <?php echo 'Hello <FORM ACTION="uebung3.php" METHOD="post" style="display:inline"> <LABEL FOR="vorname">Vorname: </LABEL> <INPUT TYPE="text" NAME="vorname"> <LABEL FOR="nachname">Nachname: </LABEL> <INPUT TYPE="textarea" NAME="nachname"> <LABEL FOR="email">E-Mail: </LABEL> <INPUT TYPE="text" NAME="email"> <INPUT TYPE="radio" NAME="geschlecht" VALUE="Maskulin"> Maskulin <INPUT TYPE="checkbox" NAME="geschlecht" VALUE="Feminin"> Feminin <input type="password" for="pw" NAME="PW"> <INPUT TYPE="submit" VALUE="Absenden"> <INPUT TYPE="reset" VALUE="Zurücksetzen"> </FORM> '; ?>
{ "pile_set_name": "StackExchange" }
Q: How to convert a php page in to jpeg file and to download I am trying to convert a web page into jpeg image file. i had used following codes. <?php //put your html code here $html_code = " <html> <head> <title>My test title</title> <style> body { font-family:verdana; font-size:11px; color:black } </style> </head> <body> this is the body </body> </html>"; // Create the image $img = imagecreate("300", "600"); imagecolorallocate($img,0,0,0); $c = imagecolorallocate($img,70,70,70); imageline($img,0,0,300,600,$c); imageline($img,300,0,0,600,$c); $white = imagecolorallocate($img, 255, 255, 255); imagettftext($img, 9, 0, 1, 1, $white, "VERDANA.TTF", $html_code); // Display the image header("Content-type: image/jpeg"); imagejpeg($img); ?> Question: Is there any library to convert html page into image ? A: You will need an HTML renderer for this. There exists a few such renderers, but most of them requires an X server on your web server, so check out Xvfb to run a framebuffer device without a screen.
{ "pile_set_name": "StackExchange" }
Q: Assert string array member content In this test, the required assertion is that if a member of the obtained string array has a value which is similar to something. For example: Say the obtained string array is string[] obtainedArr = new string("c:\programfiles", "d:\morefiles", "e:\some"); Do we have something in the lines of: Assert.That(obtainedArr, Has.Member.Which.Is.String.Containing("d:"), "D: location not obtained"); Or do we have a better way to achieving this? A: Assert.True(obtainedArr.Any(s => s.Contains("d:")), "D: location not obtained"); Notes: by default string comparison is case-sensitive, so searching for D: will fail for your sample input. Also if you are looking for sub-path, then maybe StartsWith is more appropriate check, than Contains Assert.That(obtainedArr.Any(s => s.StartsWith("d:", StringComparison.InvariantCultureIgnoreCase)); Of course, this code is not very readable, so I would create (extension) method to check if given path is subpath of some other path.
{ "pile_set_name": "StackExchange" }
Q: Error Loading QGIS 3 Couldn't load plugin 'processing' Every time I load QGIS 3.4 I get the below error ImportError: dlopen(/Library/Frameworks/SQLite3.framework/Versions/E/Python/3.6/sqlite3/_sqlite3.cpython-36m-darwin.so, 2): Library not loaded: /Library/Frameworks/SQLite3.framework/Versions/D/SQLite3 Referenced from: /Library/Frameworks/SQLite3.framework/Versions/E/Python/3.6/sqlite3/_sqlite3.cpython-36m-darwin.so Reason: image not found Traceback (most recent call last): File "/Applications/QGIS3.app/Contents/MacOS/../Resources/python/qgis/utils.py", line 309, in loadPlugin __import__(packageName) File "/Applications/QGIS3.app/Contents/MacOS/../Resources/python/qgis/utils.py", line 672, in _import mod = _builtin_import(name, globals, locals, fromlist, level) File "/Applications/QGIS3.app/Contents/MacOS/../Resources/python/plugins/processing/__init__.py", line 29, in from processing.tools.general import * # NOQA File "/Applications/QGIS3.app/Contents/MacOS/../Resources/python/qgis/utils.py", line 672, in _import mod = _builtin_import(name, globals, locals, fromlist, level) File "/Applications/QGIS3.app/Contents/MacOS/../Resources/python/plugins/processing/tools/general.py", line 39, in from processing.core.Processing import Processing File "/Applications/QGIS3.app/Contents/MacOS/../Resources/python/qgis/utils.py", line 672, in _import mod = _builtin_import(name, globals, locals, fromlist, level) File "/Applications/QGIS3.app/Contents/MacOS/../Resources/python/plugins/processing/core/Processing.py", line 58, in from processing.algs.qgis.QgisAlgorithmProvider import QgisAlgorithmProvider # NOQA File "/Applications/QGIS3.app/Contents/MacOS/../Resources/python/qgis/utils.py", line 672, in _import mod = _builtin_import(name, globals, locals, fromlist, level) File "/Applications/QGIS3.app/Contents/MacOS/../Resources/python/plugins/processing/algs/qgis/QgisAlgorithmProvider.py", line 84, in from .ImportIntoSpatialite import ImportIntoSpatialite File "/Applications/QGIS3.app/Contents/MacOS/../Resources/python/qgis/utils.py", line 672, in _import mod = _builtin_import(name, globals, locals, fromlist, level) File "/Applications/QGIS3.app/Contents/MacOS/../Resources/python/plugins/processing/algs/qgis/ImportIntoSpatialite.py", line 42, in from processing.tools import spatialite File "/Applications/QGIS3.app/Contents/MacOS/../Resources/python/qgis/utils.py", line 672, in _import mod = _builtin_import(name, globals, locals, fromlist, level) File "/Applications/QGIS3.app/Contents/MacOS/../Resources/python/plugins/processing/tools/spatialite.py", line 29, in import sqlite3 as sqlite File "/Applications/QGIS3.app/Contents/MacOS/../Resources/python/qgis/utils.py", line 672, in _import mod = _builtin_import(name, globals, locals, fromlist, level) File "/Library/Frameworks/SQLite3.framework/Versions/E/Python/3.6/sqlite3/__init__.py", line 23, in from sqlite3.dbapi2 import * File "/Applications/QGIS3.app/Contents/MacOS/../Resources/python/qgis/utils.py", line 672, in _import mod = _builtin_import(name, globals, locals, fromlist, level) File "/Library/Frameworks/SQLite3.framework/Versions/E/Python/3.6/sqlite3/dbapi2.py", line 27, in from sqlite3._sqlite3 import * File "/Applications/QGIS3.app/Contents/MacOS/../Resources/python/qgis/utils.py", line 672, in _import mod = _builtin_import(name, globals, locals, fromlist, level) ImportError: dlopen(/Library/Frameworks/SQLite3.framework/Versions/E/Python/3.6/sqlite3/_sqlite3.cpython-36m-darwin.so, 2): Library not loaded: /Library/Frameworks/SQLite3.framework/Versions/D/SQLite3 Referenced from: /Library/Frameworks/SQLite3.framework/Versions/E/Python/3.6/sqlite3/_sqlite3.cpython-36m-darwin.so Reason: image not found Python version: 3.6.8 (v3.6.8:3c6b436a57, Dec 24 2018, 02:04:31) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] QGIS version: 3.4.5-Madeira Madeira, exported Python Path: /Applications/QGIS3.app/Contents/MacOS/../Resources/python /Users/ABC/Library/Application Support/QGIS/QGIS3/profiles/default/python /Users/ABC/Library/Application Support/QGIS/QGIS3/profiles/default/python/plugins /Applications/QGIS3.app/Contents/MacOS/../Resources/python/plugins /Library/Frameworks/SQLite3.framework/Versions/E/Python/3.6 /Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6 /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages /Users/ABC/Library/Application Support/QGIS/QGIS3/profiles/default/python A: I Solved this by reinstalling GDAL from the source. After that I never got this error.
{ "pile_set_name": "StackExchange" }
Q: Constraining a shiny app input based on another input I have a basic shiny app that evaluates A + B: library(shiny) ui <- fluidPage( numericInput(inputId = "A", label = "A", value = 5, step = 1), sliderInput(inputId = "B", label = "B", min = 0, max = 10, value = 5), textOutput(outputId = "value") ) server <- function(input, output) { output$value <- renderText(paste0("A + B = ", input$A + input$B)) } shinyApp(ui = ui, server = server) A is a numericInput value and B is a sliderInput value. I want to constrain my app so that the maximum input value for B is always 2 * A. I, therefore, must change the hardcoded max = in sliderInput to something that can be dynamic. How can I accomplish this? Thanks A: You can call updateSliderInput to change the maximum value for B from within an observe which will be triggered whenever A changes: library(shiny) ui <- fluidPage( numericInput(inputId = "A", label = "A", value = 5, step = 1), sliderInput(inputId = "B", label = "B", min = 0, max = 10, value = 5), textOutput(outputId = "value") ) # Notice the session argument to be passed to updateSliderInput server <- function(input, output, session) { output$value <- renderText(paste0("A + B = ", input$A + input$B)) observe(updateSliderInput(session, "B", max = input$A*2)) } shinyApp(ui = ui, server = server) A: You are looking for renderUI() library(shiny) ui <- fluidPage( numericInput(inputId = "A", label = "A", value = 5, step = 1), uiOutput("slider"), textOutput(outputId = "value") ) server <- function(input, output) { output$value <- renderText(paste0("A + B = ", input$A + input$B)) output$slider <- renderUI({ sliderInput(inputId = "B", label = "B", min = 0, max = 2*input$A, value = 5) }) } shinyApp(ui = ui, server = server)
{ "pile_set_name": "StackExchange" }
Q: C# .NET Core IoT Error for ARM embedded board : Unhandled exception. System.IO.IOException: Device or resource busy I want to use .NET core IoT library in order to run C# code for my SAMA5D27 SOM1 EK1 ARM embedded board. .NET core IoT github I have build this .NET core project composed from project.cs source file : using System; using System.Device.Gpio; using System.Threading; namespace led_blink { class Program { static void Main(string[] args) { var pin = 81; var lightTimeInMilliseconds = 1000; var dimTimeInMilliseconds = 200; Console.WriteLine($"Let's blink an LED!"); using (GpioController controller = new GpioController()) { controller.OpenPin(pin, PinMode.Output); Console.WriteLine($"GPIO pin enabled for use: {pin}"); Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs eventArgs) => { controller.Dispose(); }; while (true) { Console.WriteLine($"Light for {lightTimeInMilliseconds}ms"); controller.Write(pin, PinValue.High); Thread.Sleep(lightTimeInMilliseconds); Console.WriteLine($"Dim for {dimTimeInMilliseconds}ms"); controller.Write(pin, PinValue.Low); Thread.Sleep(dimTimeInMilliseconds); } } } } } And this is .csproj file : <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp3.1</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Iot.Device.Bindings" Version="1.0.0" /> <PackageReference Include="System.Device.Gpio" Version="1.0.0" /> </ItemGroup> </Project> As you can see, the code is used for blinking Led which is situated on PIN 81 which corresponds to PortC pin 17 on my board. I build the project in order to use on arm-linux board. First, to check if the pin is working well, I used libgpiod library and I turned on the led of pin81 using gpioset gpiochip0 81=1 and it is working well. Furthermore, I have checked my GPIOs using gpioinfo command and this is the result of the desired pin : line 81: "PC17" unused input active-high But when I try to run the C# code, it fails with this output message : Let's blink an LED! Unhandled exception. System.IO.IOException: Device or resource busy at System.IO.FileStream.WriteNative(ReadOnlySpan`1 source) at System.IO.FileStream.FlushWriteBuffer() at System.IO.FileStream.FlushInternalBuffer() at System.IO.FileStream.Flush(Boolean flushToDisk) at System.IO.FileStream.Flush() at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder) at System.IO.StreamWriter.Dispose(Boolean disposing) at System.IO.TextWriter.Dispose() at System.IO.File.WriteAllText(String path, String contents) at System.Device.Gpio.Drivers.SysFsDriver.OpenPin(Int32 pinNumber) at System.Device.Gpio.GpioController.OpenPin(Int32 pinNumber) at System.Device.Gpio.GpioController.OpenPin(Int32 pinNumber, PinMode mode) at led_blink.Program.Main(String[] args) in /home/ubuntu/netcore/Program.cs:line 23 Aborted This is my board device tree : device_tree PS : I have removed ISC node which is using PC17 GPIO from device tree in order to free the pin ISC_DeviceTree_node Why my code can't run ? any help please ! A: Finaly i found the solution. You must use LibGpioD driver instead of SysFs interface in your Linux platform and your C# code.
{ "pile_set_name": "StackExchange" }
Q: How to check for numbers less than one and non-numbers in JavaScript? I am new to JavaScript. For one of my assignments, I have to write JavaScript code for my class that determines and displays the tax amount on a user entered income. So far my code looks like this: <!DOCTYPE html> <html> <head> <title>JavaScript Tax Assignment</title> </head> <body> <script> //declare variables and collect amount enter. // Assign amount entered to var amountEntered. var amountEntered = window.prompt("Enter an income amount in dollars"); var x = parseInt(amountEntered); var untaxableIncome = 12000; var taxBracketOne = 36000; var taxBracketTwo = 90000; var bracketOneTax = 0.15; var bracketTwoTax = 0.25; var total; //determine if the number is less than one if (x < 1) { alert("Enter a whole number greater than 0"); } // else if (x == NaN) { alert("Enter a whole number greater than 0"); } else if (x <= untaxableIncome) { alert("You will not be charged taxes on your income"); } else if (x >untaxableIncome && x <= taxBracketOne) { total = amountEntered * bracketOneTax; document.write("You will need to pay " + total + " on your " + amountEntered + " income.") } else if (x > taxBracketOne && x <= taxBracketTwo) { total = amountEntered * bracketTwoTax; document.write("You will need to pay " + total + " on your " + amountEntered + " income.") } else (x > taxBracketTwo) { document.write("I do not have the data to calculate the tax on this income.") } </script> </body> </html> The calculations work well, the only problem I'm having is that when I enter .5 or a letter, I do not get the alert("Enter a whole number greater than 0"); What am I doing wrong? A: You're using parseInt(), which can only parse whole numbers, not fractions. If you type .5, it returns NaN. But you can't test this with if (x == NaN). NaN is a special number that's never equal to anything, not even itself. You have to use if (isNaN(x)). If you want to tell if a number is a fraction between 0 and 1, you need to use parseFloat() instead of parseInt(). And if you want to tell whether the number is a whole number, you can do: if (x == Math.floor(x)) Math.floor() takes a number that might have a fraction after the decimal point and returns the highest integer less than or equal to it. If the number is already an integer, these will obviously be the same.
{ "pile_set_name": "StackExchange" }
Q: Class to filter URLs for Spring Boot does not build This is a Spring Boot Java project using Maven. If I remove the @Configuration annotation from WebConfig, the application builds but the class seems to be ignored. If I include it, the app fails with this message: Error starting Tomcat context. Exception: java.lang.ClassCastException. Message: org.springframework.boot.web.servlet.DispatcherType cannot be cast to javax.servlet.DispatcherType. Application run failed. How can I properly set up Spring Boot to use filters? Here is the main app class: import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication public class GetJobDetailsApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(GetJobDetailsApplication.class); } public static void main(String[] args) { SpringApplication.run(GetJobDetailsApplication.class, args); } } Here is the Controller: import java.util.Map; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MainRESTController { // inject via application.properties @Value("${welcome.message:test}") private String message = "Hello World"; @RequestMapping("/") public String welcome(Map<String, Object> model) { model.put("message", this.message); return "welcome"; } } Here is the WebConfig where I set up the filters: import org.owasp.filters.ClickjackFilter; import org.springframework.boot.web.servlet.DispatcherType; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.filter.ShallowEtagHeaderFilter; import java.util.EnumSet; @Configuration public class WebConfig { @Bean public FilterRegistrationBean clickjackFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(clickjackFilter()); registration.addUrlPatterns("/"); registration.addInitParameter("paramName", "paramValue"); registration.setName("clickjackFilter"); registration.setOrder(1); return registration; } @Bean(name = "clickjackFilter") public ClickjackFilter clickjackFilter() { return new ClickjackFilter(); } @Bean public FilterRegistrationBean shallowEtagHeaderFilter() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new ShallowEtagHeaderFilter()); registration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class)); registration.addUrlPatterns("/"); return registration; } } And here is the clickjackFilter class: import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; public class ClickjackFilter implements Filter { private String mode = "DENY"; /** * Add X-FRAME-OPTIONS response header to tell IE8 (and any other browsers who * decide to implement) not to display this content in a frame. For details, please * refer to http://blogs.msdn.com/sdl/archive/2009/02/05/clickjacking-defense-in-ie8.aspx. */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse) response; res.addHeader("X-FRAME-OPTIONS", mode); chain.doFilter(request, response); } public void destroy() { } public void init(FilterConfig filterConfig) { String configMode = filterConfig.getInitParameter("mode"); if (configMode != null) { mode = configMode; } } } Dependencies in pom.xml file: <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>javax.el</groupId> <artifactId>javax.el-api</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> </dependency> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-jaxrs</artifactId> <version>1.5.9</version> </dependency> <dependency> <groupId>org.apache.tiles</groupId> <artifactId>tiles-core</artifactId> <version>${apachetiles.version}</version> </dependency> <dependency> <groupId>org.apache.tiles</groupId> <artifactId>tiles-jsp</artifactId> <version>${apachetiles.version}</version> </dependency> <dependency> <groupId>org.apache.tiles</groupId> <artifactId>tiles-extras</artifactId> <version>${apachetiles.version}</version> </dependency> <dependency> <groupId>org.apache.tiles</groupId> <artifactId>tiles-api</artifactId> <version>${apachetiles.version}</version> </dependency> <dependency> <groupId>org.apache.tiles</groupId> <artifactId>tiles-servlet</artifactId> <version>${apachetiles.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot</artifactId> <version>2.1.4.RELEASE</version> </dependency> <!-- Tomcat embedded container--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <!-- JSTL for JSP --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <!-- Need this to compile JSP --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> <!-- Need this to compile JSP, tomcat-embed-jasper version is not working --> <dependency> <groupId>org.eclipse.jdt.core.compiler</groupId> <artifactId>ecj</artifactId> <version>4.6.1</version> <scope>provided</scope> </dependency> <!-- Optional, test for static content, bootstrap CSS--> <dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>3.3.7</version> </dependency> </dependencies> A: On closer look on your stacktrace, can you try setting the DispatcherType as java.lang.Object java.lang.Enum<DispatcherType> javax.servlet.DispatcherType since the FilterRegistrationBean expects a parameter of type javax.servlet.DispatcherType for the set setDispatcherTypes() Or you can directly register the filter beans by using the annotations like : @Order(Ordered.LOWEST_PRECEDENCE -1) @Component public class ABCFilter implements Filter { ------ } In spring boot normally you configure the filters like : @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Autowired HandlerInterceptor customInjectedInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(...) ... registry.addInterceptor(customInjectedInterceptor).addPathPatterns("/**"); } } or if you are using Spring 5x then : @Configuration public WebConfig implements WebMvcConfigurer { // ... } By doing this we are essentially customizing the spring boot auto configuration beans , so that springboot can still auto configure all of the other things.If you are using springboot consider removing @EnableWebMvc and using springboot's autoconfiguration.
{ "pile_set_name": "StackExchange" }
Q: update a select query in oracle DB I have 5 tables in a DB like this (script below):: DB SCRIPT CREATE TABLE EQUIPE ( code_equipe char(3) primary key, nom varchar(30), directeur varchar(30)); CREATE TABLE PAYS ( code_pays varchar(3) primary key, nom varchar(20)); CREATE TABLE COUREUR ( num_dossart number(3) primary key, code_equipe char(3), nom varchar(30), code_pays varchar(3)); CREATE TABLE ETAPE ( num_etape number(1) primary key, date_etape date, kms number(3), ville_depart varchar(20), ville_arrivee varchar(20)); CREATE TABLE TEMPS ( num_dossart number(3), num_etape number(1), temps_realise number(6), primary key(num_dossart,num_etape)); ALTER table COUREUR add CONSTRAINT FK_avoir_code_equipe FOREIGN KEY (code_equipe) REFERENCES EQUIPE(code_equipe); ALTER table COUREUR add CONSTRAINT FK_avoir_code_pays FOREIGN KEY (code_pays) REFERENCES PAYS(code_pays); ALTER table TEMPS add CONSTRAINT FK_avoir_num_dossart FOREIGN KEY (num_dossart) REFERENCES COUREUR(num_dossart); ALTER table TEMPS add CONSTRAINT FK_avoir_num_etape FOREIGN KEY (num_etape) REFERENCES ETAPE(num_etape); and my query select num_etape,max(temps_realise) from TEMPS group by num_etape gave this result and i want to update it to give result like this this is A: I have solved my question thanks guys select num_dossart,nom,num_etape,dernier from COUREUR C, (select num_etape ,max(temps_realise) as dernier from TEMPS GROUP BY num_etape) T where num_dossart = (select num_dossart from TEMPS where temps_realise = dernier )
{ "pile_set_name": "StackExchange" }
Q: Finding the MLE of pareto dist., and trouble interpreting $\prod$ notation properly. I am generally having trouble understanding how to use product notation when calculating Maximum Likelihood Estimators. The example bellow is from a random sample $X_1,...,X_n$. Find the MLE of $\theta$. $f(x, x_0, \theta)=\theta x_{0}^{\theta} x^{-(1+\theta)}, \ for \ x>x_0, \ \theta > 1, \ \& \ x_0$ is known. step one $ L(x, \theta) = \prod_{i=1}^{n} \theta x_{0}^{\theta} x^{-(1+\theta)}$ step two $ L(x, \theta) = \theta^{n} x_{0}^{n \theta} \prod_{i=1}^{n} x_{i}^{-(1+\theta)}$ step three $ \ln [L(x, \theta)] = n \ln({\theta}) + n \theta \ln({x_{0}}) - (1+\theta)\sum_{i=1}^{n} \ln({x_i})$ step four $ \dfrac{\partial}{\partial \theta} \ln [L(x, \theta)] = \dfrac{n}{\theta}+ n \ln{x_0} -\sum^{n}_{i=1} \ln{x_i}$ step five (set to 0, solve for $\theta$) $\hat{\theta}= \dfrac {n}{\sum \ln {x_i}- n \ln{x_0}}$ The answer given is $\hat{\theta}=\dfrac{n}{\sum\ln(\frac{x_{i}}{x_0})}$ On step two, I am not sure if I correctly distributed the product, specifically $\prod_{i=1}^{n} x_{i}^{-(1+\theta)}$. On step three, is $-(1+\theta)\sum_{i=1}^{n} \ln({x_i})$ the correct way to take the natural log of the product? Finally, is my step five answer the same as the given answer given a little bit of algebra? Thanks so much for your time and help! A: Everything looks right except that at step three it should be $1+\theta$ instead of $1-\theta$.
{ "pile_set_name": "StackExchange" }
Q: Remove brackets from string array when printing as csv using pandas I want to write a .csv file. One of the columns is "words". Each category of words is in a row, and the cell "words" has a list of words that I read as: words = [] for i in range(len(category)): r = requests.post(base_url+'/'+url[i]) if r.ok: data = r.content.decode('utf8') words.append(pd.Series.tolist((pd.read_csv(io.StringIO(data), squeeze=True)).T)) url_f = [base_url + s for s in url] df = pd.DataFrame({'category': category, 'url': url_f, 'words': words}) df.to_csv("lm_words.csv") the list of words is downloaded as r. The table looks something like this: index | category | url | words 0. | cat1. | www.| [word1, word2, word3] And I am trying to get rid of the brackets in [ word1, word2, word3 ]. I have this written in R and it doesn't print the brackets in the .csv Edit1: Format A: Use str.join Ex: df = pd.DataFrame({'category': category, 'url': url_f, 'words': words}) df["words"] = df["words"].apply(", ".join)
{ "pile_set_name": "StackExchange" }
Q: saving a folder from being destroyed after push on heroku I have an app that lets users upload documents. The app saves the documents to a folder on the server, say users_documents. The app is hosted on Heroku. When I do a git push heroku master the new app is deployed but all the files in users_documents are deleted, is there a way to tell git (or heroku) not to rewrite that folder? A: You should probably be storing your data in something more permanent than Heroku's ephemeral file storage. When the dyno is restarted your data disappears, and even if you have no intentions of restarting your dyno, Heroku maintenance may start new ones as hardware needs maintenance.
{ "pile_set_name": "StackExchange" }
Q: How to write this Subscript for Lagrangian Minimization Equation in Beamer So I want an \alpha below the word 'minimise' as in this paper in equation 5 and 6. A: Welcome to TeX.SE! You could use \documentclass{beamer} \usepackage{amsmath} \DeclareMathOperator*{\minimize}{minimize} \begin{document} \begin{frame}[t] \frametitle{A slide} \[\minimize_{\{\alpha\}} \|\boldsymbol{\mathrm{i}}-\boldsymbol{\Phi\mathcal{D}\alpha}\|_2 +\lambda \|\boldsymbol{\alpha}\|_1\] or $\displaystyle\minimize_{\{\alpha\}} \|\boldsymbol{\mathrm{i}}-\boldsymbol{\Phi\mathcal{D}\alpha}\|_2 +\lambda \|\boldsymbol{\alpha}\|_1$ \end{frame} \end{document} Notice that none of this is specific to beamer.
{ "pile_set_name": "StackExchange" }
Q: Get max of two entries query Query: select machinename, StatusCode, size from machine where MachineID In( '33','22') and StatusCode = 166 ORDER BY size DESC Result: machinename StatusCode size ----------- ---------- ---- test1 166 50 test1 166 25 test2 166 75 test2 166 48 Requirement: I need to display only one entry for each machine. I have to do this by taking the max size value between the two entries as shown above. like for test1 i have two sizes 50 and 25 I have to show the row which has 50 and ignore row which has 25. Thanks Desired Result: machinename StatusCode size ----------- ---------- ---- test1 166 50 test2 166 75 A: This will work, but you won't be able to order by starttime select machinename, StatusCode, max(size) as size from machine where MachineID In( '33','22') and StatusCode = 166 group by machinename, StatusCode order by max(size) DESC A: If you wanted to order by StartTime you would have to use ROW_NUMBER so that you could select the starttime field: SELECT machinename, StatusCode, size FROM ( SELECT machinename, StatusCode, StartTime size, ROW_NUMBER() OVER (PARTITION BY MachineID ORDER BY size DESC) AS rn FROM machine WHERE MachineID IN ('33','22') AND StatusCode = 166 ) T1 WHERE rn = 1 ORDER BY StartTime DESC But if you want to order by size, it's easier: SELECT machinename, StatusCode, MAX(size) AS size FROM machine WHERE MachineID IN ('33','22') AND StatusCode = 166 GROUP BY MachineID ORDER BY MAX(size) DESC
{ "pile_set_name": "StackExchange" }
Q: How to Animate Addition or Removal of Android ListView Rows In iOS, there is a very easy and powerful facility to animate the addition and removal of UITableView rows, here's a clip from a youtube video showing the default animation. Note how the surrounding rows collapse onto the deleted row. This animation helps users keep track of what changed in a list and where in the list they were looking at when the data changed. Since I've been developing on Android I've found no equivalent facility to animate individual rows in a TableView. Calling notifyDataSetChanged() on my Adapter causes the ListView to immediately update its content with new information. I'd like to show a simple animation of a new row pushing in or sliding out when the data changes, but I can't find any documented way to do this. It looks like LayoutAnimationController might hold a key to getting this to work, but when I set a LayoutAnimationController on my ListView (similar to ApiDemo's LayoutAnimation2) and remove elements from my adapter after the list has displayed, the elements disappear immediately instead of getting animated out. I've also tried things like the following to animate an individual item when it is removed: @Override protected void onListItemClick(ListView l, View v, final int position, long id) { Animation animation = new ScaleAnimation(1, 1, 1, 0); animation.setDuration(100); getListView().getChildAt(position).startAnimation(animation); l.postDelayed(new Runnable() { public void run() { mStringList.remove(position); mAdapter.notifyDataSetChanged(); } }, 100); } However, the rows surrounding the animated row don't move position until they jump to their new positions when notifyDataSetChanged() is called. It appears ListView doesn't update its layout once its elements have been placed. While writing my own implementation/fork of ListView has crossed my mind, this seems like something that shouldn't be so difficult. Thanks! A: Animation anim = AnimationUtils.loadAnimation( GoTransitApp.this, android.R.anim.slide_out_right ); anim.setDuration(500); listView.getChildAt(index).startAnimation(anim ); new Handler().postDelayed(new Runnable() { public void run() { FavouritesManager.getInstance().remove( FavouritesManager.getInstance().getTripManagerAtIndex(index) ); populateList(); adapter.notifyDataSetChanged(); } }, anim.getDuration()); for top-to-down animation use : <set xmlns:android="http://schemas.android.com/apk/res/android"> <translate android:fromYDelta="20%p" android:toYDelta="-20" android:duration="@android:integer/config_mediumAnimTime"/> <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="@android:integer/config_mediumAnimTime" /> </set> A: The RecyclerView takes care of adding, removing, and re-ordering animations! This simple AndroidStudio project features a RecyclerView. take a look at the commits: commit of the classic Hello World Android app commit, adding a RecyclerView to the project (content not dynamic) commit, adding functionality to modify content of RecyclerView at runtime (but no animations) and finally...commit adding animations to the RecyclerView A: Take a look at the Google solution. Here is a deletion method only. ListViewRemovalAnimation project code and Video demonstration It needs Android 4.1+ (API 16). But we have 2014 outside.
{ "pile_set_name": "StackExchange" }
Q: Iterative function on set Is there a name for the procedure/function $ S = f(A) $ such that: $$ S = \{ x : x \in A \} \cup \{ f(x) : x \in S \} $$ Basically take a set, apply a function to all it's elements, if you get any new elements, apply the function to those elements again etc. A: This is an example of a closure operation. Coincidentally, there was a question asked earlier today about such things. Given a set $S$ and a function $f : S \to S$, the closure of a subset $A \subseteq X$ is a subset $\mathrm{cl}_f(A) \subseteq S$ such that the following three conditions hold: $A \subseteq \mathrm{cl}_f(A)$; For all $x \in S$, if $x \in \mathrm{cl}_f(A)$, then $f(x) \in \mathrm{cl}_f(A)$; and If $C \subseteq S$ is any subset such that $A \subseteq C$ and $f(x) \in C$ for all $x \in C$, then $\mathrm{cl}_f(A) \subseteq C$. The first two conditions say that $\mathrm{cl}_f(A)$ contains $A$ and contains $f$ of all of its elements; the third condition says that $\mathrm{cl}_f(A)$ is the smallest such subset.
{ "pile_set_name": "StackExchange" }
Q: How to get string base64 in a variable? This is my code: but not get the string base64 in my variable. I need the string base64 in this variable var base64. I have seen other issues but none of them meets what I need <input type:file multiple id="files"> <script> function listarchivos(){ var base64; //in this variable i need the base64 var selectedFile = document.getElementById("files").files; var fileToLoad = selectedFile[0]; getBase64(fileToLoad).then( data => alert(data) ); } //This is my function for get base64, but not return the string base64 function getBase64(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => resolve(reader.result); reader.onerror = error => reject(error); return Promise.resolve(reader.result) }); } </script> the function that I have already complies with obtaining the base64 string of the file that is given as a parameter, what I can not do is get access to that string to assign it to a variable and use it. I just need you to tell me how I can get access to that base64 chain, I just need it in a variable that can be handled as desired. I have already tried the following options var base64 = getBase64(fileToLoad).then( data => alert(data) ); //this not works getBase64(fileToLoad).then( data => base64 = data ); //This not works getBase64(fileToLoad).then( data => return{data} );//this not works A: Since Promise makes the function asynchronous, the following code would start running getBase64() and continuously executing console.log(base64) which is not defined yet. function listarchivos() { base64; //in this variable i need the base64 var selectedFile = document.getElementById("files").files; var fileToLoad = selectedFile[0]; getBase64(fileToLoad).then( data => { base64 = data; } ); console.log(base64) // undefined } So you should await for getBase64() be done or use a callback like the followings. await example 1 async function listarchivos() { var base64; //in this variable i need the base64 var selectedFile = document.getElementById("files").files; var fileToLoad = selectedFile[0]; await getBase64(fileToLoad).then( data => { alert(data); base64 = data; } ); console.log(base64) } //This is my function for get base64, but not return the string base64 function getBase64(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => resolve(reader.result); reader.onerror = error => reject(error); return Promise.resolve(reader.result) }); } $('#files').on('change', listarchivos) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="file" multiple id="files"> await example 2 async function listarchivos() { var base64; //in this variable i need the base64 var selectedFile = document.getElementById("files").files; var fileToLoad = selectedFile[0]; base64 = await getBase64(fileToLoad).then( data => { return data; } ); console.log(base64) } //This is my function for get base64, but not return the string base64 function getBase64(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => resolve(reader.result); reader.onerror = error => reject(error); return Promise.resolve(reader.result) }); } $('#files').on('change', listarchivos) function DoSomething() { console.log(base64) } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="file" multiple id="files"> callback var base64; function listarchivos() { var selectedFile = document.getElementById("files").files; var fileToLoad = selectedFile[0]; getBase64(fileToLoad).then( data => { base64 = data; DoSomething() } ); } //This is my function for get base64, but not return the string base64 function getBase64(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => resolve(reader.result); reader.onerror = error => reject(error); return Promise.resolve(reader.result) }); } $('#files').on('change', listarchivos) function DoSomething() { console.log(base64) } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="file" multiple id="files">
{ "pile_set_name": "StackExchange" }
Q: What are some advanced uses for Block? I read the answers to this question (What are the use cases for different scoping constructs?) and this one (Condition, Block, Module - which way is the most memory and computationally efficient?). According to those, Block is safer (if something aborts, it restores the values) and faster (perhaps something to do with the low-level pointer redirection that I believe it uses) than Module, but less memory-efficient if the function is defined a certain way. That being said, (1) why does Leonid say that Module is "safer" when it doesn't have as-good garbage collection, and (2) if I am to use Module for most of the time, what are some of the "advanced" uses which require Block? A: Safety Module is safer than Block because: It is a lexical scoping construct, which means that variable bindings are only tied to a specific piece of code. Variables outside that piece of code are never affected by these bindings. In contrast, Block basically binds a variable to a piece of execution stack, not a piece of code. Such bindings are much harder to understand and debug, since execution stack is not something carved in stone, it is dynamic and usually data-dependent. The way Module resolves variable collisions is such that the integrity of inner or outer level bindings is never broken (at least in theory - in practice the lexical scoping is emulated in Mathematica and can be broken, but let's say this is very unlikely to happen by itself). In contrast, nested Block-s will simply have the variable value be the one (re)defined most recently, and also those different Block-s can be in different functions - while nested Module-s normally are in one function. Both these points lead to the same conclusion that code which uses Block is harder to understand and debug. Basically, it is almost the same as using global variables (which are however guaranteed to get back their values after Block executes). Advanced uses of Block Probably the main one is to change the order of evaluation non-trivially, in a way not easily possible with other constructs. Block-ed functions or symbols forget what they were, and therefore evaluate to themselves. This often allows to alter the order of evaluation of expressions in non-trivial ways. I will show a couple of examples. Example: emulating OptionValue Here is one, from this answer: a possible emulation of OptionValue, which is one of the most magical parts of the pattern-matcher: Module[{tried}, Unprotect[SetDelayed]; SetDelayed[f_[args___, optpt : OptionsPattern[]], rhs_] /; !FreeQ[Unevaluated[rhs], autoOptions[]] := Block[{tried = True}, f[args, optpt] := Block[{autoOptions}, autoOptions[] = Options[f]; rhs]] /; ! TrueQ[tried]; Protect[SetDelayed];] the usage: Options[foo] = {bar -> 1}; foo[OptionsPattern[]] := autoOptions[] foo[] (* {bar -> 1} *) Villegas-Gayley trick of function's redefinition (call:f[args___])/;!TrueQ[inF]:= Block[{inF=True}, your code; call ] allows you to inject your own code into another function and avoid infinite recursion. Very useful, both for user-defined and built-in functions Safe memoization fib[n_]:= Block[{fib}, fib[0]=fib[1]=1; fib[k_]:= fib[k] = fib[k-1] + fib[k-2]; fib[n] ] The point here being that the memoized values will be cleared automatically at the end. Making sure the program does not end up in an illegal state in case of Aborts or exceptions a = 1; b = 2; Block[{a = 3, b = 4}, Abort[] ] The point here is that the values of a and b are guaranteed to be not altered globally by code inside Block, whatever it is. Change the order of evaluation, or change some function's properties Comparison operators are not listable by default, but we can make them: Block[{Greater}, SetAttributes[Greater, Listable]; Greater[{1, 2, 3, 4, 5}, {5, 4, 3, 2, 1}] ] (* {False, False, False, True, True} *) Preventing premature evaluation This is a generalization of the standard memoization idiom f[x_]:=f[x] = ..., which will work on arguments being arbitrary Mathematica expressions. The main problem here is to treat arguments containing patterns correctly, and avoid premature arguments evaluation. Block trick is used to avoid infinite recursion while implementing memoization. ClearAll[calledBefore]; SetAttributes[calledBefore, HoldAll]; Module[{myHold}, Attributes[myHold] = {HoldAll}; calledBefore[args___] := ( Apply[Set, Append[ Block[{calledBefore}, Hold[Evaluate[calledBefore[Verbatim /@ myHold[args]]] ] /. myHold[x___] :> x ], True]]; False ) ] Block is used here to prevent the premature evaluation of calledBefore. The difference between this version and naive one will show upon expressions involving patterns, such as this: calledBefore[oneTimeRule[(head:RuleDelayed|Rule)[lhs_,rhs_]]] calledBefore[oneTimeRule[(head:RuleDelayed|Rule)[lhs_,rhs_]]] (* False True *) where the naive f[x_]:=f[x]=... idiom will give False both times. Creating local environments The following function allows you to evaluate some code under certain assumptions, by changing the $Assumptions variable locally. This is just a usual temporary changes to global variables expressed as a function. ClearAll[computeUnderAssumptions]; SetAttributes[computeUnderAssumptions, HoldFirst]; computeUnderAssumptions[expr_, assumptions_List] := Block[{$Assumptions = And[$Assumptions, Sequence @@ assumptions]}, expr]; Local UpValues This example came from a Mathgroup question, where I answered using Block trick. The problem is as follows: one has two (or more) long lists stored in indexed variables, as follows: sym[1] = RandomInteger[10^6, 10^6]; sym[2] = RandomInteger[10^6, 10^6]; sym[3] = ... One has to perform a number of operations on them, but somehow knows (symbolically) that Intersection[sym[1],sym[2]] == 42 (not true for the above lists, but this is for the sake of example). One would therefore like to avoid time-consuming computation Intersection[sym[1],sym[2]];//AbsoluteTiming (* {0.3593750, Null} *) in such a case, and use that symbolic knowledge. The first attempt is to define a custom function like this: ClearAll[myIntersection]; Attributes[myIntersection] = {HoldAll}; myIntersection[sym[i_], sym[j_]] := 42; myIntersection[x_, y_] := Intersection[x, y]; this uses the symbolic answer for sym[_] arguments and falls back to normal Intersection for all others. It has a HoldAll attribute to prevent premature evaluation of arguments. And it works in this case: myIntersection[sym[1], sym[2]] (* 42 *) but not here: a:=sym[1]; b:=sym[2]; myIntersection[a,b];//Timing (* {0.359,Null} *) The point is that having given myIntersection the HoldAll attribute, we prevented it from match the sym[_] pattern for a and b, since it does not evaluate those and so does not know what they store, at the moment of the match. And without such capability, the utility of myIntersection is very limited. So, here is the solution using Block trick to introduce local UpValues: ClearAll[myIntersectionBetter]; Attributes[myIntersectionBetter] = {HoldAll}; myIntersectionBetter[args___] := Block[{sym}, sym /: Intersection[sym[a_], sym[b_]] := 42; Intersection[args]]; what this does is that it Block-s the values of sym[1], sym[2] etc inside its body, and uses UpValues for sym to softly redefine Intersection for them. If the rule does not match, then the "normal" Intersection automatically comes into play after execution leaves Block. So now: myIntersectionBetter[a,b] (* 42 *) This seems to be one of the cases where it would be rather hard to achieve the same result by other means. Local UpValues I find a generally useful technique, used it in a couple more situations where they also saved the day. Enchanced encapsulation control This will load the package but not add its context to the $ContextPath: Block[{$ContextPath}, Needs[your-package]] This will disable any global modifications that the package being loaded could make to a given symbol: Block[{symbolInQuestion}, Needs[the-package]] There are many more applications, Block is a very versatile device. For some more intricate ones, see e.g. this answer - which provides means for new defintions to be tried before the older ones - a feature which would be very hard to get by other means. I will add some more examples as they come to mind. A: Briefly, Block allows you to temporarily change global definitions and functions in a way that Module does not. This is both its strength and weakness. If you use Block[{x = 5}, (* stuff *)] without realizing that something deep inside "stuff" relies on x you may break things. On the other hand you can use this power intentionally to do some interesting things. Change global settings With a recursive definition for Fibonacci numbers: f[0] = 0; f[1] = 1; f[n_] := f[n] = f[n - 1] + f[n - 2] We need a larger value for $RecursionLimit to get the 300th number in the series: Block[{$RecursionLimit = 500}, f @ 300] 222232244629420445529739893461909967206666939096499764990979600 Change the meaning of built-in syntax listSample := {12*12.5*13*13.5*14*14.5, 12*12.5*13*13.5*14*14.5}; Block[{Times = List}, listSample] {{12, 12.5, 13, 13.5, 14, 14.5}, {12, 12.5, 13, 13.5, 14, 14.5}} Additional example (more advanced). Change the behavior of some internal functions One can use this method to Save only the direct definitions of expr, rather than also all linked definitions as is the default behavior: Block[{FullDefinition = Definition}, Save["filename.m", expr] ] Temporarily clear definitions x = 1; (* global definition *) D[Sin[x], x] (* this now fails *) General::ivar: 1 is not a valid variable. >> Solution: Block[{x}, g[x_] = D[Sin[x], x]] We now have the correct Definition for g: g[x_] = Cos[x]
{ "pile_set_name": "StackExchange" }
Q: Porting a mobile game written in C++/OpenGL to UE4 I am very sad because a few days ago the SDK I was using called Marmalade was announced to be shutting down. I was using that SDK to bring my game to the iOS and Android platforms with great ease. I am considering switching to Unreal Engine 4, however I have 0 experience working with it. How simple would it be to port my C++/OpenGL codebase to it? I know there is a million ways to work with unreal, like blueprints and so on, but let's say I already have an engine, what steps would I take to port it? If anyone could provide a rough step by step process of how you would do it and possibly link me to some learning materials I would be very greatful! Thanks all A: The question is too broad but I'll try to answer it anyway. The low level part of your engine (input, rendering, serialization, file operations, etc) is taken care of by UE4. You pretty much won't be able to use parts of your engine in that regard. GUI is also something that you are going to have to remake the UE4 way. Your gameplay logic can be reused. But UE4 has its own approach for gameplay handling as well so you should familiarize yourself with it. Blueprints are very powerful and to use it you gonna have to carefully go through all of your gameplay classes, reparent them from UE4 basic classes (UObject, AActor, AController etc), then mark methods and class members with UFUNCTION and UPROPERTY so it would be exposed to Blueprints. I would recommend to try making a simple project to get a hang of how things are done in UE4 and only then to try to reimplement your game in UE4. UE4 has a good documentation so study it. I personally had an experience to switch from a different engine to UE4 and it took our team around 4 month, but our project is big. We pretty much used none of the code from our old engine. We followed the same approaches and same logic, but we pretty much reimplemented everything.
{ "pile_set_name": "StackExchange" }
Q: How to input text from Serial monitor into a character array? I'm using a Mega 2560 and Uno and want to input text to the serial monitor which can be stored in character array char in[]; I want array specifically as I'll be breaking each character to trigger different code for making a morse code. #include<Arduino.h> //#include<Softwareserial.h> int Speaker1 = 4; int Speaker2 = 6; int LED = 2; int Relay = 12; char n = '0'; char in[]; //int outPins[] = { 2, 4, 6, 8 }; void high() { digitalWrite(Speaker1, HIGH); tone(Speaker2, 800); digitalWrite(LED, HIGH); digitalWrite(Relay, HIGH); } void low() { digitalWrite(Speaker1, LOW); tone(Speaker2, 800); digitalWrite(LED, LOW); digitalWrite(Relay, LOW); } void setup() { Serial.begin(9600); pinMode(Speaker1, OUTPUT); pinMode(Speaker2, OUTPUT); pinMode(LED, OUTPUT); pinMode(Relay, OUTPUT); Serial.print("Enter your desired text: "); //in = Serial.readString(); /*<-------------HELP NEEDED HERE */ for (int i = 0; i < strlen(in); i++) { n = in[i]; switch (n) { case 'A': high(); delay(100); low(); delay(100); high(); delay(300); low(); delay(300); break; case 'B': high(); delay(300); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(300); break; case 'C': high(); delay(300); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(100); low(); delay(300); break; case 'D': high(); delay(300); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(300); break; case 'E': high(); delay(100); low(); delay(300); break; case 'F': high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(100); low(); delay(300); break; case 'G': high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(100); low(); delay(300); break; case 'H': high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(300); break; case 'I': high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(300); break; case 'J': high(); delay(100); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(300); break; case 'K': high(); delay(300); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(300); low(); delay(300); break; case 'L': high(); delay(100); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(300); break; case 'M': high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(300); break; case 'N': high(); delay(300); low(); delay(100); high(); delay(100); low(); delay(300); break; case 'O': high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(300); break; case 'P': high(); delay(100); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(100); low(); delay(300); break; case 'Q': high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(300); low(); delay(300); break; case 'R': high(); delay(100); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(100); low(); delay(300); break; case 'S': high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(300); break; case 'T': high(); delay(300); low(); delay(300); break; case 'U': high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(300); low(); delay(300); break; case 'V': high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(300); low(); delay(300); break; case 'W': high(); delay(100); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(300); break; case 'X': high(); delay(300); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(300); low(); delay(300); break; case 'Y': high(); delay(300); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(300); break; case 'Z': high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(300); break; case ' ': delay(700); break; case '1': high(); delay(100); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(300); break; case '2': high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(300); break; case '3': high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(300); break; case '4': high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(300); low(); delay(300); break; case '5': high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(300); break; case '6': high(); delay(300); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(300); break; case '7': high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(300); break; case '8': high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(100); low(); delay(100); high(); delay(100); low(); delay(300); break; case '9': high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(100); low(); delay(300); break; case '10': high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(100); high(); delay(300); low(); delay(300); break; } } } void loop() { } A: I suggested in a comment you read the blog post Reading Serial on the Arduino. In this post, Majenko shows a readline() function that does almost exactly what you want. This function is non-blocking, which, in the embedded world, is most of the time a mandatory feature. However, in one of your comments you wrote that you want a blocking function: I need the program to "wait" like [...] scanf Degrading a non-blocking function into a blocking one is as easy as wrapping the non-blocking function in a loop. Here is a code snippet for reading a CR-terminated string, which is similar to a blocking version of Majenko's readline(): char buffer[80]; size_t pos = 0; for (;;) { int c = Serial.read(); if (c == -1) continue; // no input if (c == '\r') { // end of line buffer[pos] = '\0'; // terminate the string break; } if (pos < sizeof buffer - 1) { buffer[pos++] = c; } } That being said, I could not resist the temptation to brutally simplify your program. The key to the simplification is to consider the Morse code as a data structure. Then, the code for keying a string is generic: you look up each character in the code table and key it in turn. This saves the long switch/case: struct code_t { char c; const char *code; }; static const code_t morse_code[] = { {'A', ".-" }, {'B', "-..." }, {'C', "-.-." }, {'D', "-.." }, {'E', "." }, {'F', "..-." }, {'G', "--." }, {'H', "...." }, {'I', ".." }, {'J', ".---" }, {'K', "-.-" }, {'L', ".-.." }, {'M', "--" }, {'N', "-." }, {'O', "---" }, {'P', ".--." }, {'Q', "--.-" }, {'R', ".-." }, {'S', "..." }, {'T', "-" }, {'U', "..-" }, {'V', "...-" }, {'W', ".--" }, {'X', "-..-" }, {'Y', "-.--" }, {'Z', "--.." }, {'1', ".----"}, {'2', "..---"}, {'3', "...--"}, {'4', "....-"}, {'5', "....."}, {'6', "-...."}, {'7', "--..."}, {'8', "---.."}, {'9', "----."}, {'0', "-----"}, {' ', " " }, {'\0', NULL} // sentinel }; static inline void high() { digitalWrite(LED_BUILTIN, HIGH); } static inline void low() { digitalWrite(LED_BUILTIN, LOW); } // Key a string in Morse. void key(const char *s) { for (; *s; s++) { // *s = current letter // Find this letter's code. const code_t *p; for (p = morse_code; p->c; p++) { if (p->c == toupper(*s)) break; // found } if (!p->c) continue; // not found -> ignore // Send this code's symbols. for (const char *code = p->code; *code; code++) { if (*code != ' ') high(); switch (*code) { case ' ': delay(100); break; case '.': delay(100); break; case '-': delay(300); break; } low(); delay(100); } delay(200); // inter-letter spacing = 300 ms } } void setup() { Serial.begin(9600); pinMode(LED_BUILTIN, OUTPUT); } void loop() { // Read a string. char buffer[80]; size_t pos = 0; for (;;) { int c = Serial.read(); if (c == -1) continue; // no input if (c == '\r') { // end of line buffer[pos] = '\0'; // terminate the string break; } if (pos < sizeof buffer - 1) { buffer[pos++] = c; } } // Key it in Morse. key(buffer); } Note that this program reads CR-terminated strings from the Serial port and keys them on the builtin LED. If you want your program to work on a single string, you can call exit() at the end of loop() or, alternatively, merge loop() into setup() and provide an empty loop().
{ "pile_set_name": "StackExchange" }
Q: WP8 Pull to Refresh inside Pivot I am trying to add a Pull to Refresh RadControl from Telerik within a PivotItem in WP8. This is the code: <phone:PivotItem Header="Title" Foreground="Black"> <telerikPrimitives:RadDataBoundListBox.PullToRefreshIndicatorStyle> <Style TargetType="telerikListBox:PullToRefreshIndicatorControl"> <Setter Property="RefreshTimeLabelFormat" Value="last refresh time: {0:H:mm}"/> </Style> </telerikPrimitives:RadDataBoundListBox.PullToRefreshIndicatorStyle> </phone:PivotItem> Error messages: The property 'PullToRefreshIndicatorStyle' does not exist on the type 'PivotItem' in the XML namespace` The attachable property 'PullToRefreshIndicatorStyle' was not found in type 'RadDataBoundListBox'. The member "PullToRefreshIndicatorStyle" is not recognized or is not accessible. How do I get this to work within the PivotItem control? A: Looks like you are missing some tags. Aren't you suppose to have the telerikPrimitives:RadDataBoundListBox defined within the pivot item?' Like such: <phone:PivotItem Header="Title" Foreground="Black"> <telerikPrimitives:RadDataBoundListBox> <telerikPrimitives:RadDataBoundListBox.PullToRefreshIndicatorStyle> <Style TargetType="telerikListBox:PullToRefreshIndicatorControl"> <Setter Property="RefreshTimeLabelFormat" Value="last refresh time:{0:H:mm}"/> </Style> </telerikPrimitives:RadDataBoundListBox.PullToRefreshIndicatorStyle> </telerikPrimitives:RadDataBoundListBox> </phone:PivotItem>
{ "pile_set_name": "StackExchange" }
Q: Why does the quality and style on this Naruto Shippuden series differ from the regular one? I was watching this episode of Naruto on YouTube. I would like to know why the quality and style of the anime differs from the regular one? A: The first part of the video's description reads (emphasis by me): Naruto,Sasuke,Kakashi Team 7 Vs Kaguya Ōtsutsuki Full Fight (English Sub) . Naruto Shippuden: Ultimate Ninja Storm 4 the Rabbit Goddess大筒木カグヤ"Kaguya Otsutsuki" vs Naruto,Sasuke Uchiha Perfect Susanoo Kakashi. Rinne Sharingan vs Byakugan. Kaguya's unstable Tailed Beast Transformation awakening,Final TruthSeeker Orbs ultimate jutsu. Previous Boss Battles; So as you can see, that is not a video from an episode of the anime series, but rather a cutscene from the Naruto Shippuden: Ultimate Ninja Storm 4 videogame. The bottom-most part of the description also clearly states that this is from a game:
{ "pile_set_name": "StackExchange" }
Q: Elasticsearch: disable coordination factor for multi match query I use a multi match query with different weights on each field. I set tie_breaker to 1 to disable use_dis_max and use the sum instead of the max for the score. GET index_name/index_type/_search?explain { "size": 1, "query": { "multi_match": { "query": "ticket", "fields": ["title^9", "descr^4", "*section_body"], "tie_breaker": 1 } } } ES sums the scores for each field then multiplies it by the coordination factor. I want to disable the coordination factor, so I tried to wrap my multi match query into a bool query and set disable_coord to true as the following: GET index_name/index_type/_search?explain { "size": 1, "query": { "bool": { "disable_coord": true, "should": [ { "multi_match": { "query": "ticket", "fields": ["title^9", "descr^4", "*section_body"], "tie_breaker": 1 } } ] } } } But I can see that nothing changed in the scoring formula, ES is still summing the scores for all different fields then multiplying the result by the coordination factor. How can I disable the coordination factor ? A: I would recommending separating the individual conditions of the should and boosting them individually. That might look something like the following: { "size": 1, "query": { "bool": { "disable_coord": true, "should": [ {"match" : {"title" : {"query" : "ticket", "boost" : 9}}}, {"match" : {"descr" : {"query" : "ticket", "boost" : 4}}}, {"multi_match" : { "fields" : ["*section_body"], "query" : "ticket" }} ] } } } For a silly set of test data I ginned up, it does look like this results in the coordination factor no longer being applied, namely that the resulting scores for each document are higher when disable_coord is true versus when it is set to false.
{ "pile_set_name": "StackExchange" }
Q: Relation between tracial states on von Neumann algebras and their GNS representations Let $M$ be a von Neumann algebra acting on a Hilbert space $H$, and let $\tau$ be a faithful tracial state on $M$. What is the relation between the GNS representation of $(M,\tau)$ and the original action of $M$ on $H$? More precisely, let $M_\tau$ denote the Hilbert space obtained by completing $M$ with the inner product $\langle x,y\rangle_\tau=\tau(y^*x)$ (since $\tau$ is faithful, this inner product is nondegenerate), and $M$ acts faithfully (again since $\tau$ is a faithful state) on $M_\tau$ by left multiplication. Let $\varphi_\tau:M\to B(M_\tau)$ denote this representation. My question is: is $\varphi_\tau(M)$ a von Neumann algebra on $M_\tau$? If so, $\tau$ becomes a vector state under the identification $M\simeq\varphi_\tau(M)$: $\tau(u)=\langle u(1_M),1_M\rangle_\tau$. In case $M$ admits a cyclic vector $x$ for which $\tau(u)=\langle u(x),x\rangle$, the result is true, but the last comment above becomes useless. In fact, in this case the actions of $M$ on $H$ and on $M_\tau$ are unitarily equivalent (see Murphy, Theorem 5.1.4). A: The result is that $\varphi_\tau(M)$ is a von Neumann algebra if and only if $\tau $ is normal. If $\tau$ is normal, then so is $\varphi_\tau$ and so $\varphi_\tau(M)$ is a von Neumann algebra. Conversely, suppose that $\varphi_\tau(M)$ is a von Neumann algebra. Let $\{x_j\}$ be a monotone net of selfadjoints in $M$ and let $x=\sup x_j\in M$. As $\{\varphi_\tau(x_j)\}$ is a monotone bounded net of selfadjoints in $\varphi_\tau(M)$, since $\varphi_\tau$ is surjective there exists $y\in M$ such that $\varphi_\tau(y)=\sup\varphi_\tau(x_j)$. Since $\varphi_\tau$ is a $*$-isomorphism and $\varphi_\tau(y-x_j)\geq0$, we get that $y-x_j\geq0$ for all $j$. So $y$ is an upper bound for the net, and thus $x\leq y$ (because $x$ is the supremum of the net in $M$). But then $$\varphi_\tau(x_j)\leq\varphi_\tau(x)\leq\varphi_\tau(y),$$ which implies $\varphi_\tau(x)=\varphi_\tau(y)$ since $\varphi_\tau(y)$ is the supremum of the net $\{\varphi_\tau(x_j)\}$ in $\varphi_\tau(M)$. Then $y-x$ is a positive element of $M$ with $\varphi_\tau(y-x)=0$, so by faithfulness $y-x=0$. In other words, $$ \sup\varphi_\tau(x_j)=\varphi_\tau(y)=\varphi_\tau(x)=\varphi_\tau(\sup x_j). $$ So $\varphi_\tau$ is normal. And then $$ \sup\tau(x_j)=\sup\langle\varphi_\tau(x_j)\,\hat 1_M,\hat 1_M\rangle =\langle\sup\varphi_\tau(x_j)\hat1_M,\hat1_M\rangle =\langle\varphi_\tau(\sup x_j)\hat1_M,\hat1_M\rangle=\tau(\sup x_j). $$ (the second equality is due to the fact that $\sup\varphi_\tau(x_j)=\lim_{SOT}\varphi_\tau(x_j)$). So $\tau$ is normal.
{ "pile_set_name": "StackExchange" }
Q: Performance between Django and raw Python I was wondering what the performance difference is between using plain python files to make web pages and using Django. I was just wondering if there was a significant difference between the two. Thanks A: Django IS plain Python. So the execution time of each like statement or expression will be the same. What needs to be understood, is that many many components are put together to offer several advantages when developing for the web: Removal of common tasks into libraries (auth, data access, templating, routing) Correctness of algorithms (cookies/sessions, crypto) Decreased custom code (due to libraries) which directly influences bug count, dev time etc Following conventions leads to improved team work, and the ability to understand code Plug-ability; Create or find new functionality blocks that can be used with minimal integration cost Documentation and help; many people understand the tech and are able to help (StackOverflow?) Now, if you were to write your own site from scratch, you'd need to implement at least several components yourself. You also lose most of the above benefits unless you spend an extraordinary amount of time developing your site. Django, and other web frameworks for every other language, are designed to provide the common stuff, and let you get straight to work on business requirements. If you ever banged out custom session code and data access code in PHP before the rise of web frameworks, you won't even think of the performance cost associated with a framework that makes your job interesting and eas(y)ier. Now, that said, Django ships with a LOT of components. It is designed in such a way that most of the time, they won't affect you. Still, a surprising amount of code is executed for each request. If you build out a site with Django, and the performance just doesn't cut it, you can feel free to remove all the bits you don't need. Or, you can use a 'slim' python framework. Really, just use Django. It is quite awesome. It powers many sites millions times larger than anything you (or I) will build. There are ways to improve performance significantly, like utilizing caching, rather than optimizing a loop over custom Middleware. A: Depends on how your "plain Python" makes web pages. If it uses a templating engine, for instance, the performance of that engine is going make a huge difference. If it uses a database, what kind of data access layer you use (in the context of the requirements for that layer) is going to make a difference. The question, thus, becomes a question of whether your arbitrary (and presently unstated) toolchain choices have better runtime performance than the ones selected by Django. If performance is your primary, overriding goal, you certainly should be able to make more optimal selections. However, in terms of overall cost -- ie. buying more web servers for the slower-runtime option, vs buying more programmer-hours for the more-work-to-develop option -- the question simply has too many open elements to be answerable. A: Premature optimisation is the root of all evil. Django makes things extremely convenient if you're doing web development. That plus a great community with hundreds of plugins for common tasks is a real boon if you're doing serious work. Even if your "raw" implementation is faster, I don't think it will be fast enough to seriously affect your web application. Build it using tools that work at the right level of abstraction and if performance is a problem, measure it and find out where the bottlenecks are and apply optimisations. If after all this you find out that the abstractions that Django creates are slowing your app down (which I don't expect that they will), you can consider moving to another framework or writing something by hand. You will probably find that you can get performance boosts by caching, load balancing between multiple servers and doing the "usual tricks" rather than by reimplementing the web framework itself.
{ "pile_set_name": "StackExchange" }
Q: Is question 17571 on The Workplace on-topic here? Although I'm doubtful, after going through help/on-topic of this site, but thought I'd still ask. Is the question How should a teacher respond to his/her student in school, when they happend to be parent and child? on-topic here? A: This question seems more geared toward elementary and high-school level parent-child relationships, but you could write a postsecondary-level version of this which would be appropriate for our board.
{ "pile_set_name": "StackExchange" }
Q: What is a function that converts any number to a one, while keeping the sign intact? Given a number $x$, I would like an $f(x)$ whose value always equals 1, but keeps the sign of $x$ intact. So if $x = 5$, then $f(x) = 1$. If $x = -13$, then $f(x) = -1$ and $f(0) = 0$ What is the algebraic formula for $f(x)$? I was leaning towards using mod, but couldn't figure out the correct equation. Thank you! A: We can define the $sgn(x)$ function as follows: $$sgn(x)=1, x>0$$ $$sgn(x)=0, x=0$$ $$sgn(x)=-1, x<0$$ Another possibility is considering the function: $$g(x)=\frac{x}{|x|}$$ that is defindened $\forall x\in R, x\neq0$.
{ "pile_set_name": "StackExchange" }
Q: Getting a Tensors value in Java I habe trained a recurrent neural network with tensorflow using python. I saved the model and restored it in a Java-Application. This is working. Now i feed my input-Tensors to the pretrained modell and fetch the output. My problem now is, that the output is a Tensor and I don´t know hot to get the Tensors value (it is a simple integer-tensor of shape 1). The python code looks like this: sess = tf.InteractiveSession() X = tf.placeholder(tf.float32, [None, n_steps, n_inputs], name="input_x") y = tf.placeholder(tf.int32, [ None]) keep_prob = tf.placeholder(tf.float32, name="keep_prob") basic_cell = tf.contrib.rnn.OutputProjectionWrapper(tf.contrib.rnn.BasicRNNCell(num_units=n_neurons),output_size=n_outputs) outputs, states = tf.nn.dynamic_rnn(basic_cell, X, dtype=tf.float32) logits = tf.layers.dense(states, n_outputs, name="logits") xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y,logits=logits) loss = tf.reduce_mean(xentropy) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) training_op = optimizer.minimize(loss) correct = tf.nn.in_top_k(logits, y,1, name="correct") pred = tf.argmax(logits, 1, name="prediction") accuracy = tf.reduce_mean(tf.cast(correct, tf.float32)) init = tf.global_variables_initializer() def train_and_save_rnn(): # create a Saver object as normal in Python to save your variables saver = tf.train.Saver() # Use a saver_def to get the "magic" strings to restore saver_def = saver.as_saver_def() print (saver_def.filename_tensor_name) print (saver_def.restore_op_name) # Loading the Train-DataSet data_train, labels_train = load_training_data("Train.csv") data_test, labels_test = load_training_data("Test.csv") #labels_train=reshape_labels_to_sequences(labels_train) #labels_test=reshape_labels_to_sequences(labels_test) dt_train = reshape_data(data_train) dt_test = reshape_data(data_test) X_test = dt_test X_test = X_test.reshape((-1, n_steps, n_inputs)) y_test = labels_test-1 sess.run(tf.global_variables_initializer()) # START TRAINING ... for epoch in range(n_epochs): for iteration in range(dt_train.shape[0]-1): X_batch, y_batch = dt_train[iteration], labels_train[iteration]-1 X_batch = X_batch.reshape((-1, n_steps, n_inputs)) y_batch = y_batch.reshape((1)) sess.run(training_op, feed_dict={X: X_batch, y: y_batch}) acc_train = accuracy.eval(feed_dict={X: X_batch, y: y_batch}) acc_test = accuracy.eval(feed_dict={X: X_test, y: y_test}) print(epoch, "Train accuracy:", acc_train, "Test accuracy:", acc_test) # SAVE THE TRAINED MODEL ... builder.add_meta_graph_and_variables(sess, [tf.saved_model.tag_constants.SERVING]) builder.save(True) #true for human-readable What I do in Java is: byte[] graphDef = readAllBytesOrExit(Paths.get(IMPORT_DIRECTORY, "/saved_model.pbtxt")); /*List<String> labels = readAllLinesOrExit(Paths.get(IMPORT_DIRECTORY, "trained_model.txt")); */ try (SavedModelBundle b = SavedModelBundle.load(IMPORT_DIRECTORY, "serve")) { // create the session from the Bundle Session sess = b.session(); s = sess; g = b.graph(); // This is just a sample Tensor for debugging: Tensor t = Tensor.create(new float[][][] {{{(float)0.8231331,(float)-5.2657013,(float)-1.1111984,(float)0.0074825287,(float)0.075252056,(float)0.07835889,(float)-0.035752058,(float)-0.035610847,(float)0.045247793,(float)1.5594741,(float)57.78549,(float)-0.21489286,(float)0.011989355,(float)0.15965772,(float)13.370155,(float)3.4708557,(float)3.7776794,(float)-1.1115816,(float)0.72939104,(float)-0.44342846,(float)11.001129,(float)10.549805,(float)-50.719162,(float)-0.8261242,(float)0.71805984,(float)-0.1849739,(float)9.334606,(float)3.0003967,(float)-52.456577,(float)-0.1875816,(float)0.19306469,(float)0.004947722,(float)5.4054375,(float)-0.8630371,(float)-24.599575,(float)1.3387873,(float)-1.1488495,(float)-2.8362968,(float)22.174248,(float)-32.095154,(float)10.069847}}}); runTensor(t); } public static void runTensor(Tensor inputTensor) throws IOException, FileNotFoundException { try (Graph graph = g; Session sess = s;) { Integer gesture = null; Tensor y_ph = Tensor.create(new int[]{0}); Tensor result = sess.runner() .feed("input_x", inputTensor) .feed("Placeholder", y_ph) .fetch("pred") .run().get(0); System.out.println(result); } catch (Exception e) { e.printStackTrace(); } } The output should (I´m not sure if it´s working) be an Integer between 0 and 10 for the predicted class. How can I extract the Integer in Java from the Tensor? Thank you in advance. A: Use Tensor.intValue() if it is a scalar, or Tensor.copyTo() if it is not. (So System.out.println(result.intValue());)
{ "pile_set_name": "StackExchange" }
Q: Do opponent mulligans tell you anything? In Hearthstone, both you and your opponent get an opportunity to mulligan (or redraw) some cards at the start of a match. My question is whether strategy is altered based upon seeing your opponent mulligan all of their cards, or perhaps none of their cards. For example, do competitive aggressive decks behave more aggressively when an opponent redraws all cards? What can be discerned (if anything) by the fact that your opponent redraws cards at the start? A: The short answer to this question is yes, opponent's mulligans can tell you something. However, things that it will tell you can vary significantly, generally based on the class your opponent is playing. Firstly, decks tend to be either oriented towards the short game, the mid game, or the long game. For example, Zoolock is one of the most well-known short game decks, whereas an example of a long game deck would be Druid ramp. Using an example of warlock, with the current meta taken into account: Warlock is generally the easiest to discern based on mulligan. If your opponent mulligans heavily, the most likely possibilities are: They are playing Handlock and don't have a good hand. They are playing Zoolock and started with no one-drops. On the flip side, if they keep most, if not all their cards, the most likely possibilities are: They are playing Zoolock and have at least 1 or 2 one-drops, ideally an undertaker. They are playing Handlock, and have either a twilight drake in hand or a mountain giant, as well as one of their earlier cards or removal, including hellfire, mortal coil, ancient watcher + sunfury protector. Keep in mind, there are other, less played warlock decks that could throw this off, but generally, per class, there tend to be two to three decks that 50-75% of the hearthstone population is playing. Unfortunately, it would be very difficult to break down all possible scenarios, as information that might be derived from your opponent's mulligan is dependent on a number of things. The most key things to think about when deciding what your opponent's mulligan means, other than knowing what net-decks are common in which class: What rank are you, and what is the 'deck to beat' at that rank? What class is your opponent playing? What class are YOU playing?
{ "pile_set_name": "StackExchange" }
Q: CNN with 0.995 accuracy does not perform well in implementation To keep it short, I have trained a model on a binary classification with equal data in each class so as to not have class imbalance. The model is trained on 10 000 images with the respective labels and validated on 6 000 images with the respective labels. The result is a model with 0.995 accuracy which should mean that implementation of the model will classify the correct classes 0.995 of the time. (Model is NOT choosing class A all the time and being correct 0.995 of the time because there is no class imbalance) However, this is not the case. Also, the data has been shuffled so the model is also not guessing class A for the first 5000 images and then guessing class B for the rest to get 0.995 accuracy. The full code, question and things I took note of is on my github: https://github.com/Nickclickflick/tutorials Feel free to download and use the model so as to see the results of the flappy bird bot. Edit 1: 8 000 of the total images are original and the other 8 000 are augmented as described below The following code snippet shows the augmentation to the original images datagen = ImageDataGenerator(featurewise_center=True, samplewise_center=True, featurewise_std_normalization=True, samplewise_std_normalization=True, zca_whitening=True, zca_epsilon=1e-06) Edit 2: The following code was used to generate the original dataset (this is available on github) import numpy as np from grabscreen import grab_screen import cv2 import time from getkeys import key_check import os jump = [1,0] do_nothing = [0,1] starting_value = 1 while True: file_name = 'E:/flappy/tmp_data/training_data-{}.npy'.format(starting_value) if os.path.isfile(file_name): print('File exists, moving along',starting_value) starting_value += 1 else: print('File does not exist, starting fresh!',starting_value) break def keys_to_output(keys): output = [0,0] if ' ' in keys: output = jump else: output = do_nothing return output def main(file_name, starting_value): file_name = file_name starting_value = starting_value training_data = [] # countdown for i in list(range(6))[::-1]: print(i+1) time.sleep(1) paused = False print('STARTING!!!') while True: if not paused: screen = grab_screen(region=(0,200,600,1000)) last_time = time.time() # resize to something a bit more acceptable for a CNN screen = cv2.resize(screen, (150,250)) # run a color convert: screen = cv2.cvtColor(screen, cv2.COLOR_BGR2RGB) keys = key_check() output = keys_to_output(keys) training_data.append([screen,output]) if len(training_data) % 10 == 0: print(len(training_data)) if len(training_data) == 100: np.save(file_name,training_data) print('SAVED') training_data = [] starting_value += 1 file_name = 'E:/flappy/tmp_data/training_data-{}.npy'.format(starting_value) keys = key_check() # pause script if 'T' in keys: if paused: paused = False print('unpaused!') time.sleep(1) else: print('Pausing!') paused = True time.sleep(1) main(file_name, starting_value) A: There are three things named accuracy, Precision, and recall. Accuracy is generally not the preferred performance measure for classifiers, especially when you are dealing with skewed datasets (i.e., when some classes are much more frequent than others). Precision: TP _________ TP + FP Recall: TP _________ TP + FN where, TP=True positives FP=False negatives A much better way to evaluate the performance of a classifier is to look at the confusion matrix. The general idea is to count the number of times instances of class A are classified as class B.To compute the confusion matrix, you first need to have a set of predictions, so they can be compared to the actual targets. you can use the cross_val_predict() function from scikitkearn library to compute the predicted targets. from sklearn.model_selection import cross_val_predict y_train_pred = cross_val_predict(sgd_clf, X_train, y_train_5, cv=3) Now you are ready to get the confusion matrix using the confusion_matrix() function. Just pass it the target classes (y_train_5) and the predicted classes (y_train_pred): from sklearn.metrics import confusion_matrix confusion_matrix(y_train_5, y_train_pred) Scikit-Learn provides several functions to compute classifier metrics, including precision and recall: from sklearn.metrics import precision_score, recall_score precision_score(y_train_5, y_train_pred) recall_score(y_train_5, y_train_pred) Hope this helps:)
{ "pile_set_name": "StackExchange" }
Q: How to stop variable in for loop from being passed by reference in JavaScript I am assigning onclicks that contain the number that the link is on the page. This is my code: var aTags = document.getElementsByTagName("a"); for (var t = 0; t < aTags.length; t++){ var aTag = aTags[t]; aTag.onclick = function(){setSubMenu(t);}; } function setSubMenu(t){ console.log("t: " + t); //The issue is t is always evaluating to the length of aTags //instead of the current tag. } How do I fix this issue? A: Wrap it in a self-executing closure: for (var t = 0; t < aTags.length; t++)(function(t) { var aTag = aTags[t]; aTag.onclick = function() { setSubMenu(t); }; })(t);
{ "pile_set_name": "StackExchange" }
Q: Is operator && strict in Haskell? For example, I have an operation fnB :: a -> Bool that makes no sense until fnA :: Bool returns False. In C I may compose these two operations in one if block: if( fnA && fnB(a) ){ doSomething; } and C will guarantee that fnB will not execute until fnA returns false. But Haskell is lazy, and, generally, there is no guarantee what operation will execute first, until we don't use seq, $!, or something else to make our code strict. Generally, this is what we need to be happy. But using && operator, I would expect that fnB will not be evaluated until fnA returns its result. Does Haskell provide such a guarantee with &&? And will Haskell evaluate fnB even when fnA returns False? A: The function (&&) is strict in its second argument only if its first argument is True. It is always strict in its first argument. This strictness / laziness is what guarantees the order of evaluation. So it behaves exactly like C. The difference is that in Haskell, (&&) is an ordinary function. In C, this would be impossible. But Haskell is lazy, and, generally, there are no guarantee what operation will execute first, until we don't use seq, $!, or something else to make our code strict. This is not correct. The truth is deeper. Crash course in strictness: We know (&&) is strict in its first parameter because: ⊥ && x = ⊥ Here, ⊥ is something like undefined or an infinite loop (⊥ is pronounced "bottom"). We also know that (False &&) is non-strict in its second argument: False && ⊥ = False It can't possibly evaluate its second argument, because its second argument is ⊥ which can't be evaluated. However, the function (True &&) is strict in its second argument, because: True && ⊥ = ⊥ So, we say that (&&) is always strict in its first argument, and strict in its second argument only when the first argument is True. Order of evaluation: For (&&), its strictness properties are enough to guarantee order of execution. That is not always the case. For example, (+) :: Int -> Int -> Int is always strict in both arguments, so either argument can be evaluated first. However, you can only tell the difference by catching exceptions in the IO monad, or if you use an unsafe function. A: As noted by others, naturally (&&) is strict in one of its arguments. By the standard definition it's strict in its first argument. You can use flip to flip the semantics. As an additional note: Note that the arguments to (&&) cannot have side effects, so there are only two reasons why you would want to care whether x && y is strict in y: Performance: If y takes a long time to compute. Semantics: If you expect that y can be bottom.
{ "pile_set_name": "StackExchange" }
Q: What happens when type providers change in F#? After watching Channel 9's video on F# Type Providers, I'm wondering about data schema changes. Don touched on this a little bit at the end, but I'm looking for more details. The demo made it look as though you're essentially pressing '.' to explore what kinds of data is available to you. After you link up to, say, crime rates in the US in 2008, what happens when you distribute your application and the schema changes? Do you get runtime type errors? Is it the responsibility of the developer to handle these errors? Also, does this put the responsibility into the type provider's hands? Currently when you download a .NET assembly, you know it will never change until you (manually or through a service) explicitly update it. Compile errors from evolving types must be resolved, but you can always hold off the upgrade until you're ready for the change. With type providers, do you have to program more cautiously against them? A: Responding to the schema changes is the responsibility of the type provider, but only at the development time. Once you develop an application, it gets compiled using the type provider and using the current schema at the time of the compilation. When you're using type provider from Visual Studio, it can monitor the schema changes and notify the Visual Studio IDE that there has been a change in the schema. I wrote a XML type provider example that does this, so when you change the schema (XML file used as an example), you'll immediately get errors in VS. I did a video demonstration of this (around 19:40). Once you compile your program, the type provider generates code that should be used in the compiled form (and the type provider is not used at runtime). This means that if the schema changes at runtime, you can't do anything about it (the developer needs to react). If the schema change is backwards-compatible (i.e. add new columns to a DB table), then your program may still work fine though.
{ "pile_set_name": "StackExchange" }
Q: celery task_success with sender filter I am trying to get the sender filter working e.g. @celery.task def run_timer(crawl_start_time): return crawl_start_time @task_success.connect def run_timer_success_handler(sender, result, **kwargs): print '##################################' print 'in run_timer_success_handler' The above works fine, but if I try to filter by sender, it never works: @task_success.connect(sender='tasks.run_timer') def run_timer_success_handler(sender, result, **kwargs): print '##################################' print 'in run_timer_success_handler' I also tried: @task_success.connect(sender='run_timer') @task_success.connect(sender=run_timer) @task_success.connect(sender=globals()['run_timer']) None of them work. How do I effectively use the sender filter to ensure that by callback is called on for the run_timer task and not the others. A: It's better to filter sender inside function in this case now. Like: @task_success.connect def ... if sender == '...': ... Because current celery signals implementation has issue when task sender and worker are different python processes. Because it converts your sender into the identifier and uses it for filtering, but celery sends task by string name. Here is the problem code (celery.utils.dispatch.signals): def _make_id(target): # pragma: no cover if hasattr(target, 'im_func'): return (id(target.im_self), id(target.im_func)) return id(target) And id('tasks.run_timer') is not the same as id('tasks.run_timer') of a worker process. If you want you may hack it and relace id by hash function
{ "pile_set_name": "StackExchange" }
Q: Backup of Postgresql database with pg_dump after a search on the internet with no result, I turn to you! I would like to create a java program, that if you click on a button, it makes a backup of a database in postgresql. I saw that i must use pg_dump but do not understand how to make it work. can someone please help me? thank you! A: if you want to use an OS command inside a Java program, make this (with vivek answer): public class Backup{ public static void main(String[] args) throws java.io.IOException, java.lang.InterruptedException { final String cmd = "pg_dump --format=c --username \"postgres\" db_name > \"D:\\pgBackup\\db_name.backup\""; java.lang.Runtime rt = java.lang.Runtime.getRuntime(); java.lang.Process p = rt.exec(cmd); } }
{ "pile_set_name": "StackExchange" }
Q: MATLAB no longer supports user-defined MEX configuration? I've upgraded my MATLAB to 2014b (on OS X 10.10), and tried to test some old MEX C/C++ codes. As usual, I run mex -setup from the command window, and I would expect to be provided the chance to overwrite the option file "meshopt.sh". But now, it seems MATLAB has made some change and I am not allowed to change the MEX configuration, it simply says: MEX configured to use Xcode with Clang for C language compilation, ... to choose a different language, select one from the following mex -setup C++ mex -setup FORTRAN So, is it true that the old ways to modify "mexopts.sh" are no longer feasible? A: It seems that the following command works: mex -setup my_mexopts.sh however, there's some warning information, Legacy MEX infrastructure is provided for compatibility; it will be removed in a future version of MATLAB. Apart from that, everything looks fine, except I got some warning at compile time seems due to compiler version(gcc 4.9.1) on my current system(OS X 10.10). gcc: warning: couldn't understand kern.osversion '14.0.0
{ "pile_set_name": "StackExchange" }
Q: How can I make a copy of a CookieContainer? Given, instances of CookieContainer are not thread safe. Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe. So it turns out I cannot use the same container across multiple concurrent HTTP requests without synchronization. Unfortunatelly from the documentation at MSDN it's not clear how one can properly synchronize it. A solution would be using a copy of a master container for each request and once the request is finished the cookies from the copy could be merged back to the master container. Creating a copy and merging can be done in a synchronized manner. So the question is : how can I make a copy of an instance of the CookieContainer class? A: The CookieContainer class is Serializable. Since you said you need to serialize it anyway, why not just use a BinaryFormatter to serialize it to a MemorySteam and then Deserialize it to make a copy? I know this is overly simple, so please ignore if it isn't helpful. private CookieContainer CopyContainer(CookieContainer container) { using(MemoryStream stream = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, container); stream.Seek(0, SeekOrigin.Begin); return (CookieContainer)formatter.Deserialize(stream); } } A: Take a look at the CookieContainter class and you'll see that concurrent scenarios are suppose to occur when there are changes in the cookie collection, right? You'll notice that the author of CookieContainer took care of using lock {} and SyncRoot all around these collection-changing parts of the code, and I don't think that such approach is not addressed to concurrent scenarios. Also, you can notice that any added Cookie is literally cloned, so the cookies inside the container and all the operations made will not mess up with object references outside the cookie container. In the worst case of I'm missing something, the clone also gives us a tip of what exactly you have to copy and how you could do it, in case of using the reflection approach described in the other posts (I personally would not consider it a hack, since it fits the requirement and it is managed, legal and safe code :) ). In fact, the mentions all over MSDN documentation are "Any instance members are not guaranteed to be thread safe." - its a kind of reminder, because you are right, you really need to be careful. Then with such statement you can suppose basically two things: 1) Non-static members are not safe at all. 2) Some members can be thread safe, but they aren't properly documented.
{ "pile_set_name": "StackExchange" }
Q: How to find object with id value in deep nested array? Given this structure, how would I find the object with the given id in this deeply nested object structure. const menuItems = [ { id: 1, imageUrl: "http://placehold.it/65x65", display: "Shop Women", link: "#", type: "image", nextItems: [ { id: 10, display: "홈", link: "#", type: "menuitem" }, { id: 20, display: "의류", link: "#", type: "menuitem-withmore", nextItems: [ { id: 100, display: "I'm inside one nest", link: "#", type: "menuitem" } ] }, { id: 30, display: "가방", link: "#", type: "menuitem-withmore", nextItems: [] }, { id: 40, display: "신발", link: "#", type: "menuitem-withmore", nextItems: [] }, { id: 50, display: "악세서리", link: "#", type: "menuitem-withmore", nextItems: [] }, { id: 60, display: "SALE", link: "#", type: "menuitem-withmore", style: "bold", nextItems: [] }, { id: 70, display: "브랜드", link: "#", type: "menuitem-withmore", nextItems: [] }, { type: "separator" }, { id: 80, display: "위시리스트", link: "#", type: "menuitem" }, { id: 90, display: "고객센터", link: "#", type: "menuitem" }, { id: 99, display: "앱 다운로드", link: "#", type: "menuitem" } ] }, { id: 2, imageUrl: "http://placehold.it/65x65", display: "Shop Men", link: "#", type: "image", nextItems: [ { id: 95, display: "MEN's ITEMS.", link: "#", type: "menuitem" } ] } ]; Let's say I want to find the object with id: 20 and return this: { id: 20, display: "의류", link: "#", type: "menuitem-withmore", nextItems: [ { id: 100, display: "I'm inside one nest", link: "#", type: "menuitem" } ] }, I can't seem to find how to use lodash for this, and there's this package that may have solved my issue but I couldn't understand how to make it work for my use case. https://github.com/dominik791/obj-traverse A: Use DFS. const menuItems = [ { id: 1, imageUrl: "http://placehold.it/65x65", display: "Shop Women", link: "#", type: "image", nextItems: [ { id: 10, display: "홈", link: "#", type: "menuitem" }, { id: 20, display: "의류", link: "#", type: "menuitem-withmore", nextItems: [ { id: 100, display: "I'm inside one nest", link: "#", type: "menuitem" } ] }, { id: 30, display: "가방", link: "#", type: "menuitem-withmore", nextItems: [] }, { id: 40, display: "신발", link: "#", type: "menuitem-withmore", nextItems: [] }, { id: 50, display: "악세서리", link: "#", type: "menuitem-withmore", nextItems: [] }, { id: 60, display: "SALE", link: "#", type: "menuitem-withmore", style: "bold", nextItems: [] }, { id: 70, display: "브랜드", link: "#", type: "menuitem-withmore", nextItems: [] }, { type: "separator" }, { id: 80, display: "위시리스트", link: "#", type: "menuitem" }, { id: 90, display: "고객센터", link: "#", type: "menuitem" }, { id: 99, display: "앱 다운로드", link: "#", type: "menuitem" } ] }, { id: 2, imageUrl: "http://placehold.it/65x65", display: "Shop Men", link: "#", type: "image", nextItems: [ { id: 95, display: "MEN's ITEMS.", link: "#", type: "menuitem" } ] } ]; function dfs(obj, targetId) { if (obj.id === targetId) { return obj } if (obj.nextItems) { for (let item of obj.nextItems) { let check = dfs(item, targetId) if (check) { return check } } } return null } let result = null for (let obj of menuItems) { result = dfs(obj, 100) if (result) { break } } console.dir(result)
{ "pile_set_name": "StackExchange" }
Q: Using session variables to store expanding lists I'm working on an application where a user can input data: using an example, they can input a product name, a description, and a price. There are also two buttons: one button, "Add new product", will allow them to temporarily save all of the product data (NOT to the database) and allow them to input another information on a product; the other button, "Save changes", will save all of those products that were added via "Add new product". I'm completely new with session variables, but they look pretty similar to Viewbag/Tempdata/etc. But I'm trying to figure out if I can make a list from a session variable, and add a product to the list as the user presses "Add new product" until they hit "Save changes". Is this possible? A: Did a little hack for this. In my view model, I made a counter variable to keep track of the products and incremented it whenever the controller got called (IE, 1 for the first product they're adding, 2 for the second, etc.). So once the controller gets called when they click on the Add New Product button, I pass in the view model and check the counter variable. If it's == 1, I make a new list, append that item, and make a session variable equal to the list. Otherwise, if it's greater, I get the session variable that contains the list, append the item, and re-set the session variable. Probably needs to be cleared out at some point, but I'm getting there and this seems to work so far.
{ "pile_set_name": "StackExchange" }
Q: What font is used on Geographic Information Systems.SE? What's the font name used in the Geographic Information Systems.SE logo? A: Museo Slab. The same typeface is used as a web font on the site for titles, inspecting the styling applied to those elements will reveal which font is used: A: Looking at the CSS for the page reveals it to be Museo Slab 500. This is a free font from exljbris. http://www.exljbris.com/museoslab.html
{ "pile_set_name": "StackExchange" }
Q: PHP how to pipe a variable to netcat with shell_exec I want to send the content of a string (labeldata for barcode printer) to netcat for printing. I get it to work by writing the string to a file and using the code below. $file = 'out.prn'; file_put_contents($file, $normal_label); $prn_status = shell_exec('cat '.$file.' | netcat -w 1 192.168.31.10 8000'); but how can I do it directly from the variable? I've tried different things like shell_exec($normal_label > netcat... shell_exec($normal_label | netcat... A: For you script to work, you may change this line: $prn_status = shell_exec('cat '.$file.' | netcat -w 1 192.168.31.10 8000'); to this: $prn_status = shell_exec('echo '.$normal_label.' | netcat -w 1 192.168.31.10 8000'); But, instead of depending on netcat, you may also write to the TCP port directly with fsockopen. Then you script would also work on system that do not have netcat on it. More portable (yay): <?php $fp = fsockopen('192.168.31.10', 8000, $errno, $errstr, 30); if (!$fp) { echo "$errstr ($errno)<br />\n"; } else { $result = ''; fwrite($fp, $normal_label); while (!feof($fp)) { $result .= fgets($fp, 128); } fclose($fp); } echo $result;
{ "pile_set_name": "StackExchange" }
Q: Invalid argument deleting file I have made this very simpel program and all it needs to do is deleting a file #include <string> #include <iostream> #include <fstream> int main() { string x = "C:\Users\dino\Documents\profiles\fil.txt"; if(remove(x.c_str()) != 0) { perror("Error deleting "); } return 0; } But the perror gives me Invalid argument Can't i choose the directory of the file I want to delete? if not, is there another way i can? A: You need to escape your string. . . string x = "C:\\Users\\dino\\Documents\\profiles\\fil.txt";
{ "pile_set_name": "StackExchange" }
Q: Python: which is a fast way to find index in pandas dataframe? I have a dataframe like the following df = a ID1 ID2 Proximity 0 0 900000498 NaN 0.000000 1 1 900000498 900004585 3.900000 2 2 900000498 900005562 3.900000 3 3 900000498 900008613 0.000000 4 4 900000498 900012333 0.000000 5 5 900000498 900019524 3.900000 6 6 900000498 900019877 0.000000 7 7 900000498 900020141 3.900000 8 8 900000498 900022133 3.900000 9 9 900000498 900022919 0.000000 I want to find for a given couple ID1-ID2 the corresponding Proximity value. For instance given the input [900000498, 900022133] I want as output 3.900000 A: If this is a common operation then I'd set the index to those columns and then you can perform the index lookup using loc and pass a tuple of the col values: In [60]: df1 = df.set_index(['ID1','ID2']) In [61]: %timeit df1.loc[(900000498,900022133), 'Proximity'] %timeit df.loc[(df['ID1']==900000498)&(df['ID2']==900022133), 'Proximity'] 1000 loops, best of 3: 565 µs per loop 100 loops, best of 3: 1.69 ms per loop You can see that once the cols form the index then lookup is 3x faster than a filter operation. The output is pretty much the same: In [63]: print(df1.loc[(900000498,900022133), 'Proximity']) print(df.loc[(df['ID1']==900000498)&(df['ID2']==900022133), 'Proximity']) 3.9 8 3.9 Name: Proximity, dtype: float64
{ "pile_set_name": "StackExchange" }
Q: Taking informations from another site i am trying to get infos from another site. <td> <?php $site=file_get_contents("$link"); $price='#<div class="price_a">(.*?)<\/div>#si'; preg_match_all($price,$site,$pricelist); for ($a=0; $a<1; $a++){ echo $pricelist[1][$a]; } ?> </td> <td> <?php $site=file_get_contents("$link"); $price='#<div class="price_a">(.*?)<\/div>#si'; preg_match_all($price,$site,$pricelist); for ($a=1; $a<2; $a++){ echo $pricelist[1][$a]; } ?> </td> But in the source code there are also tags like <div class="price_m"> or <div class="price_n"> How can i take all tags from this site and use it in tags? Thanks... A: Not sure if I understood you properly, but why not just use a wildcard on the class name, too? <td> <?php $site=file_get_contents("$link"); $price='#<div class="price_[a-z]">(.*?)<\/div>#si'; preg_match_all($price,$site,$pricelist); for ($a=0; $a<1; $a++){ echo $pricelist[1][$a]; } ?> </td> <td> <?php $site=file_get_contents("$link"); $price='#<div class="price_[a-z]">(.*?)<\/div>#si'; preg_match_all($price,$site,$pricelist); for ($a=1; $a<2; $a++){ echo $pricelist[1][$a]; } ?> </td>
{ "pile_set_name": "StackExchange" }
Q: Compare 3 values within certain percentage of each other I am trying to make this: 3 input boxes take the value of the input and compare to a certain percentage if values are within 3% of each other. output = something else output something else. any help would be appreciated on getting started. A: First create the inputs which on a basic level looks like this: <input type="text" width="3em"> That will create a single input tag. So, placing three, or however many, will create the inputs. Now, we need a way to get the inputs we just created. To do this we'll need some JavaScript. document.getElementsByTagName("input"); This will get us all input tags on the screen. Now, we can iterator through these tags and get the data we need in which I will place into an array. Note: Each input tag has a property called value which stores the string placed inside of the input which can be changed to a number by placing a + in front. var numbers = [], inputs = document.getElementsByTagName("input"); for(var i = 0; i < inputs.length; ++i) { var number = +inputs[i].value; // Makes sure that a number is there. if(!isNaN(number)) numbers.push(number); } Now that we have everything in an array, time for some math! Let us look at an easy example of comparing the percentage off a particular number is from another. If we are given 7 and 3 how far off are they from each other? First we find the average -> (7 + 3) / 2 then we find the difference between |3 - 7| then we divide the difference by the average ... 4 / 5 = .8. Yay! But, what about three numbers? Well, now we must do that between every number... Then we check each one to see if within range. Yuck! To do this it will require an embedded for loop. So, we need to have an embedded for loop such that we do not repeat comparisons. Just like the following: numbers => 1 2 3 4 Compare 1 -> 2, 1 -> 3, 1 -> 4 Compare 2 -> 3, 2 -> 4 Compare 3 -> 4 Stop! This brought me to this mess: var inrange = true, tolerance = 3/*In percentage!*/; for(var i = 0; i < numbers.length && inrange; ++i) for(var j = i + 1; j < numbers.length && inrange; ++j) { var diff = (numbers[i] - numbers[j]), // Need to make sure diff is positive. Could use Math.abs... pdiff = 2 * (diff < 0 ? -1*diff : diff) / (numbers[i] + numbers[j]); // If false will cause the loops to stop. inrange = (100 * pdiff) <= tolerance; } With the calculation function we can now focus on the display! Now, we need a button that will call to a function and do the magic for us! This can be done with the input tag as well, but by changing its type. <input type="submit" value="calculate" onclick="calculate()"> So, now we need a way to display... A really easy way is to have a <p> tag with an id. <p id="display"></p> To get this tag, we can use some JavaScript as well. document.getElementById("display"); These tags have an attribute called innerHTML in which we can edit to do, well..., change the inner HTML. var p = document.getElementById("display"); p.innerHTML = "Hello World!"; Now, we can combine everything above to get: <input type="text" width="3em"> <input type="text" width="3em"> <input type="text" width="3em"> <input type="submit" value="calculate" onclick="calculate()"> <p id="display"></p> <p id="results"></p> <script> // The tolerance for the numbers to be within. var tolerance = 3, // The number of inputs expected. amount = 3; function calculate() { var numbers = [], inputs = document.getElementsByTagName("input"); // Gets all of the numbers. for(var i = 0; i < inputs.length; ++i) // Need to check type to make sure not getting the button. if(inputs[i].type === "text"){ var number = +inputs[i].value; if(!isNaN(number)) numbers.push(number); } // Need to make sure the correct amount of inputs were found. if(numbers.length !== amount) return; var inrange = true, // Gets the results p tag. results = document.getElementById("results"); // Clear old results. results.innerHTML = ""; // Compares each number finding the avg percent difference. for(var i = 0; i < numbers.length && inrange; ++i) for(var j = i + 1; j < numbers.length && inrange; ++j) { var diff = (numbers[i] - numbers[j]), pdiff = 2 * (diff < 0 ? -1*diff : diff) / (numbers[i] + numbers[j]); inrange = (100 * pdiff) <= tolerance; results.innerHTML += "Input " + (i+1) + " to " + (j+1) + ": " + (100 * pdiff) + " " + (inrange ? "<=" : ">") + " " + tolerance + " <br>"; } // Gets the display tag. var p = document.getElementById("display"); // Makes sure that within tolerance! if(inrange) p.innerHTML = "Within tolerance!"; else p.innerHTML = "Try again..."; } </script> A function I use to limit the amount of digits shown where x is the number and n is the number of digits. This can be used on the display of the results. To use, simply take the results.innerHTML += ... + (100 * pdiff) + ... and place the function results.innerHTML += ... + limit_decimal(100 * pdiff, #) + ... where # is the number of decimals you want. function limit_decimal(x, n) { // Makes sure it is a number. if(isNaN(x = +x)) return x; // If n is not a number then set to zero. isNaN(n = +n) && (n = 0); // Makes x a string. var s = x + "", // Split the string up by the decimal. parts = s.split("."); // Return the first part if n is zero. if(n === 0) return parts[0]; // If just the first part, place zeros. if(parts.length === 1) { s += "."; for(var i = 0; i < n; ++i) s += "0"; return s; } // If not, then get the length. var l = parts[1].length; // If the length is larger than n, remove those. if(l >= n) { return parts[0] + "." + parts[1].slice(0,n); } // Else, add zeros to fit the length. for(var i = 0; i < n - l; ++i) s+="0"; return s; }
{ "pile_set_name": "StackExchange" }
Q: Android Studio: Early Access Java versions may cause compatibility issues What is the recommended Java version for Android Studio v1.0.2? The official system requirements only specifies JDK 7 for v1.0.2 However, after selecting jdk1.7.0_71 (by navigating through: Configure -> Project Defaults -> Project Structure), the Android Studio Welcome page still warns: Early Access Java versions may cause compatibility issues. Please use stable release. I don't know if the Java compatibility is the reason, but Android studio has many bugs, the most consequential being the ineffective OK/Done button in many dialogs of Android Studio! Eg: After selecting the Eclipse project in the "Import from Non-Android Studio project" dialog, I press the OK button, but the dialog closes without any effect! A: For Android Studio 1.0.2 a JRE above 7 is incompatible. Update: But as commented by @Jackson: Android 1.5.1 works with JRE 8 but complains The basic logic is that the JDK has nothing to do with Android Studio runtime functioning. Instead, it seems that it uses the Java Runtime environment for Android Studio runtime and the JDK only for the development resources. This means that even though Android Studio points to a JDK 7, it will still show the "Early access Java versions" error if you have a JRE above 7 (in this case I had JRE 8 installed)
{ "pile_set_name": "StackExchange" }
Q: Actionscript 3 Sprite AddChild Im new to actionscript 3 and am a little confused about how the addchild function works. I want to draw 5 houses. each house has a roof and wall. Each wall has a door and a window. I have the following classes and this is how I grouped them class Main class House class Roof //a triangle class Wall //a rectangle class Door //a rectangle class Window //a square Im having trouble with inheritance of the classes. I cant made the wall class show up with a window and a door. Can someone point me to the right direction? UPDATE: This is the part I do not understand. How can I write it so that it draws the door and window relative to the wall? (use the top left corner of wall as 0,0; instead of the screen) A: I hope this helps // MAIN FLA import House; var house:House = new House(); addChild(house); package { import flash.display.Sprite; import Roof; import Wall; public class House extends Sprite { protected var wall:Wall; protected var roof:Roof; function House() { wall = new Wall(); roof = new Roof(); this.addChild(roof); this.addChild(wall); // The wall should be below the roof wall.y = roof.height + roof.y; } } } package { import flash.display.Sprite; public class Roof extends Sprite { function Roof() { } } } package { import flash.display.Sprite; import Door; public class Wall extends Sprite { protected var door :Door; function Wall() { door = new Door(true); this.addChild(door); // Door is centered. door.x = (this.width - door.width)/2; // Door is flush with bottom of the wall. door.y = this.height - door.height; } } } package { import flash.display.Sprite; import Windoe; public class Door extends Sprite { protected var win :Windoe; function Door(hasWindow:Boolean = false) { if(hasWindow) { win = new Windoe(); this.addChild(win); // The window should be centered? win.x = (this.width - win.width)/2; win.y = 20; // Just a guess. } } } } package { import flash.display.Sprite; // The word Window may be reserved, so using Windoe just to be safe public class Windoe extends Sprite { function Windoe() { } } }
{ "pile_set_name": "StackExchange" }
Q: Trying to make a peak voltage adapter I'm trying to make a PVA using the following schematic: I have put something together that looks like: Obviously the input at the top will have positive lead going into the diode and the negative lead on the other side. Is this correct, I have little knowledge and not really sure about schematics. I want to use this to test my ignition system. If it's wrong could someone point out what needs to be changed or draw a simplified version (I understand the schematic may be as simple as it gets) or alter the image of my PVA so it's usable? A: You haven't connected together what you think you have. The positive sides of the resistor and capacitor aren't connected to each other. You're missing a jumper wire between them.
{ "pile_set_name": "StackExchange" }
Q: Graphics card not under load when playing games I just got a new computer with an i7 4790k and GTX 770, however am very disappointed with performance. I was getting bad framerates on League of Legends on Very High and just now I booted Mirror's Edge, an old-ass game, and it was running at a very low framerate on high settings. A friend suggested it sounds like the graphics card isn't being used, and sure enough using GPU-Z to monitor while playing Mirror's Edge the GPU was under 0% load (it was still available to monitor though so I guess it's connected fine). I also definitely have the latest drivers installed. Monitor-wise I have a Samsung 1080p monitor connected over VGA (only came with that and it seemed to look fine) and a Sony 1080p TV over HDMI for sound and extra screen space, however I only game on the one monitor. Both are plugged into the motherboard jacks so I could use Intel's software to manage their relative positions etc. I would't think this would affect much though right? I would assume the graphics card provides extra processing no matter what is plugged into it. What do? A: I'm an idiot and not plugging things into the graphics card does indeed mean it's not being used. Solution: go buy another HDMI cable. UPDATE: Bought an HDMI to DVI cable and graphics card is now under load when playing games, and can run Mirror's Edge at max settings with no noticeable frame issues. Not much of a claim to fame but it's the only thing I have to test with right now :P I just assumed the graphics card provides additional graphics processing no matter where the displays are plugged in, and wasn't tied to rendering the output to a display specifically. I guess I assumed wrong.
{ "pile_set_name": "StackExchange" }
Q: Find $\arctan(\sqrt{2})-\arctan\left(\frac{1}{\sqrt{2}}\right)$ I did it as follows: $$\arctan(\sqrt{2})-\arctan\left(\frac{1}{\sqrt{2}}\right)=\tan\Bigg(\arctan(\sqrt{2})-\arctan\left(\frac{1}{\sqrt{2}}\right)\Bigg)=\frac{\sqrt{2}-\frac{1}{\sqrt{2}}}{1+\frac{1}{\sqrt{2}}\sqrt{2}}=\frac{\sqrt{2}}{4}.$$ But there is no such an answer. What is wrong with it? A: The angle you are looking for is the red angle: $$\arctan\sqrt{2}-\arctan\frac{1}{\sqrt{2}} = \arctan\left(\frac{\sqrt{2}-\frac{1}{\sqrt{2}}}{1+1}\right)=\color{red}{\arctan\frac{1}{\sqrt{8}}} $$
{ "pile_set_name": "StackExchange" }
Q: Would Mind Uploaded People on Fast Computers have any Unique Skills or Knowledge? In my setting, there are basically no biological life forms left, as everyone has either been mind-uploaded or is an artificial intelligence. It is supposed to take place at a very distant point in the future post Andromeda-Milky Way merger, so technology has had a long time to develop and the computers people are stored in are at speeds approaching theoretical limits (as set by Bremermann's limit) of 1.36e50 computations a second per kg of material. What I am struggling with is whether or not everyone would know exactly the same facts and skills as everyone else. If everyone is stored in a separate computer with arbitrarily high computations per second allowed for each individual, I worry that whenever any question comes up they could simply "google" the answer instantly and no one would have any knowledge not known by someone else. Is there any pragmatic reason (not based on personal taste of the individual) for having specializations such as "Scientist", "Engineer", etc. within such a society? What could prevent individuals from all having the same skills and knowledge? A: Let's break this down. 1. Knowledge != Skill You can know everything there is to know about painting, and still be a bad painter. In fact, most critics of any field fall into this category. You can know something very well without being able to actually do it. Sure, your society is in the far future and we've collectively learnt a lot, but that doesn't still mean individuals being good at something depends on knowledge alone. In this far in the future, we're talking about intergalactic levels of engineering, which will definite pose challenges even to the most advanced, and those individuals will still have to think creatively to find solutions. 2. Sometimes imagination is better (powerful) than information The best example for this is Einstein. All the leading scientists in his time knew all the major things about physics and cosmology. But it was Einstein who could actually come up with the Theory of Relativity, which is almost completely a product of pure imagination. What sets him apart? We don't know for sure - yes he's probably more intelligent than your average scientist, but what does 'intelligence' mean? It's correlated with information/knowledge for sure, but there's much more to it than that. So in your future, people who could imagine new things are the scientists. 3. We can't know everything How far advanced we may be, there's still some knowledge that is likely fundamentally unknowable. For example, take the age old question, What's beyond our universe? It may be that we're only one of infinitely many universes, but it could be that because of the limitations of physics we simply can't know anything about what's beyond our universe. And that's jut one example, there could be many more things like that. So even with all the knowledge in the universe, you still can't know everything. In such cases, individualistic abilities to think, imagine, and be creative can be useful. A: Looks like you posited universal sharing of information - does that have to be the case? Even with tremendous computation powers, raw knowledge is still valuable (maybe even more so), so if there are still independent agents with free will, they may choose to control and protect their knowledge for their advantage. This leads to a question - why cannot everyone gather raw knowledge? Because that is gained from physical interaction with the real world, not from navel gazing. So controlling more physical objects is still a source of power. Those can be thought as extended bodies - but do not have to be physically connected. In fact, it's quite feasible that a single independent mind can control significant armies of distributed "dumb" robots (those without free will). Those private "bodies", coupled with private knowledge (which they help to gain), form the answer to specialization and in fact to individuality.
{ "pile_set_name": "StackExchange" }
Q: Making Large IndexedDB Persistent in Browser I am looking at making a LOB html5 web application. The main part we are trying to accomplish is to make the application offline capable. This will mean taking a large chunk of SQL data from the server and storing it in the browser. This will need to be living in the browser for quite a while, dont want to have to continuously refresh it everytime the browser is closed and reopened. We are looking at storing the data inside the client in indexedDB but I read that indexedDB is stored in temporary storage so the lifetime of it cannot be relied on. Does anyone know of any strategies on prolonging its lifetime? Also we will be pulling down massive chunks of data so 1-5mb storage might not suffice what we require. My current thought is to somewhat store it down to the browser storage using html5 storage API's and hydrate it into the indexedDb as it's required. Just need to make sure we can grow the storage limit to whatever we need. Any advice on how we approach this? A: We are looking at storing the data inside the client in indexedDB but I read that indexedDB is stored in temporary storage so the lifetime of it cannot be relied on. That is technically true but in practice I've never seen the browser actually delete data. More common if you're storing a lot of data, you will hit quota limits which are annoying and sometimes inconsistent/buggy. Regardless, you shouldn't rely on data in IndexedDB always being there forever, because users can always delete data, have their computers break without backups, etc.
{ "pile_set_name": "StackExchange" }
Q: render list from json data from url on ReactJS I want to render list from json data from url on ReactJS THis is the data on loaclhost 10.0.10.10/3000 confused to use axios or fetch { "users": [{ "_id": "7odGhvEvLBYtQujdZ", "createdAt": "2019-07-23T10:48:01.438Z", "username": "123", "profile": { "active": "true" } }, { "_id": "dgBWJ4qBNx94MketL", "createdAt": "2019-07-23T15:33:34.270Z", "username": "user1", "profile": { "active": "true" } }, { "_id": "hNTnjMEXdn5gbNSGZ", "createdAt": "2019-07-23T16:16:56.070Z", "username": "user2", "profile": { "active": "true" } }, { "_id": "porAsWJ3ba48JnLPd", "createdAt": "2019-07-23T10:21:05.541Z", "username": "user3" }, { "_id": "f6NJpu8rggfGmYJEY", "createdAt": "2019-07-30T11:47:54.652Z", "username": "usre4", "profile": { "active": true } }, { "_id": "anZQB6PsfuatCGxA6", "createdAt": "2019-07-30T11:44:55.997Z", "username": "user5", "profile": { "active": true } } ] } i want a simple way to dispay this data in list or table in reactJS. using axios or fetch. A: Use Array.map to render your template for each entry class ListComponent extends Component { constructor(props) { super(props); this.state = { articles: [], } } async componentDidMount() { fetch('https://jsonplaceholder.typicode.com/todos/') .then(response => response.json()) .then(json => { this.setState({ articles: json, }) }) } render() { return ( this.state.articles.map(row => <div key={row._id}>{row.username}</div>) ) } }
{ "pile_set_name": "StackExchange" }
Q: Passing array by refence in Angular 5 I am trying to learn Angular 5, I created a sample project (Blog where I display posts), here the service for the posts: export class PostService { posts = [ { title: "Post 1", content: "bla bla bla", loveIts: 0, created_at: new Date, }, { title: "Post 2", content: "bla bla bla", loveIts: 0, created_at: new Date, }, { title: "Post 3", content: "bla bla bla", loveIts: 0, created_at: new Date, }, ]; getPosts() { return this.posts; } setLoveItsToDefault() { for (let post of this.posts) { post.loveIts = 0; } } initializeLovesPost(i: number) { this.posts[i].loveIts = 0; } } And in AppComponent, I inject the service, and I try to update all posts (if they have more than 1 love/like, then I set it to 0): export class AppComponent { @Input() posts : Post[]; constructor(private postService: PostService) { } ngOnInit() { this.posts = this.postService.getPosts(); } onInitializeLoves() { if (confirm('Are you sure to initialize all loves of all posts to 0 ?')) { this.postService.setLoveItsToDefault(); } else { return null; } } } In the html code: <button class="btn btn-primary" (click)="onInitializeLoves()">Initialize loves</button><br><br> <ul class="list-group"> <app-post [posts]="posts"></app-post> </ul>> Here I use posts (PostListComponent, selector: 'app-post'): export class PostListComponent implements OnInit { @Input() posts: Post; constructor(private postService: PostService) { } } The html for this component: <app-post-item *ngFor="let post of posts" [postTitle]="post.title" [postContent]="post.content" [postCreatedAt]="post.created_at" [postLoveits]="post.loveIts"> </app-post-item> And here the last component PostListItemComponent who display each post: export class PostListItemComponent implements OnInit { @Input() postTitle: string; @Input() postContent: string; @Input() postLoveits: number; @Input() postCreatedAt: Date; constructor() { } getPadding() { return '0px'; } onAddLoveIt() { this.postLoveits++; } onAddDontLoveIt() { this.postLoveits--; } } Here where I use loves/likes: <li [ngClass]="{'list-group-item': true, 'list-group-item-success': postLoveits > 0, 'list-group-item-danger': postLoveits < 0}"> <div class="row"> <div class="col-md-12"> <div class="col-md-6" [ngStyle]="{'padding-left': getPadding()}"><h3 class="pull-left">{{ postTitle }}</h3></div> <div class="col-md-6"><h3 class="pull-right">{{ postCreatedAt | date: 'dd/MM/y h:m' }}</h3></div> </div> </div> <p>{{ postContent }}</p> <button class="btn btn-success" (click)="onAddLoveIt()">Love it!</button> <button class="btn btn-danger" (click)="onAddDontLoveIt()">Don't love it!</button> Everything works fine without error, but if the posts have loves/likes, if i do console.log then I see they are initialized to 0, but in my page nothing changes, so here I am not sure if I have to render the array again, or to pass it by reference (I know in angular the array is passed by reference by default) ? In the tutorial I am following, he just made the same way I made, and it was working... Update Here a link for github repository, to see the full code. A: In your PostListItemComponent, the input values are copies of the corresponding Post properties: <app-post-item *ngFor="let post of posts" [postTitle]="post.title" [postContent]="post.content" [postCreatedAt]="post.created_at" [postLoveits]="post.loveIts"> </app-post-item> export class PostListItemComponent implements OnInit { @Input() postTitle: string; @Input() postContent: string; @Input() postLoveits: number; @Input() postCreatedAt: Date; ... } Changes to the source data (the items of the array) would update the values in the component, thanks to one-way data binding, but changes to the values in the component will not modify the source data. Here is what I think happens when you click on the buttons to add/remove a "love" on a post: The value of postLoveIts is modified in the component The source data (the loveIts property of the Post) remains unchanged Due to the data binding, Angular updates postLoveIts with the source data The view keeps showing the original post.loveIts value In order to keep a reference to the item of the Post array, and to make sure that any change in the component modifies the source data, you could pass the Post itself to the PostListItemComponent: <app-post-item *ngFor="let p of posts" [post]="p"></app-post-item> and refer to its properties in code: export class PostListItemComponent { @Input() post: Post; onAddLoveIt() { this.post.loveIts++; } onAddDontLoveIt() { this.post.loveIts--; } } and in the template: <li [ngClass]="{'list-group-item': true, 'list-group-item-success': post.loveIts > 0, 'list-group-item-danger': post.loveIts < 0}"> <div class="row"> <div class="col-md-12"> <div class="col-md-6" [ngStyle]="{'padding-left': getPadding()}"><h3 class="pull-left">{{ postTitle }}</h3></div> <div class="col-md-6"><h3 class="pull-right">{{ post.created_at | date: 'dd/MM/y h:m' }}</h3></div> </div> </div> <p>{{ post.content }}</p> <button class="btn btn-success" (click)="onAddLoveIt()">Love it!</button> <button class="btn btn-danger" (click)="onAddDontLoveIt()">Don't love it!</button> Note: If the post input value has any chance of being undefined or null, you can use the safe navigation operator ?. in the template to avoid runtime errors (e.g. post?.loveIts > 0). By the way, the posts input property in PostListComponent should be defined as an array: @Input() posts: Post[];
{ "pile_set_name": "StackExchange" }
Q: Small worlds under ground and mummies Reading the rules for mummies: Mummies Mummies are everywhere but they tend to trip over themselves, what with all those bandages! All your conquests require 1 more Mummy token than usual I know you get 10 to start with, but is there a good side? Or is the idea to wait until it has a rather large pile of coins? How are you supposed to play mummies to maximum effect? A: The fact that there are 10 is the good side. This is similar to other races from the base Small World and its expansions. For example, ratmen get a larger number of tokens with no downside. Kobolds (never leave a kobold token alone), barbarians (no redeployment) and pixies (only 1 stays on the board in each region) all have even larger token numbers but have some kind of downside that let them play differently. Kobolds are good at spreading fast but only hold a normal amount of territory. Barbarians spread fast over lots of territory but can't defend it strategically. Pixies are like barbarians on steroids; even more tokens but even less ability to defend. Mummies are similar; they get more tokens, allowing them to hold lots of territory, but they have a downside that makes them spread out more slowly. This can go well with powers that reward them for holding particular regions (the territory powers), or that want them to stick together (frightened). It also does well with certain powers, such as Tomb, by making the race much more resilient in decline. If you get a power or other ability that makes attacking easier (such as the rabbit sword), they can spread more quickly and hold more total territory. Mummies are good when your goal is to build up a strong board presence, where consistency is more important than speed. As such, you generally don't want them as your first race unless they have a strong power combo. They'll do well when your previous declined race is still going strong, taking time to spread wide into their own large decline. Reborn is a great combo for your previous race, helping mummies spread quickly and then minimising the loss of previous pieces when they're ready to decline. Additionally, as you mention, if the mummies aren't a great pick for the current game situation, they'll accumulate money as people skip them, making them more valuable later on.
{ "pile_set_name": "StackExchange" }
Q: Rate limiting algorithm for throttling request I need to design a rate limiter service for throttling requests. For every incoming request a method will check if the requests per second has exceeded its limit or not. If it has exceeded then it will return the amount of time it needs to wait for being handled. Looking for a simple solution which just uses system tick count and rps(request per second). Should not use queue or complex rate limiting algorithms and data structures. Edit: I will be implementing this in c++. Also, note I don't want to use any data structures to store the request currently getting executed. API would be like: if (!RateLimiter.Limit()) { do work RateLimiter.Done(); } else reject request A: The most common algorithm used for this is token bucket. There is no need to invent a new thing, just search for an implementation on your technology/language. If your app is high avalaible / load balanced you might want to keep the bucket information on some sort of persistent storage. Redis is a good candidate for this. I wrote Limitd is a different approach, is a daemon for limits. The application ask the daemon using a limitd client if the traffic is conformant. The limit is configured on the limitd server and the app is agnostic to the algorithm.
{ "pile_set_name": "StackExchange" }
Q: jquery tablesorter not sorting hello i am stuck with jquery tablesorter: http://tablesorter.com/docs/index.html#Examples and would be grateful if some jquery guru could check my code to see where i am going wrong. instead of displaying 10 records per page it is displaying all records and also when i try to sort it does nothing. in addition to that, there are no zebra stripes appearing. all libraies are loaded and there are no errors in firebug. many thanks for your help. <?php $q=$_GET["q"]; $con = mysql_connect('localhost', 'root', ''); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("sample", $con); $sql="SELECT * FROM logger_log WHERE idusr_log = '".$q."' order by datein_log desc"; $result = mysql_query($sql); echo "<table id=\"userlog\" class=\"tablesorter\"> <thead> <tr> <th align=\"left\">Ip Address</th> <th align=\"left\">Date In</th> <th align=\"left\">Date Out</th> </tr> </thead>"; while($row = mysql_fetch_array($result)) { echo "<tbody>"; echo "<tr>"; echo "<td>" . $row['ip_log'] . "</td>"; echo "<td>" . date('d/m/Y H:i:s',strtotime($row['datein_log'])) . "</td>"; echo "<td>" . date('d/m/Y H:i:s',strtotime($row['dateout_log'])) . "</td>"; echo "</tr>"; echo"</tbody>"; } echo "</table>"; mysql_close($con); ?> <div id="pager" class="pager"> <form> <img src="css/blue/first.png" class="first"/> <img src="css/blue/prev.png" class="prev"/> <input type="text" class="pagedisplay"/> <img src="css/blue/next.png" class="next"/> <img src="css/blue/last.png" class="last"/> <select class="pagesize"> <option selected="selected" value="10">10</option> <option value="20">20</option> <option value="30">30</option> <option value="40">40</option> </select> </form> </div> <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="js/jquery.tablesorter.min.js"></script> <script type="text/javascript" src="js/jquery.tablesorter.pager.js"></script> <link href="css/blue/style.css" rel="stylesheet" type="text/css" /> <script> $(document).ready(function() { $("#userlog") .tablesorter({widthFixed: true, widgets: ['zebra']}) .tablesorterPager({container: $("#pager")}); } ); </script> A: You need to remove the <tbody> fom your results loop and place it around your while loop. echo "<tbody>"; while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['ip_log'] . "</td>"; echo "<td>" . date('d/m/Y H:i:s',strtotime($row['datein_log'])) . "</td>"; echo "<td>" . date('d/m/Y H:i:s',strtotime($row['dateout_log'])) . "</td>"; echo "</tr>"; } echo"</tbody>"; echo "</table>";
{ "pile_set_name": "StackExchange" }
Q: Tomcat - making a project folder the web root I have this folder under Tomcat webapps/mysite which is where all my JSPs and other things are located. To access this folder I go to http://blah.com/mysite and it works just fine. However (because of stylesheets and images statically connected to the root /) I have to make it so that when I go to http://blah.com/ it will load the stuff inside webapps/mysite. I've tried many different things including contexts and setting the absolute path in server.xml... nothing seems to work, whenever I go to http://blah.com/ it still tries to load the ROOT folder... what's happening here? A: The solution I use is to set this in your Tomcat server.xml Add a <Context> element within the <Host> like below which sets your mysite as the default web app. Note the empty path="" which makes it the default. <Context docBase="mysite" path="" /> Attributes of Context Container from the Tomcat docs: docBase You may specify an absolute pathname for this directory or WAR file, or a pathname that is relative to the appBase directory of the owning Host. path All of the context paths within a particular Host must be unique. If you specify a context path of an empty string (""), you are defining the default web application for this Host, which will process all requests not assigned to other Contexts. See others who have had similar question and the similar answer here, here and here See also Apache Tomcat Configuration Reference - Context
{ "pile_set_name": "StackExchange" }
Q: What's the reason i have to use jsonp? What's the reason i have to use jsonp? A few days ago i asked why i have no response from a rest server with jquery. The reason was that i must use JSONP. I tested that with a own server and it worked. Now i have to convince my college's who have control of the right server that the output have to be JSONP instead of json. Only i don't now exactly why i must use JSONP? And is this only a jquery problem or is it not possible with javascript at all? Can anyone help me with these questions? Thanks A: JSONP is used to get data via AJAX cross-domain. Well, not exactly, JSONP is actually a bit of a "hack". AJAX requests only work on the same domain, but <script> tags can be included from any domain. This is what JSONP is, it's actually a Javascript file, that gets added as a <script> tag. That's why in JSONP, it's callback({data: value}), this is a script that gets executed. A: If the AJAX request is being made to an URL that falls under the so called Same origin policy, it will normally fail in most browsers due to built-in browser restrictions. But if you are on the same domain, protocol and port as your colleges server, you don’t need JSONP to make AJAX requests, you can just go ahead using the standard AJAX tools. If you are not, JSONP is an industry-standard technique of working around the same origin policy, but it also requires that the server delivers data in a special way to make it available for the client.
{ "pile_set_name": "StackExchange" }
Q: Issue in Embark command 'embark ipfs' I am using Embark version 2.1 .I have used the command 'embark ipfs' but it returns the following error. /usr/local/bin/ipfs /home/toshiba/.nvm/versions/node/v6.9.1/lib/node_modules/embark/node_modules/solc/soljson.js:1 (function (exports, require, module, __filename, __dirname) { var Module;if(!Module)Module=(typeof Module!=="undefined"?Module:null)||{};var moduleOverrides={};for(var key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var ENVIRONMENT_IS_WEB=typeof window==="object";var ENVIRONMENT_IS_WORKER=typeof importScripts==="function";var ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof require==="function"&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;var ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;if(ENVIRONMENT_IS_NODE){if(!Module["print"])Module["print"]=function print(x) {process["stdout"].write(x+"\n")};if(!Module["printErr"])Module["printErr"]=function printErr(x){process["stderr"].write(x+"\n")};var nodeFS=require("fs");var nodePath=require("path");Module["read"]=function read(filename,binary){filename=nodePath["normalize"](filename);var ret= ReferenceError: build_dir is not defined at IPFS.deploy (/home/toshiba/.nvm/versions/node/v6.9.1/lib/node_modules/embark/lib/ipfs.js:16:37) at Object.ipfs (/home/toshiba/.nvm/versions/node/v6.9.1/lib/node_modules/embark/lib/index.js:265:10) at Command.<anonymous> (/home/toshiba/.nvm/versions/node/v6.9.1/lib/node_modules/embark/lib/cmd.js:136:17) at Command.listener (/home/toshiba/.nvm/versions/node/v6.9.1/lib/node_modules/embark/node_modules/commander/index.js:301:8) at emitTwo (events.js:106:13) at Command.emit (events.js:191:7) at Command.parseArgs (/home/toshiba/.nvm/versions/node/v6.9.1/lib/node_modules/embark/node_modules/commander/index.js:615:12) at Command.parse (/home/toshiba/.nvm/versions/node/v6.9.1/lib/node_modules/embark/node_modules/commander/index.js:458:21) at Cmd.process (/home/toshiba/.nvm/versions/node/v6.9.1/lib/node_modules/embark/lib/cmd.js:19:11) at Object.process (/home/toshiba/.nvm/versions/node/v6.9.1/lib/node_modules/embark/lib/index.js:31:9) How can i solve this issue? A: This has been fixed in 2.2.0, please update to 2.2.0 and use the new command embark upload ipfs. you'll need to have a ipfs node running.
{ "pile_set_name": "StackExchange" }
Q: Joomla! add script in document head from article We have a couple of pages that require special care, jquery-ui will be called from external scripts which are going to "somehow" be added to the head section of an article. I've attempted with jumi, however it isn't the best choice(including a js in stead of php would render it in html body), the only way I could add a javascript file was by including a php file which would echo a , but as one would imagine, this isn't elegant nor efficient in terms of performance. Another attempt was, in stead of echoing a script, I've tried using: <?php $document = &JFactory::getDocument(); $document->addScript( "path/to/jsfile.js" ); ?> but it didn't work as I've expected, it seems that joomla creates the head section before this php script has the chance of being executed. I've also gave easy header a go, however, it seems that it will include the files in all articles, which I do not wish since it will have a pretty big impact in terms of bandwidth and possible javascript issues down the road. I'm farily new to joomla so anything that would provide some flexibility is good as an answer. If something isn't unclear, please ask, I will try to answer the best I can. Please note that I'm using joomla 1.7 and php5. A: Jumi uses the onAfterRender event (looking at the 2.0.6 plugin) - by this time I think the <head> tag has already been written out, in-fact the whole document is already rendered. You could try getting the document body and then searching for the closing tag </head> and inserting the script link before it. Something like this: $myJS = "<script type='text/javascript' src='http://mysever.com/my.js'>" $content = JResponse::getBody(); // gets the html in it's ready to send to browser form $hdPos = strpos($content, '</head>'); $hdPos += 7; //move position to include the <head> tag $bodyLen = strlen($content); $content = substr($content, 0, $hdPos) . $myJS . substr($content, $hdPos, $bodyLen); JResponse::setBody($content); NB: This is untested and I don't use Jumi these days but it should be close.
{ "pile_set_name": "StackExchange" }
Q: Entity Wrapper : how to delete multiple values field? I have a multiple values field on the user entity. This field is field_data. There are several values in this field. I want to delete all of them. I tried the following code: for ($i = 0; $i < count($user->field_data->value()); $i++) { $user->field_data[$i]->delete(); } But I get errors about ->delete() not being a method on this object. I also tried with ->clear() to no avail. I've been looking for examples on Google for how to do this, but my Google-fu is not so strong today. A: Well, I solved it. The answer is kind of tricky. You can't delete a value in a multiple values field. However, you can set it to "empty". When it's empty, it's removed. Here is the code to use: // Also, note the ->count() method for ($i = 0; $i < $user->field_data->count(); $i++) { $user->field_data[$i]->set(); } This way, values are now empty and the multiple fields have no value left. It's well shown in the UI too and the deltas are correctly handled in the database.
{ "pile_set_name": "StackExchange" }
Q: Accessibility of data member in member function before declaration of data member Consider this code: class Test { public: Test() { i = 0; } private: int i; }; Data member 'i' is used even before it is declared/defined. Should this not be a compilation error ? (It compiled fine!!!) A: The rule is that member functions defined in the class definition are compiled as if they were defined immediately after the class definition.
{ "pile_set_name": "StackExchange" }
Q: php code to display none? I'm sure this is fairly simple but I really don't get php is there a way to have the below code to display none if there's no url details entered? <div class="details"> <h3>web</h3> <div>URL: <span><a href="<?=$website_url?>"><?=$website_url?></a></span></div> </div> Thanks A: Wrap it in an if statement. <? if($website_url): ?> <div class="details"> <h3>web</h3> <div>URL: <span><a href="<?=$website_url?>"><?=$website_url?></a></span></div> </div> <? endif;?> EDIT This might be better: <?php if($website_url){ ?> <div class="details"> <h3>web</h3> <div>URL: <span><a href="<?php echo $website_url; ?>"><?php echo $website_url; ?></a></span></div> </div> <?php } ?>
{ "pile_set_name": "StackExchange" }
Q: Improving my search method I have created a program that allows the user to input either a Dvd collection or a book collection. I am fairly happy with what I have managed to achieve (still fairly new to programming) but I have an annoyance with my search method. The search does work and returns what the user looks for but it then also prints out that nothing could be found afterwards. The reason being, I think, that the way I have written my code, means that each search parameter is read before ending and returning back to the menu. I think that I maybe need to use a boolean or similar to end the loop when the conditions of the search are met. I am sure that any experienced programmers will be shaking their head at my code... The search method: /** * Asks user to input Dvd title then compares * with Dvd titles in collection * @param none * @return none */ public void searchDvd() { String temp = ""; // Temporary variable to hold dvd title System.out.println ("\nPlease enter Dvd Title (full title) to search for: "); temp= Genio.getString(); if(temp.equals(dvd1.getTitle())) { clrscr(); System.out.println("\nDvd is present in collection at location 1 (Dvd 1 in collection):\n\nTitle: " + dvd1.getTitle() + " \n Director: " + dvd1.getDirector() + " \n Lead Act: " + dvd1.getLead() + " \n Run Time: " + dvd1.getRunTime() + " \n Price: " + dvd1.getDvdPrice()); pressKey(); } if(temp.equals(dvd2.getTitle())) { clrscr(); System.out.println("\nDvd is present in collection at location 2 (Dvd 2 in collection):\n\nTitle: " + dvd2.getTitle() + " \n Director: " + dvd2.getDirector() + " \n Lead Act: " + dvd2.getLead() + " \n Run Time: " + dvd2.getRunTime() + " \n Price: " + dvd2.getDvdPrice()); pressKey(); } if(temp.equals(dvd3.getTitle())) { clrscr(); System.out.println("\nDvd is present in collection at location 3 (Dvd 3 in collection):\n\nTitle: " + dvd3.getTitle() + " \n Director: " + dvd3.getDirector() + " \n Lead Act: " + dvd3.getLead() + " \n Run Time: " + dvd3.getRunTime() + " \n Price: " + dvd3.getDvdPrice()); pressKey(); } else { clrscr(); System.out.println("\nSorry, there were no Dvd's found with that title to display.\n "); pressKey(); } } The collection class (with main()): public class Collection { //Declare private variables for use with class instances private Dvd dvd1; private Dvd dvd2; private Dvd dvd3; private Book book1; private Book book2; private Book book3; public Collection() { //array = new int[2]; //dvd1 = dvd1; //dvd2 = dvd2; //dvd3 = dvd3; dvd1 = new Dvd(); dvd2 = new Dvd(); dvd3 = new Dvd(); book1 = new Book(); book2 = new Book(); book3 = new Book(); } public static void main(String args[]) { //creates an instance of the collection class Collection collection = new Collection(); collection.menu(); } public void menu() { //declare the option field int option; char answer; //start do while loop for the menu do { //display the menu clrscr(); System.out.println(""); System.out.println("\n\n~#~#~#~#~ DVD COLLECTION MENU ~#~#~#~#~\n\n"); System.out.println("\n<><><><> DVD's <><><><>\n"); System.out.println("1: Add (up to 3) Dvd's to Collection"); System.out.println("2: Display Dvd Collection"); System.out.println("3: Search Dvd Collection by collection"); System.out.println("\n<><><><> BOOK's <><><><>\n"); System.out.println("4: Add (up to 3) Books's to Collection"); System.out.println("5: Display Book Collection"); System.out.println("6: Search Book Collection by Title"); System.out.println("7: Quit program"); //prompt user to enter a selection System.out.println("\nPlease select an option (1 - 7): "); //use genio to get the user input option=Genio.getInteger(); // Option 1 allows user to add up to 3 Dvd's to dvd collection if (option == 1) { clrscr(); System.out.println("Enter Dvd 1 details:\n"); dvd1.setDvdInputs(); pressKey(); System.out.println("Enter Dvd 2 details:\n"); dvd2.setDvdInputs(); pressKey(); System.out.println("Enter Dvd 3 details:\n"); dvd3.setDvdInputs(); pressKey(); } // Option 2 allows user to display Dvd collection if (option == 2) { clrscr(); displayDvds(); } // Option 3 allows the user to search the Dvd collection by title if (option == 3) { clrscr(); searchDvd(); } // Option 4 allows user add books to the book collection if (option == 4) { clrscr(); System.out.println("Enter Book 1 details:\n"); book1.setBookInputs(); pressKey(); System.out.println("Enter Book 2 details:\n"); book2.setBookInputs(); pressKey(); System.out.println("Enter Book 3 details:\n"); book3.setBookInputs(); pressKey(); } //i Option 5 allows the user to display the collection of books if (option == 5) { clrscr(); displayBooks(); } // Option 6 allows the user to search the Book collection by title if (option == 6) { clrscr(); searchBook(); } } // Option 7 will print a message that tells that the program may be exited while (option != 7); clrscr(); System.out.println("You may now close the program. (click cross at top right)"); } public void displayDvds() { float totalPrice = 0; totalPrice = dvd1.getDvdPrice() + dvd2.getDvdPrice() + dvd3.getDvdPrice(); int totalRunTime = 0; totalRunTime = dvd1.getRunTime() + dvd2.getRunTime() + dvd3.getRunTime(); if (dvd1.getTitle() == "" && dvd1.getDirector() == "" && dvd1.getLead() == "" && dvd1.getRunTime() == 0 && dvd1.getDvdPrice() == 0 && dvd2.getTitle() == "" && dvd2.getDirector() == "" && dvd2.getLead() == "" && dvd2.getRunTime() == 0 && dvd2.getDvdPrice() == 0 && dvd3.getTitle() == "" && dvd3.getDirector() == "" && dvd3.getLead() == "" && dvd3.getRunTime() == 0 && dvd3.getDvdPrice() == 0) { clrscr(); System.out.println("Sorry, there were no Dvd's in the collection to display."); pressKey(); } else { clrscr(); System.out.println(" \nDvd Collection:\n DVD1:\nTitle: " + dvd1.getTitle() + " \nDirector: " + dvd1.getDirector() + " \nLead Act: " + dvd1.getLead() + " \nRun Time: " + dvd1.getRunTime() + " \nPrice: £" + dvd1.getDvdPrice()); System.out.println(" \nDvd Collection:\n DVD2:\nTitle: " + dvd2.getTitle() + " \nDirector: " + dvd2.getDirector() + " \nLead Act: " + dvd2.getLead() + " \nRun Time: " + dvd2.getRunTime() + " \nPrice: £" + dvd2.getDvdPrice()); System.out.println(" \nDvd Collection:\n DVD3:\nTitle: " + dvd3.getTitle() + " \nDirector: " + dvd3.getDirector() + " \nLead Act: " + dvd3.getLead() + " \nRun Time: " + dvd3.getRunTime() + " \nPrice: £" + dvd3.getDvdPrice()); System.out.println(" \nTotal cost of combined Dvd's: £" + totalPrice); System.out.println(" \nTotal Run Time of combined Dvd's: " + totalRunTime + " minutes."); pressKey(); } } public void searchDvd() { String temp = ""; // Temporary variable to hold dvd title System.out.println ("\nPlease enter Dvd Title (full title) to search for: "); temp= Genio.getString(); if(temp.equals(dvd1.getTitle())) { clrscr(); System.out.println("\nDvd is present in collection at location 1 (Dvd 1 in collection):\n\nTitle: " + dvd1.getTitle() + " \n Director: " + dvd1.getDirector() + " \n Lead Act: " + dvd1.getLead() + " \n Run Time: " + dvd1.getRunTime() + " \n Price: " + dvd1.getDvdPrice()); pressKey(); } if(temp.equals(dvd2.getTitle())) { clrscr(); System.out.println("\nDvd is present in collection at location 2 (Dvd 2 in collection):\n\nTitle: " + dvd2.getTitle() + " \n Director: " + dvd2.getDirector() + " \n Lead Act: " + dvd2.getLead() + " \n Run Time: " + dvd2.getRunTime() + " \n Price: " + dvd2.getDvdPrice()); pressKey(); } if(temp.equals(dvd3.getTitle())) { clrscr(); System.out.println("\nDvd is present in collection at location 3 (Dvd 3 in collection):\n\nTitle: " + dvd3.getTitle() + " \n Director: " + dvd3.getDirector() + " \n Lead Act: " + dvd3.getLead() + " \n Run Time: " + dvd3.getRunTime() + " \n Price: " + dvd3.getDvdPrice()); pressKey(); } else { clrscr(); System.out.println("\nSorry, there were no Dvd's found with that title to display.\n "); pressKey(); } } public void displayBooks() { float totalbPrice = 0; totalbPrice = book1.getBookPrice() + book2.getBookPrice() + book3.getBookPrice(); int totalPages; totalPages = book1.getPages() + book2.getPages() + book3.getPages(); if (book1.getBookTitle() == "" && book1.getAuthor() == "" && book1.getGenre() == "" && book1.getPages() == 0 && book1.getBookPrice() == 0 && book2.getBookTitle() == "" || book2.getAuthor() == "" && book2.getGenre() == "" && book2.getPages() == 0 && book2.getBookPrice() == 0 && book3.getBookTitle() == "" && book3.getAuthor() == "" && book3.getGenre() == "" && book3.getPages() == 0 && book3.getBookPrice() == 0) { clrscr(); System.out.println("Sorry, there were no Book's in the collection to display."); pressKey(); } else { clrscr(); System.out.println(" \nBook Collection:\n BOOK 1: \nTitle: " + book1.getBookTitle() + " \nAuthor: " + book1.getAuthor() + " \nGenre: " + book1.getGenre() + " \nPages: " + book1.getPages() + " \nPrice: £" + book1.getBookPrice()); System.out.println(" \nBook Collection:\n BOOK 2: \nTitle: " + book2.getBookTitle() + " \nAuthor: " + book2.getAuthor() + " \nGenre: " + book2.getGenre() + " \nPages: " + book2.getPages() + " \nPrice: £" + book2.getBookPrice()); System.out.println(" \nBook Collection:\n BOOK 3: \nTitle: " + book3.getBookTitle() + " \nAuthor: " + book3.getAuthor() + " \nGenre: " + book3.getGenre() + " \nPages: " + book3.getPages() + " \nPrice: £" + book3.getBookPrice()); System.out.println(" \nTotal cost of combined Book's: £" + totalbPrice); System.out.println(" \nTotal number of combined book pages: " + totalPages + " pages."); pressKey(); } } public void searchBook() { String tempb; // Temporary variable to hold book title System.out.println ("\nPlease enter Book Title (full title) to search for: "); tempb= Genio.getString(); if(tempb.equals(book1.getBookTitle())) { clrscr(); System.out.println("\nBook is present in collection at location 1 (Book 1 in collection):\n\nTitle: " + book1.getBookTitle() + " \nAuthor: " + book1.getAuthor() + " \nLead Act: " + book1.getGenre() + " \nRun Time: " + book1.getPages() + " \nPrice: " + book1.getBookPrice()); pressKey(); } if(tempb.equals(book2.getBookTitle())) { clrscr(); System.out.println("\nBook is present in collection at location 2 (Book 2 in collection):\n\nTitle: " + book2.getBookTitle() + " \nAuthor: " + book2.getAuthor() + " \nLead Act: " + book2.getGenre() + " \nRun Time: " + book2.getPages() + " \nPrice: £" + book2.getBookPrice()); pressKey(); } if(tempb.equals(book3.getBookTitle())) { clrscr(); System.out.println("\nBook is present in collection at location 3 (Book 3 in collection):\n\nTitle: " + book3.getBookTitle() + " \nAuthor: " + book3.getAuthor() + " \nLead Act: " + book3.getGenre() + " \nRun Time: " + book3.getPages() + " \nPrice: £" + book3.getBookPrice()); pressKey(); } else { clrscr(); System.out.println("\nSorry, there were no Book's found with that title to display.\n "); pressKey(); } } public static void clrscr() { for ( int i=1;i<=50;i++) System.out.println(); } public static void pressKey() { String s; System.out.print("\nPress return to continue : \n"); s = Genio.getString(); } } The Dvd class class is identical to this): public class Dvd { // instance Dvd variables private String dvdTitle = ""; // Title of dvd set to empty private String dvdDirector = ""; // Director of dvd set to empty private String dvdLead = ""; // Lead actor/actress of dvd set to empty private int dvdRunTime = 0; //Dvd run time in minutes private float dvdPrice = 0; //Value of dvd public Dvd( ) { dvdTitle = ""; dvdDirector = ""; dvdLead = ""; dvdRunTime = 0; dvdPrice = 0; } / public void setDvdInputs() { System.out.println("Please enter the Dvd Title: "); dvdTitle=Genio.getString(); System.out.println("Please enter the Dvd Director: "); dvdDirector=Genio.getString(); System.out.println("Please enter the Dvd Lead Actor/Actress: "); dvdLead=Genio.getString(); System.out.println("Please enter the Dvd Run Time: "); dvdRunTime=Genio.getInteger(); System.out.println("Please enter the Dvd Cost: "); dvdPrice=Genio.getFloat(); } public String getTitle(){ return dvdTitle; } public String getDirector(){ return dvdDirector; } public String getLead(){ return dvdLead; } public int getRunTime() { return dvdRunTime; } public float getDvdPrice() { return dvdPrice; } } The Book class: public class Book { // instance Dvd variables private String bookTitle = ""; // Title of dvd set to empty private String bookAuthor = ""; // Director of dvd set to empty private String bookGenre = ""; // Lead actor/actress of dvd set to empty private int bookPages = 0; //Dvd run time in minutes private float bookPrice = 0; //Value of dvd public Book( ) { bookTitle = ""; bookAuthor = ""; bookGenre = ""; bookPages = 0; bookPrice = 0; } public void setBookInputs() { System.out.println("Please enter the Book Title: "); bookTitle=Genio.getString(); System.out.println("Please enter the Book Author: "); bookAuthor=Genio.getString(); System.out.println("Please enter the Book Genre: "); bookGenre=Genio.getString(); System.out.println("Please enter the Book Page Number: "); bookPages=Genio.getInteger(); //should be dvdRunTime = Genio.getDouble(); System.out.println("Please enter the Book Cost: "); bookPrice=Genio.getFloat(); //should be dvdPrice = Genio.getFloat(); } public String getBookTitle(){ return bookTitle; } public String getAuthor(){ return bookAuthor; } public String getGenre(){ return bookGenre; } public int getPages() { return bookPages; } public float getBookPrice() { return bookPrice; } } The Genio (user input) class: import java.io.BufferedReader; import java.io.InputStreamReader; public class Genio { public Genio() { } private static String getStr() { String inputLine = ""; BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { inputLine = reader.readLine(); } catch(Exception exc) { System.out.println ("There was an error during reading: " + exc.getMessage()); } return inputLine; } public static int getInteger() { int temp=0; boolean OK = false; BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); do { try { temp = Integer.parseInt(keyboard.readLine()); OK = true; } catch (Exception eRef) { if (eRef instanceof NumberFormatException) { System.out.print("Integer value needed: "); } else { System.out.println("Please report this error: "+eRef.toString()); } } } while(OK == false); return(temp); } public static float getFloat() { float temp=0; boolean OK = false; BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); do { try { temp = Float.parseFloat(keyboard.readLine()); OK = true; } catch (Exception eRef) { if (eRef instanceof NumberFormatException) { System.out.print("Number needed: "); } else { System.out.println("Please report this error: "+eRef.toString()); } } } while(OK == false); return(temp); } public static double getDouble() { double temp=0; boolean OK = false; BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); do { try { temp = Double.parseDouble(keyboard.readLine()); OK = true; } catch (Exception eRef) { if (eRef instanceof NumberFormatException) { System.out.print("Number needed: "); } else { System.out.println("Please report this error: "+eRef.toString()); } } } while(OK == false); return(temp); } public static char getCharacter() { String tempStr=""; char temp=' '; boolean OK = false; do { try { tempStr = getStr(); temp = tempStr.charAt(0); OK = true; } catch (Exception eRef) { if (eRef instanceof StringIndexOutOfBoundsException) { // means nothing was entered so prompt ... System.out.print("Enter a character: "); } else { System.out.println("Please report this error: "+eRef.toString()); } } } while(OK == false); return(temp); } public static String getString() { String temp=""; try { temp = getStr(); } catch (Exception eRef) { System.out.println("Please report this error: "+eRef.toString()); } return(temp); } } A: Your problem is caused by having separate if statements. if(something) { } if(somethingElse) // This is separate from the one above. You can use else if to chain them.. if(something) { } else if(somethingelse) { } else { System.out.println("Sorry, none could be found"); } or if you want your code to be more efficient and you're using JDK7+, you can use a switch.. switch(input) { case "Something": // Do something break; default: System.out.println("Sorry, none could be found"); break; } and finally, if you want to keep the exact same if structure, then you can use a boolean value. if(something) { found = true; } if(!found) { System.out.println("Sorry, none could be found"); } I've added this last one in for the sake of completeness, but I wouldn't recommend it. Use one of the first two options.
{ "pile_set_name": "StackExchange" }
Q: Android Declaring Buttons Programmatically I have done tons of searching on the internet tonight and this is what I have come up with. For some reason it is not working. I am not getting any errors and I can verify my loops are actually running. Here is my code. TableLayout table = (TableLayout) findViewById(R.id.tablelayout1); while (numsounds>0){ Log.d("MYTAG", ""+numsounds); if(numsounds>=3){ Log.d("MYTAG", ""+numsounds); TableRow row = new TableRow(this); for (int j = 0; j < 3; j++) { int button_num = j + 1 + ( row_num * 3); row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT)); buttonparams.height = LayoutParams.MATCH_PARENT; int btnwidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics()); buttonparams.width = btnwidth; buttonparams.weight = .31f; Button btn = new Button(this); btn.setLongClickable(true); btn.setLayoutParams(buttonparams); btn.setText(soundtitleArray[button_num]); btn.setId(j + 1 + ( button_num)); btn.getBackground().setAlpha(150); btn.setOnClickListener(buttonClickListener); btn.setOnLongClickListener(buttonLongClickListener); row.addView(btn); } numsounds=numsounds-3; Log.d("MYTAG", ""+numsounds); table.addView(row); row_num = row_num+1; } if(numsounds<3){ Log.d("MYTAG", ""+numsounds); TableRow row = new TableRow(this); for (int j = 0; j < numsounds; j++) { int button_num = j + 1 + ( row_num * numsounds); row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT)); buttonparams.height = LayoutParams.MATCH_PARENT; int btnwidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics()); buttonparams.width = btnwidth; float btnweight = 1/numsounds; buttonparams.weight = btnweight; Button btn = new Button(this); btn.setLongClickable(true); btn.setLayoutParams(buttonparams); btn.setText(soundtitleArray[button_num]); btn.setId(j + 1 + ( button_num)); btn.getBackground().setAlpha(150); btn.setOnClickListener(buttonClickListener); btn.setOnLongClickListener(buttonLongClickListener); row.addView(btn); } table.addView(row); row_num = row_num+1; numsounds=numsounds-1; Log.d("MYTAG", ""+numsounds); } } I know the code is running because it is outputing the change in numbers to logcat. What i can figure out is it keeps giving me a blank screen with only my background showing. The buttons are not showing up. Also My Imports are as follows. import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import com.<MYAPP>.SoundBoard; import com.<MYAPP>.R; import android.content.ContentValues; import android.content.Intent; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.provider.MediaStore.Audio.AudioColumns; import android.util.Log; import android.util.TypedValue; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.widget.Button; import android.widget.RelativeLayout; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.Toast; import com.google.ads.AdRequest; import com.google.ads.AdSize; import com.google.ads.AdView; import android.widget.TableRow.LayoutParams; I declared the buttonparams at the beginning of my class as: private TableLayout.LayoutParams buttonparams = new TableLayout.LayoutParams(); A: Layout params you've used for the TableRow should be of TableRow.LayoutParams, try TableRow.LayoutParams buttonparams = new TableRow.LayoutParams();
{ "pile_set_name": "StackExchange" }
Q: How to use the verb fit? I'm wondering how to use the verb fit. I found some examples on the internet. Sometimes a indirect object is used, sometimes it's not needed: My clothes fit better now and people keep asking, "Are you losing weight?" Also, different prepositions are used in these other examples. Her elegant behaviour fit perfectly with the diplomatic corps. These old boots are fit for the rubbish bin. That table does not fit in the small room. Even though you can't fit into any of your prepregnancy clothes, you still have your shoes, right? But which of these phrases are correct? 1) Your clothes fit too tight to you and your appearance has changed before the mirror. 2) Your clothes fit you too tight and your appearance has changed before the mirror. 3) Your clothes fit too tight and your appearance has changed before the mirror. 4) Your clothes fit in you too tight and your appearance has changed before the mirror. 5) Your clothes fit into you too tight and your appearance has changed before the mirror. The prepositions "in" and "into" look equivalent, and the rest have other different meanings. Is this right? Is there some rules to make me more understandable all of this? A: You are basically trying to express Your clothes are too tight on you your clothes are form fitting You will want to use "tightly" (adverb) instead of "tight" in the constructions you have proposed. In #4 and #5 using "in" and "into" does not make any sense since clothes are not "in" a person, but "on" a person. #1 your clothes fit too tightly on you #2 your clothes fit you too tightly #3 your clothes fit too tightly the three sentences are all equivalent in meaning. #3 is the shortest form, and each of these sentences implies the other with certain words left out.
{ "pile_set_name": "StackExchange" }
Q: Taking properties from Maven settings.xml file to application context There are nice SO question and answers about this issue, but these options didn't work for me. I want to pass variables to app context: <bean class="blah.blah.Blah" id="blah"> <property name="first" value="${first.property}"/> <property name="second" value="${second.property}"/> </bean> I have the following in the Maven's settings.xml file: <profiles> <profile> <id>profileId</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <first.property>first value</first.property> <second.property>second value</second.property> </properties> I tried this option (which is a bit strange), it gave no results. Than I added this plugin: <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>properties-maven-plugin</artifactId> <version>1.0-alpha-2</version> <executions> <execution> <phase>process-resources</phase> <goals> <goal>write-project-properties</goal> </goals> <configuration> <outputFile> src/main/resources/maven.properties </outputFile> </configuration> </execution> </executions> </plugin> And there wasn't any maven.properties files in the project afterwards. If I created empty file, nothing appeared in it. And I tried to do repeat these steps with -PprofileId, it didn't help. Could someone please provide a working code snippet or tell me what do I miss here? Thanks in advance. Update: I was wrong, properties-maven-plugin works fine. A: It's not clear to me from your question - but if you tried running mvn -PprofileId resources:resources the properties plugin would not run, because the command is executing an individual goal, not a Maven lifecycle phase. What happens if you run mvn -PprofileId process-resources? Another question, are any other profiles active? activeByDefault does not mean "always active." Per Maven docs "All profiles that are active by default are automatically deactivated when a profile in the POM is activated on the command line or through its activation config." So if you have another profile active, the one with profileId will not be. Try removing the activation block from that profile and run mvn -PprofileId process-resources.
{ "pile_set_name": "StackExchange" }
Q: Substring length errors I keep getting the error An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll when inputting a value over 70 characters in my code, could anybody please explain why? namespace testingStrategiesCoding { class Program { static void Main(string[] args) { string userMessage; int messageLength; string newMessage1; string newMessage2; string newMessage3; Console.WriteLine("Enter a message"); userMessage = Console.ReadLine(); messageLength = userMessage.Length; if (messageLength < 71) { Console.WriteLine(""); Console.WriteLine(userMessage); } else if (messageLength > 70 && messageLength < 141) { newMessage1 = userMessage.Substring(0, 70); newMessage2 = userMessage.Substring(71, messageLength); Console.WriteLine(""); Console.WriteLine(newMessage1); Console.WriteLine(""); Console.WriteLine(newMessage2); } else if (messageLength > 140 && messageLength < 211) { newMessage1 = userMessage.Substring(0, 70); newMessage2 = userMessage.Substring(71, 140); newMessage3 = userMessage.Substring(141, messageLength); Console.WriteLine(""); Console.WriteLine(newMessage1); Console.WriteLine(""); Console.WriteLine(newMessage2); Console.WriteLine(""); Console.WriteLine(newMessage3); } else { Console.WriteLine("Invalid, please enter a message lower than 210 characters."); } Console.ReadKey(); } } } I do not think this is a duplicate due to the error being a factor of a part of the code that no other thread seems to relate to. A: Substring(71, messageLength) The second substring parameter is the length, not the end-index. You need to subtract the start-index for this to work. Also, you might want to start with 70, or you lose a character. Substring(70, messageLength - 70)
{ "pile_set_name": "StackExchange" }
Q: Are Laguerre-Gaussian functions compactly supported? Laguerre-Gaussian functions are very common in optics and I wonder if they are Compactly Supported. These functions are essentially an associated Laguerre Polynomial modulated by a gaussian function. Also if someone would please recommend some good bibliography on the subject because coleagues seem to misuse the term. A: Laguerre-Gaussian functions, as Jyrki notes, are not compactly supported. Rather, the Laguerre polynomials form an orthogonal basis over the Hilbert space $L^2(0,\infty)$ having inner product $$\langle f,g\rangle = \int_0^{\infty} dx \, f(x)\, g(x)\, e^{-x}$$ In optical beam profiles, you are not going to find many good representations of functions with finite support, except as an infinite sum over functions like Laguerre Gaussians that are not finitely supported. Nonetheless, if you want a reference that treats Laguerre polynomials with all due respect, I recommend the book my professor Sam Holland wrote on Hilbert space for undergraduates: Applied Analysis by the Hilbert Space Method.
{ "pile_set_name": "StackExchange" }
Q: I want to Get a list when clicking on regions of pie chart made by using plotly and rshiny package Need help... I had created a pie graph comparing count of car makes of US industry and Autongin(internal purpose). I want to get a list of car makes in autongin when clicking on autongin count(orange region in graph) and US make count when clicking on US count(blue region in graph).The Autongin make list contains 51 car makes and US make list contains 79 car makes.I created the graph using plotly package and the database is connected .I want to get the list of car makes of Autongin and US Industry. Now there is no change when clicking on the plot. The sample data is attached here AutonginMake USMakename 1 Acura Acura 2 Aston Martin Aston Martin 3 Audi Audi 4 Bentley Bentley 5 BMW BMW 6 Buick Buick 7 Cadillac Cadillac 8 Chevrolet Chevrolet 9 Chrysler Chrysler 10 Dodge Dodge 11 Ford Ford 12 GMC GMC 13 Honda Honda 14 HUMMER Hummer I took the count of above autonginmake and US make and polotted..My requirement is to list this makes when clicking on corresponding regions of pie chart #packages needed library(plotly) library(shiny) library(DBI) library(RMySQL) #connecting db dealerinventory1<-dbConnect(RMySQL::MySQL(), user='ghhjjl', password='dfgfdgdg!', host='hfghfh', dbname='hhthhq23u') uscount1=dbGetQuery(dealerinventory1, 'SELECT count(distinct makename) as USmakes FROM dealer_inventory.CarQuery;') autongincount1=dbGetQuery(dealerinventory1, 'SELECT count(distinct makename) as autonginmakes FROM dealer_inventory.car_inventory_json_lookup;') usandautongintable <- c(autongincount1,uscount1) usandautongintable label <- c(paste("Autongin Count: ", autongincount1),paste("US Industry Count: ", uscount1)) label unlist <- as.numeric(unlist(usandautongintable)) typeof(unlist) #table used for plotting table<- as.data.frame(usandautongintable) table #for plotting pie chart plotpie<- plot_ly(table, labels = label,values = unlist, type = "pie") %>% layout(title = 'Comparison of Makes', xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE), yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE)) plotpie library(shiny) library(plotly) ui= fluidPage( plotlyOutput("plot") ) server1<- function(input,output){ output$plot=renderPlotly({ plot_ly(table, labels = label,values = unlist, type = "pie") %>% layout(title = 'Comparison of Makes', xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE), yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE)) }) } shinyApp(ui,server1) Output plot link is here http://autonginreports.iinerds.com:3838/sample-apps/plot/ A: First, hold the make names as variables. Then, use event_data of plotly to catch which part of the pie has been clicked. The make list is printed on a text output in the example, but you can use it in any way you want. A good reference is here https://plotly-book.cpsievert.me/linking-views-with-shiny.html. library(shiny) library(plotly) ui <- fluidPage(tagList( plotlyOutput("pie"), verbatimTextOutput("makes") )) server <- function(input, output) { # dummy makes data usmakes <- c("ford", "acura", "bmw") autonginmakes <- c("cadillac", "hummer") usmakes_count <- length(usmakes) autonginmakes_count <- length(autonginmakes) output$pie <- renderPlotly({ plot_ly(labels=c("US", "Autongin"), values=c(usmakes_count, autonginmakes_count), key=c("us", "autongin"), type="pie") }) output$makes <- renderPrint({ clicked <- event_data("plotly_click") if (is.null(clicked)) { "no selection" } else if (clicked$key == "us") { usmakes } else { autonginmakes } }) } shinyApp(ui, server)
{ "pile_set_name": "StackExchange" }
Q: Sign Webstart Application for Mac Store I have a java webstart application that is properly signed and working on all OSes. However running it on MAC requires the user to circumvent the Mac security features, as the app is not signed with an Apple Developer ID. I want to know if and if yes, how I can use my Apple certificates to sign the jar such that it can be run without problems on Windows and Mac. A: Unfortunately this is a not possible, and is a duplicate of: How to sign Java applet with Apple Developer ID You can however use a tool to convert your jar into an app bundle, which can in fact be signed for gatekeeper (not for App Store, but to bypass the launch restriction). See http://www.jemchicomac.com/how-to-convert-a-jar-file-into-an-app-for-osx/
{ "pile_set_name": "StackExchange" }
Q: Make algorithm text grey and showing just part of it using beamer I am preparing slides and I want to introduce some algorithm on them, however as it is to long to fit, I decided to represent just the important parts of my algorithm. So I am wondering if it is possible that I have my algorithm, with a part missing. What I mean is it should look like this: Algorithm 1. Input: data Require: some constraings [1]-[10] //this part for example to be cut out, 11. if condition 12. do something 13. other stuff So I want a few lines to be cut out, but still shown that they are cut out. And then the following statements in the algorithm need of course to have the according numbering (here starting from 11). This is how my .tex file looks so far: \documentclass[11pt]{beamer} \usepackage[latin1]{inputenc} \usepackage[T1]{fontenc} \PassOptionsToPackage{noend}{algpseudocode} \usepackage{algpseudocode} \usepackage{algorithm} \usepackage{color} \begin{document} \begin{frame} \begin{algorithm}[H] \begin{algorithmic}[1] \setcounter{ALG@line}{11} \State \textcolor{grey}{Lines cut out} \State conditions \State other stuff \State $d$: stuff \end{algorithmic} \end{algorithm} \end{frame} \end{document} A: Due to the width of the range you want to cut out, you may have to manage some manual spacing of the grayed-out line of text. However, this is fairly straight forward, as the list of items inside an algorithmic environment are just that... \items: \documentclass{beamer} \usepackage[noend]{algpseudocode} \usepackage{algorithm} \makeatletter \newcommand{\setalgolineno}[1]{\setcounter{ALG@line}{\numexpr#1-1}} \makeatother \begin{document} \begin{frame} \begin{algorithmic}[1] \item[\rlap{\alglinenumber{1-10}}\phantom{\alglinenumber{10}}] \quad \textcolor{gray}{Lines cut out} \setalgolineno{11} \State conditions \State other stuff \State $d$: stuff \end{algorithmic} \end{frame} \end{document}
{ "pile_set_name": "StackExchange" }
Q: How to dynamically change the title of a menu item I have a "new comments" menu item in the user-menu that is generated by a view. I would like to change the title of the menu to include the number of new comments. I tried using hook_menu_alter without success. I cleared the cache and rebuilt the menu using the devel function. function newcomments_menu_alter(&$items){ $items['newcomments']['title'] = '5 New Comments'; } When I add a menu item with hook_menu() I can dynamically change the title with a custom "title callback" function. But I can't figure out what the "page callback" is to display the view. A: Views doesn't implement hook_menu() to add it's items, it uses the menu link API directly to add links. This makes it a bit trickier to do what you want as hook_menu_link_alter() isn't necessarily called when the caches are flushed, but only when the link is edited via the admin UI. The links in menus don't even necessarily go through theme_menu_link() so you can't override the title at the theme level with that hook. Instead the only way I could find to do it was to implement hook_preprocess_link(), check the path, and change the title. It's not a very pleasing solution, as theme_link() seems far too generic a place to be hooking into to change just one link title, but it might do the trick: function MYMODULE_preprocess_link(&$vars) { if ($vars['path'] == 'newcomments') { $num_comments = MYMODULE_num_comments(); $vars['text'] = format_plural($num_comments, '1 New Comment', '@count New Comments'); } } The only problem is that if there are other links on the page that point to the same URL their title will also be changed. Hopefully this can be a 'feature' rather than a 'bug' ;)
{ "pile_set_name": "StackExchange" }
Q: upload / post stringIO as file I want to upload a stringIO as a file to a server. I'm not using rails to make the request, just ruby and some gems. I have created a stringIO like below: require 'rest-client' require 'zip' ... some code stream = Zip::OutputStream::write_buffer do |zip| ... code that download files and packs them end stream.rewind RestClient.post('somepath', { file: stream.read }, headers) RestClient is just some handy gem that makes it a bit easier to send http request. so my problem is that on the server side in the controller when I receive the request I get an error ArgumentError - invalid byte sequence in UTF-8: activesupport (4.2.6) lib/active_support/core_ext/object/blank.rb:117:in `blank?' carrierwave (0.10.0) lib/carrierwave/sanitized_file.rb:127:in `is_path?' carrierwave (0.10.0) lib/carrierwave/sanitized_file.rb:93:in `size' carrierwave (0.10.0) lib/carrierwave/sanitized_file.rb:136:in `empty?' carrierwave (0.10.0) lib/carrierwave/uploader/cache.rb:119:in `cache!' carrierwave (0.10.0) lib/carrierwave/mount.rb:329:in `cache' carrierwave (0.10.0) lib/carrierwave/mount.rb:163:in `export=' carrierwave (0.10.0) lib/carrierwave/orm/activerecord.rb:39:in `export=' app/controllers/exports_controller.rb:17:in `upload' (I'm using carrierwave to store the files) I think that I'm not handling the stringIO properly but honestly don't exactly know how should I pass it to the post request so that it behaves like a file any ideas? A: turns out this was happening because I was not saving the zip as a file but used write_buffer that responds with stringIO. stringIO read method returns a string that was uploaded to my controller and then I tried to save the file using carrierwave roughly like that: ... code in my controller myObject = ObjectModel.find(params[:id]) myObject.fileUploader = StringIO.new(params[:file]) => this was the string i received from stringIO read method myObject.save but it won't work because StringIO objects don't have original_filename method anymore since Rails3 (As far as I understood from the carrierwave issue page) The solutions was to create a wrapper around StringIO and add either an attribute or a method that is called original_filename afterwards file was being saved correctly. I'm posting link to carrierwave wiki that deals with this: https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-Upload-from-a-string-in-Rails-3-or-later and a sample wrapper like object class StringIOWrapper < StringIO attr_accessor :original_filename end afterwards this will work myObject.fileUploader = StringIOWrapper.new(params[:file]) myObject.save
{ "pile_set_name": "StackExchange" }
Q: Trying to scale down a Bitmap in Android not working I'm trying to scale down a bitmap. In short, the image is originally from a ByteArray with a width of 4016. After I scale the image down with factory options, it still reports the image with a width of 4016. Here are two clips of my code: Bitmap myBitmap = null; @Override protected byte[] doInBackground(Object... params) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; if (options.outHeight > options.outWidth) { options.inSampleSize = calculateInSampleSize(options, 640, 960); } else { options.inSampleSize = calculateInSampleSize(options, 960, 640); } options.inJustDecodeBounds = false; //myImageByteArray is 4016 wide myBitmap = BitmapFactory.decodeByteArray(myImageByteArray, 0, myImageByteArray.length, options); //This log statement outputs 4016!!! Shouldn't it be smaller since I just decoded the byteArray with options? Log.d("bitmap", myBitmap.getWidth()+""); } public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { // Calculate ratios of height and width to requested height and // width final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); // Choose the smallest ratio as inSampleSize value, this will // guarantee // a final image with both dimensions larger than or equal to // the // requested height and width. inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; } Update: Here are two clips of my code: Bitmap myBitmap = null; @Override protected byte[] doInBackground(Object... params) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; //myImageByteArray is 4016 wide myBitmap = BitmapFactory.decodeByteArray(myImageByteArray, 0, myImageByteArray.length, options); if (options.outHeight > options.outWidth) { options.inSampleSize = calculateInSampleSize(options, 640, 960); } else { options.inSampleSize = calculateInSampleSize(options, 960, 640); } options.inJustDecodeBounds = false; //myImageByteArray is 4016 wide myBitmap = BitmapFactory.decodeByteArray(myImageByteArray, 0, myImageByteArray.length, options); //This log statement outputs around 1000 now. Log.d("bitmap", myBitmap.getWidth()+""); } public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { // Calculate ratios of height and width to requested height and // width final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); // Choose the smallest ratio as inSampleSize value, this will // guarantee // a final image with both dimensions larger than or equal to // the // requested height and width. inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; } A: You need to call .decodeByteArray(..) twice! Once to attain the width and the height with .inJustDecodeBounds set to true and then again with .inSampleSize to get the actual scaled Bitmap, options.outHeight and options.outWidth in your code are probably zero. call BitmapFactory.decodeByteArray(myImageByteArray, 0, myImageByteArray.length, options); before checking outHeight and outWidth. Edit Take a look at this example from Google's Android Dev site: BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(getResources(), R.id.myimage, options); int imageHeight = options.outHeight; int imageWidth = options.outWidth; Notice that options.outHeight is used after calling decodeResources(...). This you have to fix in your code.
{ "pile_set_name": "StackExchange" }
Q: any way to loop iteration with same item in python? It's a common programming task to loop iteration while not receiving next item. For example: for sLine in oFile : if ... some logic ... : sLine = oFile.next() ... some more logic ... # at this point i want to continue iteration but without # getting next item from oFile. How can this be done in python? A: I first thought you wanted the continue keyword, but that would of course get you the next line of input. I think I'm stumped. When looping over the lines of a file, what exactly should happen if you continued the loop without getting a new line? Do you want to inspect the line again? If so, I suggest adding an inner loop that runs until you're "done" with the input line, which you can then break out of, or use maybe the while-condition and a flag variable to terminate. A: What you need is a simple, deterministic finite state machine. Something like this... state = 1 for sLine in oFile: if state == 1: if ... some logic ... : state = 2 elif state == 2: if ... some logic ... : state = 1
{ "pile_set_name": "StackExchange" }
Q: How to get the Position of a paragraph in google docs API Using GAS, I'm trying to navigate paragraphs in a google doc and record their starting position so that I can display an interactive navigation menu in a sidebar. But I can't find any GAS method that returns the position of a paragraph (or an element for that matter), except when the cursor is within that paragraph. I thought of inserting bookmarks to retrieve their positions, but it seems that one cannot insert a bookmark without having first a position… Am I missing anything? Note that I'm aware of the fact that headings have hash locations (except for normal paragraphs) that are easy to retrieve using a TOC; but I can't use these hash locations directly in any GAS add-on, because the caja compiler prevents it. Besides, I'd like to list more than headings in my navigation menu. A: Use the Document.newPosition(element, offset) method, where element is your Paragraph object and offset is 0. For example: var newParagraph = body.appendParagraph("some text"); var paragraphPosition = doc.newPosition(newParagraph, 0);
{ "pile_set_name": "StackExchange" }
Q: How to fix static method error while making Eloquent relationship I have two tables queries and query_feedback_types, the query table has one foreign key as query_feedback_type_id, I have created two models for respective tables as Query.php and QueryFeedbackType.php these are both inside my App\Admin folder. So my problem is that when I try to make an Eloquent relationship between these two tables and returning all data from Queries table with the help of model Query and then I want to have data of query_feedback_types table also, but I am unable to access it via $row->queryFeedbackType->query, this is giving me an error as "Cannot make static method Illuminate\Database\Eloquent\Model::query() non static in class App\Admin\QueryFeedbackType" I have already created a similar relationship but the table name in the database was very simple for it , faqs and categories with the foreign key in faqs as category_id. and that relationship worked perfectly Model Query.php namespace App\Admin; use DB; use Illuminate\Database\Eloquent\Model; class Query extends Model { public function queryFeedbackType() { return $this->belongsTo('App\Admin\QueryFeedbackType'); } protected $fillable= ['name','email_id','mobile_no','query_feedback_type_id','remark']; } Model QueryFeedbackType <?php namespace App\Admin; use DB; use Illuminate\Database\Eloquent\Model; class QueryFeedbackType extends Model { public function query() { return $this->hasMany('App\Admin\Query'); } } Controller QueryController.php use DB; use validator; use File; use App\Http\Controllers\Admin\Resize_Image; use Helper; class QueryController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $data['page'] = 'View Feedback/Query'; $data['template'] = 'admin/query/view'; $data['results'] = Query::orderBy('id', 'desc')->get(); return view('admin/includes/page', compact('data')); } } my coding page <?php if ($data['results']){ $i=1; foreach ($data['results'] as $row) { ?> <tr> {{$row->query_feedback_type}} <td><center><?php echo $row->name; ?></center></td> <td><center><?php echo $row->queryFeedbackType->id ?> //getting error in this line Error: "Cannot make static method Illuminate\Database\Eloquent\Model::query() non static in class App\Admin\QueryFeedbackType" Please explain to me the mistake I am doing here. A: The model is extending \Illuminate\Database\Eloquent\Model which already contains a static query function : /** * Begin querying the model. * * @return \Illuminate\Database\Eloquent\Builder */ public static function query() { return (new static)->newQuery(); } Fo every eloquent query under the hood, ORM will try to call this query method statically even if you don't do it. It happens internally to instantiate the query builder for your model. As in your model, you are having a method with same name query which is a non-static method. This is the reason why you are getting this error. I think in your case query() function is nothing but a simple relation. I would suggest to rename it to something like queries as it's hasMany. It will also help you remove the overlapping of function name to default static function query.
{ "pile_set_name": "StackExchange" }
Q: Java- how to obtain full xml stored in modified DOM Document I am using standard Java DOM parser to process an xml file- I have processed it and made changes to the xml document, now I want to view the modified xml. How do I store the modified XML into a string variable. For your reference, the code I am using is given below-- str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><config><var-def name=\"initial_no\">3972971</var-def><var-def name=\"webpage\">asdf</var-def><cloudwhile condition=\"${i.toInt() != 500}\" index=\"i\" returnvalue=\"false\" indexstart=\"1\" upperbound=\"500\"><var-def name=\"webpage\" overwrite=\"true\"><cloudwhile condition=\"${i.toInt() != 500}\" index=\"i\" returnvalue=\"false\" indexstart=\"100\" upperbound=\"700\"></cloudwhile><try><body><http url=\"www.google.com/patents/US${initial_no.toInt()+i.toInt()}\"/></body><catch>ERROR- No content found for this patent number.</catch></try></var-def><file action=\"write\" path=\"data/${initial_no.toInt()+i.toInt()}_content.html\"><var name=\"webpage\"/></file></cloudwhile></config>"; InputStream is = new ByteArrayInputStream(str.getBytes("UTF-8")); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(is); //some processing.. A: You can use Transformer API to do what you want: import java.io.*; import org.w3c.dom.*; import javax.xml.parsers.*; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.OutputKeys; import javax.xml.transform.stream.StreamResult; class SaveDom { public static void main(String[] args) throws Exception { String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><config><var-def name=\"initial_no\">3972971</var-def><var-def name=\"webpage\">asdf</var-def><cloudwhile condition=\"${i.toInt() != 500}\" index=\"i\" returnvalue=\"false\" indexstart=\"1\" upperbound=\"500\"><var-def name=\"webpage\" overwrite=\"true\"><cloudwhile condition=\"${i.toInt() != 500}\" index=\"i\" returnvalue=\"false\" indexstart=\"100\" upperbound=\"700\"></cloudwhile><try><body><http url=\"www.google.com/patents/US${initial_no.toInt()+i.toInt()}\"/></body><catch>ERROR- No content found for this patent number.</catch></try></var-def><file action=\"write\" path=\"data/${initial_no.toInt()+i.toInt()}_content.html\"><var name=\"webpage\"/></file></cloudwhile></config>"; InputStream is = new ByteArrayInputStream(str.getBytes("UTF-8")); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(is); // Write out the xml file // Use a Transformer for output TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty( OutputKeys.INDENT, "yes" ); transformer.setOutputProperty("encoding", "UTF-8"); DOMSource source = new DOMSource(doc); java.io.StringWriter sw = new java.io.StringWriter(); StreamResult _result = new StreamResult(sw); transformer.transform(source, _result); String out = sw.toString(); System.out.println(out); } }
{ "pile_set_name": "StackExchange" }
Q: Spring Cache with Redis - How to gracefully handle or even skip Caching in case of Connection Failure to Redis I've enabled Caching in my Spring app and I use Redis to serve the purpose. However, whenever a connection failure occurs, the app stops working whereas I think it had better skip the Caching and go on with normal execution flow. So, does anyone have any idea on how to gracefully do it in Spring ? Here is the exception I got. Caused by: org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool A: As from Spring Framework 4.1, there is a CacheErrorHandler that you can implement to handle such exceptions. Refer to the javadoc for more details. You can register it by having your @Configuration class extends CachingConfigurerSupport (see errorHandler()). A: CacheErrorHandler suggested by Stephane Nicoll is useful. But it doesn't help when it fails to create the connection to redis. The cache method like @Cacheable stills fails with RedisConnectionFailureException.
{ "pile_set_name": "StackExchange" }
Q: C# Use Constructor in another contructor I'm trying to create a constructor that looks for an object and then uses a different constructor. I don't want to have two constructors that execute the same code in both and in case of a change I would have to change both. public DokumentHandlowyC(DokumentHandlowy dokumentHandlowy) { Guid = dokumentHandlowy.Guid; KontrahentC = new KontrahentC(dokumentHandlowy.Kontrahent); Numer = dokumentHandlowy.Numer.ToString(); Obcy = dokumentHandlowy.Obcy.Numer; Date = dokumentHandlowy.Data; Pozycje = dokumentHandlowy.Pozycje.Select(x => new PozycjaDokHandlowegoC(x)).ToList(); KierunekVAT = dokumentHandlowy.Definicja.LiczonaOd; Wartosc_Brutto = new CurrencyC(dokumentHandlowy.BruttoCy); } public DokumentHandlowyC(Guid guid) { eaContext ea = new eaContext(); using (var session = ea.Login.CreateSession(true, false)) { var HM = HandelModule.GetInstance(session); dokumentHandlowy = null; try { dokumentHandlowy = HM.DokHandlowe[guid]; } catch (Exception) { throw new Enova_BrakWskazanegoObiektu($"DokumentHandlowy o Guid: '{guid.ToString()}'{System.Environment.NewLine}nie istnieje."); } //How use the contructor with DokumentHandlowy here? //Guid = dokumentHandlowy.Guid; //KontrahentC = new KontrahentC(dokumentHandlowy.Kontrahent); //Numer = dokumentHandlowy.Numer.ToString(); //Obcy = dokumentHandlowy.Obcy.Numer; //Date = dokumentHandlowy.Data; //Pozycje = dokumentHandlowy.Pozycje.Select(x => new PozycjaDokHandlowegoC(x)).ToList(); //KierunekVAT = dokumentHandlowy.Definicja.LiczonaOd; //Wartosc_Brutto = new CurrencyC(dokumentHandlowy.BruttoCy); } } A: Create a private method that does the shared functionality (in your example, populating variables) and call the method from both constructors.. see the example below: class Program { public string Title { get; set; } public Guid Id { get; set; } public Program(Guid _ProgramId) { this.Id = _ProgramId; this.PopulateFields(); } public Program(int _ProgramNumber) { this.PopulateFields(); } private void PopulateFields() { this.Title = "New Title"; } } If you want to call another constructor from another constructor, then you'd need to have the values passed in to the other constructor too in order to call the other constructor when a class is initiated, it is not possible to call the constructor from the body of another constructor.. public Program(int _ProgramNumber, Guid _ProgramId) : this(_ProgramId) { } In the above example, the constructor that takes two parameters, will also call the Program(Guid _ProgramId),
{ "pile_set_name": "StackExchange" }
Q: UITextfield uneditable field I'd like to have textfield with constant text in it non-editable like: ENTER YOUR NAME: And clicking at textfield would get cursor right after : The user should not be able to delete or edit "ENTER YOUR NAME:" also. Any ideas how to implement this? A: Set the delegate of your text field to an instance of UITextFieldDelegate implementation, and use the textField:shouldChangeCharactersInRange:replacementString: method to see if the user is attempting to change the ENTER YOUR NAME: string: - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { // "ENTER YOUR NAME:" occupies the first 16 characters; if the user us trying // to change something that is within that 16-character range, say "NO" if (range.location < 16) return NO; ... check additional conditions here return YES; } I don't think there is a way to place the cursor directly, but you can make an empty selection after the trailing colon of the initial text as described in this answer.
{ "pile_set_name": "StackExchange" }
Q: Classify if someone is home based on time I have a dataset with locations and a timestamp of a subject. For each location and timestamp I determined by comparing the location to the home address if the subject was at home or not (0/1) and added this value to the dataset. Now, I want to train a model to learn based on the timestamp when it is most likely that the subject is at home. Thus, if you give the model some timestamp, it will classify if the subject was at home at this time. The model learns the "best time" for someone being at home so to say. Obviously people are not at home at the same time every day but over a long period of time there should be some pattern and I want the model to classify based on this pattern. What would be a fitting algorithm to do this? A: This is an ideal case for feature engineering! I did this same case for myself using the google takeaway data to predict whether I am at home or at work. Instead of just using time I extracted the following features: Work Day --> 1 / 0 Day of the Week Month Year Time I then trained a random forest classification model to tell me whether I am at home, at work or other place based on those five features. As a successive step I used this model to actually identify dates where I "moved" or was "on holiday" because of the difference between prediction and actual labels.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to make Node NOT Require the ".js" Extension For Imports? Node now has built-in support for imports, which is awesome. But that support requires you to specify the file extension, which is annoying. I'm sure there's some justification for why this is (likely having to do with their weird obsession with the .mjs extension), but is there any way to work around it and make import work "like normal" (where you can leave .js off)? A: I fixed this was with the esm package. In short, the Node organization has done an awful job of rolling out ES Module support, but the saving grace is that in the meantime the guy who made the Lodash library has already added far better support, and it's super easy to get. Two steps: npm i esm node -r esm index.js (instead of just node index.js) If you just do the above you don't need any special Node flags (like experimental-modules) or anything else, and ES Module syntax (import/export) will work perfectly in your application ... including not requiring .js in imports.
{ "pile_set_name": "StackExchange" }
Q: Android Handler and Thread at start time not running? I'm trying to create a handler at the start of my application so I can have two threads working 1 the UI and 2 my server, I'm doing this so the server will not stop the UI from lagging, and usefully sort out my lag issues, but anyways, I'm looking at this website http://crodrigues.com/updating-the-ui-from-a-background-thread-on-android/ , the guy creates a runnable method, with a run method, there is also a method called updateGame which is always called when that method is ran, now I have tried out his code like so public class MainActivity extends Activity { private static final String TAG = gameObject.class.getSimpleName(); //Create a handler to deal with the server private Handler serverHandler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Turn off title requestWindowFeature(Window.FEATURE_NO_TITLE); //Make the application full screen getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView( new gamePanel( this ) ); Log.d( TAG, "View added" ); //Server method new Thread(new Runnable() { onServer( ); } ).start( ); } final Runnable updateRunnable = new Runnable() { public void run() { //call the activity method that updates the UI updateGame(); } }; //Give the positions to the game public void updateGame() { Log.d(TAG, "Update that game"); } //Update/run the server private void onServer() { if( gamePanel.rtnServerState() == true ) { Log.d(TAG, "Start the server"); } serverHandler.post( updateRunnable ); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } public void onDestroy() { Log.d( TAG, "Destroying... " ); super.onDestroy(); } public void onStop() { Log.d( TAG, "Stopping... " ); super.onStop(); } } and my updateGame is only ran once. Can anyone see the issue in why it doesn't keep running in the background? Canvas Updated post public class MainActivity extends Activity { private static final String TAG = gameObject.class.getSimpleName(); private final Handler serverHandler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Turn off title requestWindowFeature(Window.FEATURE_NO_TITLE); //Make the application full screen getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView( new gamePanel( this ) ); TextView textView = new TextView(this); textView.setTextSize(40); String message = "hello"; textView.setText(message); Log.d( TAG, "View added" ); //Server method new Thread(new Runnable() { @Override public void run() { onServer( ); } } ).start( ); } private void updateServer() { Log.d(TAG, "testing"); } //Update/run the server private void onServer() { if( gamePanel.rtnServerState() == true ) { Log.d(TAG, "Start the server"); } serverHandler.post( updateRunnable ); } //Update/server final Runnable updateRunnable = new Runnable() { public boolean running = true; public void run() { while(running){ //call the activity method that updates the UI updateServer(); } } }; @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } public void onDestroy() { Log.d( TAG, "Destroying... " ); super.onDestroy(); } public void onStop() { Log.d( TAG, "Stopping... " ); super.onStop(); } } Update number 2 public class MainActivity extends Activity { private static final String TAG = gameObject.class.getSimpleName(); private final Handler serverHandler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Turn off title requestWindowFeature(Window.FEATURE_NO_TITLE); //Make the application full screen getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView( new gamePanel( this ) ); TextView textView = new TextView(this); textView.setTextSize(40); String message = "hello"; textView.setText(message); Log.d( TAG, "View added" ); //Server method Runnable server = new Runnable() { public boolean running = true; public void run() { while(running){ onServer(); // Make sure this blocks in some way } } }; } private void updateServer() { Log.d(TAG, "testing"); } //Update/run the server private void onServer() { if( gamePanel.rtnServerState() == true ) { Log.d(TAG, "Start the server"); } serverHandler.post( updateRunnable ); } //Update/server final Runnable updateRunnable = new Runnable() { public void run() { //call the activity method that updates the UI updateServer(); } }; @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } public void onDestroy() { Log.d( TAG, "Destroying... " ); super.onDestroy(); } public void onStop() { Log.d( TAG, "Stopping... " ); super.onStop(); } } A: The Runnable object's run method is only called once, after a new Thread is created in response to your .start() call. Usually you do something like: final Runnable myRunnable = new Runnable() { public boolean running = true; public void run() { while(running){ doSomething(); } } }; But I'm not sure this is the best way to do this. The updateGame() method will be constantly called unnecessarily. Instead, put your server logic inside the runnable's run() method. In there use the while(running){...} construct I listed above but make sure there is some blocking call in there. Whether it be from a network socket, a BlockingQueue, etc. That way it won't needlessly loop. EDIT From discussion in comments. Leave final Runnable updateRunnable = new Runnable() { public void run() { //call the activity method that updates the UI updateGame(); } }; as it is and change new Thread(new Runnable() { onServer( ); } ).start( ); to Runnable server = new Runnable() { public boolean running = true; public void run() { while(running){ onServer(); // Make sure this blocks in some way } } } new Thread(server).start();
{ "pile_set_name": "StackExchange" }
Q: What is the standard guidelines for activity creation in Clearcase UCM? What is the standard guidelines for activity creation? In our team, all team members are creating activities by their own. It is not being assigned by team leader. Is it possible to create an activity by team leader then assign it to members? How to achieve it? A: Two ways you could go. ClearCase (stand alone): A trigger can enforce, the activity or the naming of the activity but this can require intial development of trigger and script & also the maitenance. You may also go part way in which you enforce the prefix to be ENH_* or DEF_* or CR_*. You can even check to see if total activity is in a list of strings you specify...limited to your need. Alternative (ClearCase with integration): What you may be looking for is a higher level order, I had created such a system with ClearCase integrated to ClearQuest. Developers are assigned "WorkRequests" (e.g. Defects / Enhancements) These can be directly assigned, tracked and added to builds. In essence you use the record ID acts node that holds all activities checked in by developer. You can report/slice/dice with activitis and checkin refs as you want) In this model you control the assigned record not the activity (but they can be the same! ie. raised records with known activties in advance and assign them.) Regards Jim2
{ "pile_set_name": "StackExchange" }
Q: Dynamically create instances of a class python I'm new in python and I'm trying to dynamically create new instances in a class. So let me give you an example, if I have a class like this: class Person(object): def __init__(self, name, age, job): self.name = name self.age = age self.job = job As far as I know, for each new instance I have to insert, I would have to declare a variable and attach it to the person object, something like this: variable = Person(name, age, job) Is there a way in which I can dynamically do this? Lets suppose that I have a dictionary like this: persons_database = { 'id' : ['name', age, 'job'], ..... } Can I create a piece of code that can iterate over this db and automatically create new instances in the Person class? A: Just iterate over the dictionary using a for loop. people = [] for id in persons_database: info = persons_database[id] people.append(Person(info[0], info[1], info[2])) Then the List people will have Person objects with the data from your persons_database dictionary If you need to get the Person object from the original id you can use a dictionary to store the Person objects and can quickly find the correct Person. people = {} for id, data in persons_database.items(): people[id] = Person(data[0], data[1], data[2]) Then you can get the person you want from his/her id by doing people[id]. So to increment a person with id = 1's age you would do people[1].increment_age() ------ Slightly more advanced material below ---------------- Some people have mentioned using list/dictionary comprehensions to achieve what you want. Comprehensions would be slightly more efficient and more pythonic, but a little more difficult to understand if you are new to programming/python As a dictionary comprehension the second piece of code would be people = {id: Person(*data) for id, data in persons_database.items()} And just so nothing here goes unexplained... The * before a List in python unpacks the List as separate items in the sequential order of the list, so for a List l of length n, *l would evaluate to l[0], l[1], ... , l[n-2], l[n-1]
{ "pile_set_name": "StackExchange" }
Q: Removing constant artifact/defect from several images I have several images, each of which has the same artifact/defect. Does anybody have a suggestion to remove such an artifact? The images are disordered arrays of dots. The artifacts include the 'squiggly worm' and the 'circular ripples' that you can hopefully identify by eye. I tried using the pixel median of all the images, like in this post, but I was unsuccessful. The following code will quickly import all the images. names = {"DgkH6V5", "QHgATwh", "CWMkitU", "IymdBJM", "BxkbVOj", "qyanXWZ", "6Wlvnr1", "upxv4EH"}; frames = Import["https://imgur.com/" <> # <> ".png"] & /@ names; A: For a start, you could consider that your artifacts are of a different frequency than the dots in the background which are slightly blurred: img = Import["https://i.stack.imgur.com/lTMs1.png"]; LowpassFilter[img, .4]
{ "pile_set_name": "StackExchange" }
Q: How do I combine multiple tables? (First has data from this month, second has all other previous data) I am looking to create a query that shows shipping number, the container ID, the tracking number, the location it was last moved to, what time it was moved, and who moved it. Here's the issue. We recently backed up or transaction history onto another table for anything that's over 30 days old. So I have the table transaction_history which gives me everything from today to 30 days ago, and I have the table AR_transaction_history, which gives me everything else (starting from 31 days ago.) I need to be able to create prompts for the user to input either the container ID, tracking number, or shipping ID. I need help joining the two tables to create 1 table with all the records. I tried union all and it does not work with my prompts. I tried an isnull statement and that didn't work either. Here is the code. select th.reference_id, th.container_id 'Container ID', sc.tracking_number 'Tracking Number', max(th.DATE_TIME_STAMP) 'Time of Last Touch', CASE WHEN th1.date_time_stamp = max(th.DATE_TIME_STAMP) then th1.user_name END AS 'User Name', CASE WHEN th1.date_time_stamp = max(th.DATE_TIME_STAMP) then th1.location END AS 'Location' from TRANSACTION_HISTORY th inner join TRANSACTION_HISTORY th1 on th1.CONTAINER_ID = th.CONTAINER_ID inner join SHIPPING_CONTAINER sc on sc.CONTAINER_ID = th.CONTAINER_ID group by th.container_id, sc.tracking_number, th1.DATE_TIME_STAMP, th1.USER_NAME, th1.LOCATION, th.REFERENCE_ID Having CASE WHEN th1.date_time_stamp = max(th.DATE_TIME_STAMP) then th1.user_name END is not null UNION ALL select th.reference_id, th.container_id 'Container ID', sc.tracking_number 'Tracking Number', max(th.DATE_TIME_STAMP) 'Time of Last Touch', CASE WHEN th1.date_time_stamp = max(th.DATE_TIME_STAMP) then th1.user_name END AS 'User Name', CASE WHEN th1.date_time_stamp = max(th.DATE_TIME_STAMP) then th1.location END AS 'Location' from AR_TRANSACTION_HISTORY th inner join AR_TRANSACTION_HISTORY th1 on th1.CONTAINER_ID = th.CONTAINER_ID inner join AR_SHIPPING_CONTAINER sc on sc.CONTAINER_ID = th.CONTAINER_ID group by th.container_id, sc.tracking_number, th1.DATE_TIME_STAMP, th1.USER_NAME, th1.LOCATION, th.REFERENCE_ID Having CASE WHEN th1.date_time_stamp = max(th.DATE_TIME_STAMP) then th1.user_name END is not null A: Do UNION ALL in a subquery, and leave the rest of your original query untouched. This is the simplest way to proceed, without reviewing the whole logic of your (aggregated) query. SELECT .... FROM ( SELECT * FROM TRANSACTION_HISTORY UNION ALL SELECT * FROM AR_TRANSACTION_HISTORY ) as th INNER JOIN SHIPPING_CONTAINER sc on sc.CONTAINER_ID = th.CONTAINER_ID GROUP BY ... Note: in general, SELECT * and UNION ALL do not get along well. This answer assumes that tables TRANSACTION_HISTORY and AR_TRANSACTION_HISTORY have exactly the same structure (columns and data types).
{ "pile_set_name": "StackExchange" }
Q: PostgreSQL: Efficiently split JSON array into rows I have a table (Table A) that includes a text column that contains JSON encoded data. The JSON data is always an array with between one and a few thousand plain object. I have another table (Table B) with a few columns, including a column with a datatype of 'JSON' I want to select all the rows from table A, split the json array into its elements and insert each element into table B Bonus objective: Each object (almost) always has a key, x. I want to pull the value of x out into column, and delete x from the original object (if it exists). E.g.: Table A | id | json_array (text) | +----+--------------------------------+ | 1 | '[{"x": 1}, {"y": 8}]' | | 2 | '[{"x": 2, "y": 3}, {"x": 1}]' | | 3 | '[{"x": 8, "z": 2}, {"z": 3}]' | | 4 | '[{"x": 5, "y": 2, "z": 3}]' | ...would become: Table B | id | a_id | x | json (json) | +----+------+------+--------------------+ | 0 | 1 | 1 | '{}' | | 1 | 1 | NULL | '{"y": 8}' | | 2 | 2 | 2 | '{"y": 3}' | | 3 | 2 | 1 | '{}' | | 4 | 3 | 8 | '{"y": 2}' | | 5 | 3 | NULL | '{"z": 3}' | | 6 | 4 | 5 | '{"y": 2, "z": 3}' | This initially has to work on a few million rows, and would then need to be run at regular intervals, so making it efficient would be a priority. Is it possible to do this without using a loop and PL/PgSQL? I haven't been making much progress. A: The json data type is not particularly suitable (or intended) for modification at the database level. Extracting "x" objects from the JSON object is therefore cumbersome, although it can be done. You should create your table B (with hopefully a more creative column name than "json"; I am using item here) and make the id column a serial that starts at 0. A pure json solution then looks like this: INSERT INTO b (a_id, x, item) SELECT sub.a_id, sub.x, ('{' || string_agg( CASE WHEN i.k IS NULL THEN '' ELSE '"' || i.k || '":' || i.v END, ', ') || '}')::json FROM ( SELECT a.id AS a_id, (j.items->>'x')::integer AS x, j.items FROM a, json_array_elements(json_array) j(items) ) sub LEFT JOIN json_each(sub.items) i(k,v) ON i.k <> 'x' GROUP BY sub.a_id, sub.x ORDER BY sub.a_id; In the sub-query this extracts the a_id and x values, well as the JSON object. In the outer query the JSON object is broken into its individual pieces and the objects with key x thrown out (the LEFT JOIN ON i.k <> 'x'). In the select list the pieces are put back together again with string concatenation and grouped into compound objects. This necessarily has to be like this because json has no built-in manipulation functions of any consequence. This works on PG versions 9.3+, i.e. since time immemorial insofar as JSON support is concerned. If you are using PG9.5+, the solution is much simpler through a cast to jsonb: INSERT INTO b (a_id, x, item) SELECT a.id, (j.items->>'x')::integer, j.items #- '{x}' FROM a, jsonb_array_elements(json_array::jsonb) j(items); The #- operator on the jsonb data type does all the dirty work here. Obviously, there is a lot of work going on behind the scenes, converting json to jsonb, so if you find that you need to manipulate your JSON objects more frequently then you are better off using the jsonb type to begin with. In your case I suggest you do some benchmarking with EXPLAIN ANALYZE SELECT ... (you can safely forget about the INSERT while testing) on perhaps 10,000 rows to see which works best for your setup.
{ "pile_set_name": "StackExchange" }
Q: CouchDB Futon custom URL I just installed CouchDB on my Ubuntu 12.04 server and I am trying to find a way to access Futon (the web based admin panel) using the IP of my computer or one of the domains I have binded on it. I have added the following below the [httpd] section in /etc/couchdb/local.ini port = 5984 bind_address = 0.0.0.0 But navigating to my_ip:5984 has no results. I restarted the CouchDB server several times though. Could you please help me out with that? A: Open port 5984 in firewall. And then: IP:5984/_utils/
{ "pile_set_name": "StackExchange" }