source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0037466408.txt" ]
Q: Java interface function with extra parameter I am beginner in Java and OOP. I have one interface, for example animal, that can shout. public interface Animal{ public void shout(); } My class Dog implement the interface, and can shout at anybody. public class Dog implements Animal{ public void shout(){ System.out.println("Woof woof"); } } I want a specific dog, class SmarterDog, that can shout to someone specific. So my function would be void shout(String somebody), so we have just one extra parameter, but still approximatively the same code. It's still an Animal, so it should implement Animal. How can I organize my code to simulate this function? What should I do for more complex functions? Should I create an extra function in the class that implements my interface? A: The method shout() in the interface and the method shout(String somebody) in the SmarterDog class have the same name but they are different methods. In Java, a method is not only identified by its name but also by its argument types. They might have some overlap in their implementation but that is not relevant. Interfaces are not about implementation. (Java 8 does allow you to define default method implementations in interfaces, but that is mostly a convenience feature added to the language.) What you could do is put the common code into a helper method in some other class and call it from both shout methods. You could also define a class responsible for shouting and add an instance of it to your animal objects. This is basically an implementation of the strategy pattern - sounds complicated but if your class hierarchy gets more complex, it might be worthwhile. The main advantage is that the "shouting" aspect of the Animal is separated from the other aspects. I would probably also change the name of the method with argument to shoutTo(String somebody) to make it clearer.
[ "stackoverflow", "0002792393.txt" ]
Q: See if item exists once in Enumerable (Linq) Given a list... class Item { public Name { get; set; } } List<Item> items = new List<Item> { new Item() { Name = "Item 1" }, new Item() { Name = "Item 1" }, new Item() { Name = "Item 2" }, new Item() { Name = "Item 3" } } List<Item> listing = new List<Item> { new Item() { Name = "Item 1" }, new Item() { Name = "Item 2" }, new Item() { Name = "Item 3" } new Item() { Name = "Item 4" } } etc. I need to create a third array that will cancel out double instances between the two; however items with "Name 1" are both the same, but different 'instances'. So the third List should have 1 instance of Item 1, since 'items' had 2 instances. Any ideas of how this can be done through Linq? A: First you need to create an EqualityComparer for Item. public sealed class ItemEqualityComparer : EqualityComparer<Item> { public override bool Equals(Item x, Item y) { return x.Name.CompareTo(y.Name) == 0; } public override int GetHashCode(Item obj) { return obj.Name.GetHashCode(); } } Then all you need to call is Union. var itemUnion = items.Union(listing, new ItemEqualityComparer());
[ "stackoverflow", "0048003439.txt" ]
Q: Disabling browserAction for my extension on all tabs I'm trying to add a "Disable" action in the context menu of my extension, to disable the extension until user decides to enable it back. Problem: chrome.browserAction.disable only works for one tab. How can I make it work for all existing and future tabs? A: Do not specify any tabId when calling chrome.browserAction.disable. Instead of calling chrome.browserAction.disable(tabId), use chrome.browserAction.disable(). That will disable the browserAction icon for all tabs. However, take into account that you will not be able to open the popup menu until you re-enable it.
[ "raspberrypi.stackexchange", "0000051829.txt" ]
Q: Unable to bring CAN interface up on Raspberry Pi 3 I followed a few tutorials on how to use CAN on Raspberry and most of them suggested I should add these lines to /boot/config.txt : dtparam=spi=on dtoverlay=mcp2515-can0,oscillator=16000000,interrupt=25 dtoverlay=spi-bcm2835-overlay I made the CAN controller on breadboard with MCP2515 and I'm pretty sure it is connected properly, including the INT pin from the MCP to GPIO25 on Raspberry. The schematic is here : http://3.bp.blogspot.com/-6iBPCZobUy4/UFB4djlVbwI/AAAAAAAAAj8/Fem4E_5u_bw/s1600/Design1+-+ARM+-+minimal+-+Schematic.png However, this command always fails : ip link set can0 up type can bitrate 500000 saying : cannot find device can0. I tried adding it manually: modprobe can ip link add can0 type can but when I try to bring the interface up again, the command hangs and I have to reboot the Pi in order to use it, because most of other unrelated commands hang as well. Finally, my questions are : Does the ip link commnad rely on proper can hardware in order to succeed ? What should I check in order to trace this problem ? A: UPDATE : It works now. There were several problems. At first, I thought the problem was caused by the kernel update, so I made a fresh SD card with kernel 4.4.13-v7+. Then someone on the Raspberry Pi forum pointed out that the overlays should be written without '-overlay' at the end (in /boot/config.txt). I added this to the /boot/config.txt and now I have two CAN interfaces. #CAN bus controllers dtoverlay=mcp2515-can0,oscillator=16000000,interrupt=25 dtoverlay=mcp2515-can1,oscillator=16000000,interrupt=24 dtoverlay=spi-bcm2835 Then I could enable them manually with : ip link set up can0 type can bitrate 500000 Then I made them start at boot by writing this in /etc/network/interfaces auto can0 iface can0 inet manual pre-up /sbin/ip link set can0 type can bitrate 500000 triple-sampling on up /sbin/ifconfig can0 up down /sbin/ifconfig can0 down auto can1 iface can1 inet manual pre-up /sbin/ip link set can1 type can bitrate 500000 triple-sampling on up /sbin/ifconfig can1 up down /sbin/ifconfig can1 down Final result shown by ifconfig : can0 Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 UP RUNNING NOARP MTU:16 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:10 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) can1 Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 UP RUNNING NOARP MTU:16 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:10 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
[ "stackoverflow", "0006851955.txt" ]
Q: Workaround to android:singleLine for items in a ListView without sacrificing itemClickListening functionality Due to this feature in ListViews, items cannot gain focus if you want ListView to be able to listen to click events through onItemClick or onListItemClick. Now this is a problem if you want a TextView in an item to be single-lined at the same time. Because if you set android:inputType="text", the TextView somehow becomes "clickable", thus gaining focus. I'm currently using android:singleLine="true" as a workaround, but it is listed as depreciated. Are there any "legit" or non-depreciating methods in doing this. A: Try.......... android:maxLines
[ "stackoverflow", "0040805920.txt" ]
Q: warning: control may reach end of non-void function [-Wreturn-type] } I am a beginner in c++ and I am trying to make a chess game and when I compile : bool isValidMove(int inCol, int inRow, int outCol, int outRow, char board[8][8]) { if (board[inRow][inCol] == '-') return false; else { if((board[inRow][inCol] == 'R' || board[inRow][inCol] == 'r') && isValidMoveRook(inCol, inRow, outCol, outRow, board)) return true; if((board[inRow][inCol] == 'K' || board[inRow][inCol] == 'k') && isValidMoveKnight(inCol, inRow, outCol, outRow, board)) return true; if((board[inRow][inCol] == 'R' || board[inRow][inCol] == 'r') && isValidMoveRook(inCol, inRow, outCol, outRow, board)) return true; } } I get this warning from my compiler warning: control may reach end of non-void function [-Wreturn-type] } can anyone help me with this problem by the way I am on the mac. A: You don't return anything at the very end if it doesn't go on your conditions. bool isValidMove(int inCol, int inRow, int outCol, int outRow, char board[8][8]) { if(board[inRow][inCol] == '-') { return false; } else { if((board[inRow][inCol] == 'R' || board[inRow][inCol] == 'r') && isValidMoveRook(inCol, inRow, outCol, outRow, board)) { return true; } if((board[inRow][inCol] == 'K' || board[inRow][inCol] == 'k') && isValidMoveKnight(inCol, inRow, outCol, outRow, board)) { return true; } if((board[inRow][inCol] == 'R' || board[inRow][inCol] == 'r')&& isValidMoveRook(inCol, inRow, outCol, outRow, board)) { return true; } } // return something here }
[ "stackoverflow", "0002407518.txt" ]
Q: Pass data to a HttpModule I have a funny little situation on my hands. I have a httpModule on my hands that I have to feed with context relative data. That means that on the page I have to set something that the HttpModule can then react on. If possible I would like to avoid having call context data in the session. Any bright ideas out there. thx for the answer. Edit: The HttpModule is working as a last minute interceptor. And my problem is that I am looking for a cleaver way of telling the HttpModule to: Intercept this call (changes dynamically, so can not be statically configured) Do some secret stuff with the data that I would like to pass to it Somehow make that action idempotent. Because it must not happen twice regardless of user actions and possible system errors. A: What do you mean you would like to avoid "having call context data in the session"? HttpContext is different to session, in the fact that it only lasts for the duration of the request. Session as its name suggests lasts for the entire session (which might include multiple requests). It might be a clean solution to use HttpContext as that is what it is there for. Regards, David Update: Should have mentioned you can access the current context via HttpContext.Current.Items.
[ "pt.stackoverflow", "0000013554.txt" ]
Q: Como desabilitar Migrations de um projeto com EF6? Olá! Tenho uma class library com modelos usando Code First e habilitei Migrations com o comando "enable-migrations" no PMC para testar e funciona muito bem. Como estou no inicio das definições de models, prefiro deixar isso para depois que fizer o primeiro deploy de produção. Como desabilito o Migrations do meu projeto? A: Coloque false no AutomaticMigrationsEnabled e quando precisar novamente coloque true. Exemplo: internal sealed class Configuration : DbMigrationsConfiguration<YourContext> { public Configuration() { AutomaticMigrationsEnabled = false; } } Também pode se usar Add-Migration InitialSchema -IgnoreChanges, para criar uma migration vazia sob o modelo atual. Nesse link, tem videos e explicações interessantes sobre o assunto, apesar de estar em inglês, o texto está muito fácil o entendimento. Referências Code First Migrations Code First Migrations and Deployment with the Entity Framework in an ASP.NET MVC Application
[ "stackoverflow", "0062427680.txt" ]
Q: Handling messages on a dead letter topic using Spring Kafka We currently have a Dead Letter Topic (DLT) configuration in place by using Spring Kafka (in a Spring Boot application). We are using the DeadLetterPublishingRecoverer within the SeekToCurrentErrorHandler. We assigned the latter one to the ConcurrentKafkaListenerContainerFactory. While processing our first messages; due to a stupid mistake in our service, we ended up with some NullPointerException exceptions and 20% of the messages ended up on the DLT (which is expected behaviour and is perfect for us). We fixed the bug, but now we want to process those 20% messages again. Possibilities we see: write a small application that copies the messages from the DLT to the original topic add a second @KafkaEventListener in our application which reads from the DLT Solution 2 is my preferred solution as moving it back to the original topic also implies that other consumer groups get the message again (should normally be OK, as all of our services are idempotent). I was wondering if there are other best practices to solve this problem. If not, I was also wondering how I can dynamically activate/deactive the @KafkaEventListener for the DLT (as you don't want to have this listener all the time up) Thanks for your feedback! Jochen A: Solution number 2 looks perfect to me. I was also wondering how I can dynamically activate/deactive the @KafkaEventListener for the DLT (as you don't want to have this listener all the time up) You can use the @KafkaListener property autoStartup, introduced since 2.2. @Autowired private KafkaListenerEndpointRegistry registry; @KafkaListener(id = "123", topics = "XXX.DLT", autoStartup = "true"){ //do your processing } //After you are done registry.getListenerContainer("123").stop();
[ "tex.stackexchange", "0000395575.txt" ]
Q: How to prevent tikzpicture contents from going outside of document bounds? I need text inside "node" command to automatically break at document margin and transition to next line as it does outside of tikzpicture. \documentclass [% border=10mm, varwidth=100mm ] {standalone} \usepackage{tikz} \begin{document} \begin{tikzpicture} \path node {% one two three four five six seven eight nine ten eleven twelve thirteen fourteen }; \end{tikzpicture} \end{document} Desired outcome: A: You can just use a minipage: \documentclass [% border=10mm, varwidth=100mm ] {standalone} \usepackage{tikz} \begin{document} \noindent\begin{tikzpicture}[inner sep=0] \path node {% \begin{minipage}{\linewidth} one two three four five six seven eight nine ten eleven twelve thirteen fourteen \end{minipage}% }; \end{tikzpicture} \end{document} "inner sep=0" option saves you from overfull hbox.
[ "stackoverflow", "0016963808.txt" ]
Q: foreach %dopar% slower than for loop Why foreach() with %dopar% slower than for. Some litle exmaple: library(parallel) library(foreach) library(doParallel) registerDoParallel(cores = detectCores()) I <- 10^3L for.loop <- function(I) { out <- double(I) for (i in seq_len(I)) out[i] <- sqrt(i) out } foreach.do <- function(I) { out <- foreach(i = seq_len(I), .combine=c) %do% sqrt(i) out } foreach.dopar <- function(I) { out <- foreach(i = seq_len(I), .combine=c) %dopar% sqrt(i) out } identical(for.loop(I), foreach.do(I), foreach.dopar(I)) ## [1] TRUE library(rbenchmark) benchmark(for.loop(I), foreach.do(I), foreach.dopar(I)) ## test replications elapsed relative user.self sys.self user.child sys.child ## 1 for.loop(I) 100 0.696 1.000 0.690 0.000 0.0 0.000 ## 2 foreach.do(I) 100 121.096 173.989 119.463 0.056 0.0 0.000 ## 3 foreach.dopar(I) 100 120.297 172.841 111.214 6.400 3.5 6.734 Some addition info: sessionInfo() ## R version 3.0.0 (2013-04-03) ## Platform: x86_64-unknown-linux-gnu (64-bit) ## ## locale: ## [1] LC_CTYPE=ru_RU.UTF-8 LC_NUMERIC=C LC_TIME=ru_RU.UTF-8 ## [4] LC_COLLATE=ru_RU.UTF-8 LC_MONETARY=ru_RU.UTF-8 LC_MESSAGES=ru_RU.UTF-8 ## [7] LC_PAPER=C LC_NAME=C LC_ADDRESS=C ## [10] LC_TELEPHONE=C LC_MEASUREMENT=ru_RU.UTF-8 LC_IDENTIFICATION=C ## ## attached base packages: ## [1] parallel stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] doMC_1.3.0 rbenchmark_1.0.0 doParallel_1.0.1 iterators_1.0.6 foreach_1.4.0 plyr_1.8 ## ## loaded via a namespace (and not attached): ## [1] codetools_0.2-8 compiler_3.0.0 tools_3.0.0 getDoParWorkers() ## [1] 4 A: It is specifically mentioned and illustrated with examples that indeed sometimes it's slower to set this up, because of having to combine the results from the separate parallel processes in the package doParallel. Reference: http://cran.r-project.org/web/packages/doParallel/vignettes/gettingstartedParallel.pdf Page 3: With small tasks, the overhead of scheduling the task and returning the result can be greater than the time to execute the task itself, resulting in poor performance. I used the example to find out that in some case, using the package resulted in 50% the time needed to execute the code.
[ "stackoverflow", "0010058291.txt" ]
Q: populating multi-table inherited models in django I am using models in following way: class UserProfile: # Some Stuff class CompanyProfile(UserProfile): # Some more stuff class CandidateProfile(UserProfile): # Even more stuff mean CompanyProfile and CandidateProfile are inheriting from UserProfile . How will I populate these CompanyProfile and CandidateProfile from whether registrationform and from another profileform? How will I tell it that which profile I am creating a user or entering data? A: I did it in following way that is in another thread on stackoverflow.com here : django user profile creation,set user profile while using multiple profile types , code is following: def save(self, commit=True): user = super(UserRegistrationForm, self).save(commit=False) user.email = self.cleaned_data["email"] if commit: user.save() person = Person(user=user) person.full_name = self.cleaned_data["fullname"] person.save() return user
[ "stackoverflow", "0054203031.txt" ]
Q: Vulkan on Android with Visual Studio There is a Vulkan Graphics API as part of the Android NDK which Visual Studio includes if you follow the instructions here. You can find the install location of this NDK by going to Tools > Options > Cross Platform > C++ > Android. So I went to that location with windows file explorer and did a search for "vulkan" and sure enough there are Vulkan header files and folders and such. I just don't know what the proper files I need to reference are and how to reference them within Visual Studio. Is it possible to develop a Vulkan Android app using Microsoft Visual Studio 2017? If so, how would I reference the Vulkan API from my native Android project? A: Yes, it's perfectly possible to build native Vulkan applications using Visual Studio 2017. To use Vulkan you only need to include the vulkan.h header file. That header will automatically include all other headers required for using Vulkan depending on your target platform. Note that older android platform versions (23 and lower) don't include the vulkan.so library, so if you target these you'd need to dynamically load the Vulkan function pointers, even for non-extension functionality.
[ "stackoverflow", "0009659834.txt" ]
Q: Find objects in a list that extend a certain class In my game, all game objects extend an Entity class. All enemy objects have their own class which extend Enemy. Enemy extends Entity. In other words, Entity -> Enemy -> SharkEnemy. Now, I want to have a function to let me test for collision against a specific class. That is, if for example I have a bullet class, I want it to only test for collision against entities that extend Enemy. I've googled around and this is what I have: public <T> Entity collide(Entity a, Class<T> desiredClass) { for (Entity b : entities) if (b.getClass() == desiredClass && collide(a, b)) return b; return null; } That is kind of what I want, but I need to know if it extends desiredClass, not if the class equals desiredClass. A: Instead of checking for class equality, use Class.isAssignableFrom() public <T> Entity collide(Entity a, Class<T> desiredClass) { for (Entity b : entities) if (desiredClass.isAssignableFrom( b.getClass() ) && collide(a, b)) return b; return null; }
[ "lifehacks.stackexchange", "0000020394.txt" ]
Q: How to prevent plugs from falling out of a wall socket? Despite carefully securing a plug in an outlet, many times I find that the plug falls out minutes after the fact (it happens all the time with things like phone chargers). I have been careful in making sure that the cord is loose enough so that it is not tugging on the plug in any way, yet this still happens. How can I prevent plugs from falling out of a wall socket? A: Replace the receptacle. It's starting to fail. Learn what "break off tabs" are, and look for them. The receptacles should be able to hold a small wall-wart. If it can't, then the thing falling out is the least of your problems. A poor gripping connection will also cause series arc faults, which will create heat and potential fire. It will cause galling that will damage the prongs and the socket, making further connections worse still. The saving grace is that it's a series arc fault, so the fault can't draw more current than the device does. But plug a heater in there later, and you could have big trouble! So shut the breaker off (check both sockets for voltage) and pull that receptacle. Take some photos first. Get a $3 Leviton ProLine or similar unit, not the 75 cent cheapies. Check the "break-off tabs" on both sides, realizing brass screws are a different side than silver screws, and match them on the new one. Then remove the wires from the old socket (loosen screws or stick a paperclip in the backstab release, or just twist it out of the backstab) one at a time and move them to the new socket exactly as you found them. Do not attempt to upgrade to a USB socket or GFCI without first coming over to diy.stackexchange.com with pix of what's there. Those fancy outlets wire up very differently than normal sockets, and the differences cause lots of wheel-spinning and frustation for a novice. Better to ask first, wait a day, read, breeze through the upgrade. Lastly, don't destroy position information. Wire location matters. If one white is with some blacks, that kind of thing is a Rosetta Stone. Don't tear all the old equipment out and post a picture like this, it won't end well. (Colors don't indicate what wires do). Colors are becuase of how cables are made, not what wires do. Take photos before you unhook anything. Do that and 95% of the time it'll go smoothly, and the diy stack can sort out the other 5%. A: If the outlet has two spots, use the lower spot; it usually provides better friction. As a janitor I always used the lower spots for carpet cleaners and other equipment with heavy cords. For a loose plug that you don't put in and take out a lot (e.g. the plug for a table lamp), try bending the prongs of the plug slightly apart. This will increase the friction holding the plug in place. Be careful not to damage the plug. Don't try this with your iPhone charger. For a small adapter like an iPhone charger, you can use a Post-It note to affix the cord to the wall above or below the outlet, which will reduce the amount of torque applied to the plug itself, and may even help hold it up. For large wall-warts (a.k.a. AC adapters) it is often more convenient to plug a power strip or even a simple extension cord into the wall and plug the AC adapter into the power strip. For a very large adapter, you can even put the adapter on its back and sort of plug the power strip down onto it.
[ "ru.stackoverflow", "0001050748.txt" ]
Q: Как закруглить при анимации углы иконки гамбургера Есть такой пример: document.querySelector('#svg').addEventListener('click', function() { [...document.querySelectorAll('.line')].forEach(s => { s.classList.contains('path-line') ? s.classList.remove('path-line') : s.classList.add('path-line'); }) }) * { padding: 0; margin: 0; box-sizing: border-box; } html, body { background-color: #272727; width: 100vw; height: 100vh; display: flex; justify-content: center; align-items: center; } svg { background-color: black; } #path_line_3 { stroke-dasharray: 30 43; stroke-dashoffset: 0; transition: all .2s; } #path_line_1 { stroke-dasharray: 30 43; stroke-dashoffset: 0; transition: all .2s; } #path_line_2 { stroke-dasharray: 30 43; stroke-dashoffset: 0; transition: all .2s; } #path_line_2.path-line { stroke-dasharray: 0 30; stroke-dashoffset: 0; } #path_line_3.path-line { stroke-dasharray: 43.4 30; stroke-dashoffset: -30; } #path_line_1.path-line { stroke-dasharray: 43.4 30; stroke-dashoffset: -30; } <svg id="svg" version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="500" height="500" viewBox="0 0 50 50"> <path id="path_line_1" class="line" d="M 10 10, 40 10, 10 40" stroke-linecap="round" fill="transparent" stroke="white " stroke-width="3" /> <path id="path_line_2" class="line" d="M 25 25, 40 25" stroke-linecap="round" fill="transparent" stroke="white " stroke-width="3" /> <path id="path_line_3" class="line" d="M 10 40, 40 40, 10 10" stroke-linecap="round" fill="transparent" stroke="white " stroke-width="3" /> </svg> Можно ли закруглить острые углы, отмеченные на картинке ниже. A: Не сразу понял что нужно кликнуть. За оформление соединения сегментов линий в SVG отвечает свойство stroke-linejoin оно может принимать такие-же значения как и stroke-linecap, который Вы уже использовали: bevel | miter | round Вам поможет stroke-linejoin="round" document.querySelector('#svg').addEventListener('click', function() { [...document.querySelectorAll('.line')].forEach(s => { s.classList.contains('path-line') ? s.classList.remove('path-line') : s.classList.add('path-line'); }) }) * { padding: 0; margin: 0; box-sizing: border-box; } html, body { background-color: #272727; width: 100vw; height: 100vh; display: flex; justify-content: center; align-items: center; } svg { background-color: black; } #path_line_3 { stroke-dasharray: 30 43; stroke-dashoffset: 0; transition: all .2s; } #path_line_1 { stroke-dasharray: 30 43; stroke-dashoffset: 0; transition: all .2s; } #path_line_2 { stroke-dasharray: 30 43; stroke-dashoffset: 0; transition: all .2s; } #path_line_2.path-line { stroke-dasharray: 0 30; stroke-dashoffset: 0; } #path_line_3.path-line { stroke-dasharray: 43.4 30; stroke-dashoffset: -30; } #path_line_1.path-line { stroke-dasharray: 43.4 30; stroke-dashoffset: -30; } <svg id="svg" version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="500" height="500" viewBox="0 0 50 50"> <path id="path_line_1" class="line" d="M 10 10, 40 10, 10 40" stroke-linecap="round" stroke-linejoin="round" fill="transparent" stroke="white " stroke-width="3" /> <path id="path_line_2" class="line" d="M 25 25, 40 25" stroke-linecap="round" fill="transparent" stroke="white " stroke-width="3" stroke-linejoin="round"/> <path id="path_line_3" class="line" d="M 10 40, 40 40, 10 10" stroke-linecap="round" fill="transparent" stroke="white " stroke-width="3" stroke-linejoin="round" /> </svg>
[ "stackoverflow", "0030024871.txt" ]
Q: How to prevent a column from being reordered in wpf I have written a wpf code for a grid, it has 5-6 columns, the first one being the name. I want to freeze this column, meaning that it should not be movable. I tried doing this <DataGridTemplateColumn Header="Name" Width="Auto" SortMemberPath="Name" CanUserReorder="False"> but the problem with this code is, I cannot move my name column to replace another column , but I can drag any other column in its place. For eg.. I can drag my shortName column in place of name column. I want that the name column should not move at all but the other columns can be movable. Can anyone help me with this? A: From MSDN: Frozen columns are always the leftmost columns in display order. You cannot drag frozen columns into the group of unfrozen columns or drag unfrozen columns into the group of frozen columns. so setting FrozenColumnCount ="1" should do the trick <DataGrid FrozenColumnCount="1" CanUserReorderColumns="True"> <DataGrid.Columns> <DataGridTextColumn Header="Name"/> <DataGridTextColumn Header="#1"/> <DataGridTextColumn Header="#2"/> <DataGridTextColumn Header="#3"/> </DataGrid.Columns> </DataGrid>
[ "music.stackexchange", "0000051578.txt" ]
Q: one of the saddle's springs on the bridge of my guitar is missing I picked this cheap guitar up from a pawn shop. As you can see the spring is missing! Will this affect the guitar or its ability to play? If so, How do I fix it? A: As you can already see, the saddle is out of position (note the head of the saddle position screw is not against the bridge plate as it should be. You just need to find a replacement spring. You might find something that will work at a hardware store or at an online or brick and more music instrument retailer. A: How do you fix it? Strip it down, and put another spring in! However, when the saddle is in the correct place, so it's intonated correctly, and it may even be there now, looking at it, tighten up the screw until its head just reaches the metalwork. At that stage, it could be left for ever, and not affect the intonation or playing of the guitar. As others have said, springs are available - even one from a ball-point retractable pen could do the trick!
[ "meta.askubuntu", "0000011816.txt" ]
Q: Is this screenshot uncool? I added a wallpaper screenshot to my answer to Architecture - 32-bit handling 64-bit instructions which was intended to illustrate the last sentence of the answer. Now I'm worried that I might have gone off the rails, and perhaps I should delete the screenshot. Is this screenshot uncool? A: I would not characterize that small summer breeze image as "going off the rails" or "uncool." When it comes to that picture, I don't think you need to worry about anything so serious. In my opinion, it doesn't add much to the post. But it doesn't really take anything away, either. It's small, reasonably unobtrusive, and arguably has the benefit of making the post more enjoyable. Or someone might consider it tedious or tangential. And maybe it effectively highlights the point about how installing 32-bit packages on a 64-bit system is the easier situation. Or maybe it distracts from it. Or maybe it makes no difference. Personally, I probably wouldn't have included such an image. I'd probably edit it out of my own post if someone else put it there. I strongly doubt I'd edit it out of anyone else's. And other people might really like it. I think if you feel your answer is subjectively better with the image in it, you should go ahead and keep it. This answer on Super User is widely liked. I upvoted it, though not for the images. While the pictures there are more strongly tied in to the answer's core message thematically, I think they're only slightly more relevant or useful than your summer breeze image. (The pictures there may even have the detrimental effect of conveying the message that Ubuntu users have to be more careful not to get hurt than Windows users, which is not true at all.) So: I think your screenshot is not a problem or a violation of our community norms or anything bad like that. But maybe you should remove it. If you're just worried because it's somewhat unusual, I'd suggest keeping it. But if on reflection you think the post isn't any better off with it, I'd suggest removing it.
[ "stackoverflow", "0055426254.txt" ]
Q: Union not picking up all ranges I'm having some challenges with a Union not working in a big macro. It's supposed to join together a few ranges but it only seems to pick up the first range. To help isolate the challenge I've trimmed all the code down to this: Dim copiedrange As Range Dim SrcWB As Workbook Dim SrcWS As Worksheet Set SrcWB = Workbooks("all-euro-data-2018-2019 (1)") Set SrcWS = SrcWB.Sheets("E1") i = 1 Set copiedrange = Union(SrcWS.Range("A" & i & ":F" & i), SrcWS.Range("AX" & i), _ SrcWS.Range("AZ" & i), SrcWS.Range("BH" & i & ":BJ" & i)) MsgBox copiedrange.Columns.Count End Sub For some reason the column count is coming back as 6 (A to F) when I think it should be higher to account for all the other ranges. What am I missing/getting wrong/being an idiot about??? Thanks in advance! A: Union is working absolutely fine. For example, MsgBox copiedRange.Address returns $A$1:$F$1,$AX$1,$AZ$1,$BH$1:$BJ$1. You're encountering the behavior of Range.Columns.Columns.Count is returning the number of columns in the first area ($A$1:$F$1). From the Range.Columns documentation: When applied to a Range object that's a multiple-area selection, this property returns columns from only the first area of the range. For example, if the Range object has two areas — A1:B2 and C3:D4 — Selection.Columns.Count returns 2, not 4. To use this property on a range that may contain a multiple-area selection, test Areas.Count to determine whether the range contains more than one area. If it does, loop over each area in the range.
[ "pt.stackoverflow", "0000090723.txt" ]
Q: Como funciona hibernate.hbm2ddl.auto? Quais são os values que posso utilizar nessa propiedade? ex: Update <prop key="hibernate.hbm2ddl.auto">update</prop> Como funciona? Quando devo utilizar? é uma boa prática? A: As opções são essas: validate: validar o schema, não faz mudanças no banco de dados. update: faz update o schema. create: cria o schema, destruindo dados anteriores. create-drop: drop o schema quando ao terminar a sessão. Ai você tem que avaliar o que é melhor para seu projeto, geralmente eu utilizo o update. Link da resposta no SOen link A: Como funciona? Respondida pelo nosso amigo Rafael. Quando devo utilizar? Isso é um pouco ambíguo, pois pode desencadear boas discussões, mas é bom pensar nisso como dar responsabilidade a uma tecnologia que teoricamente vai cuidar de todas as ações de desenvolvimento no database. Será que é uma boa idéia deixar acontecer de forma automática, a criação, atualização ou remoção de qualquer entidade pelo Hibernate? Não, por mais que o todo o desenvolvimento para o database forme o mesmo codebase, não significa que a automatização de um sobre o outro irá funcionar. Validar seus scripts de uma forma manual é sempre uma forma mais segura para o desenvolvimento. Nunca utilize isso em produção, pode ser um erro fatal. Mas podemos falar em contexto, se o seu contexto é fazer um projeto próprio de estudo e teste, talvez sim, mas eu não acredito que seja uma boa prática. Em minha experiência com ferramentas que costumam fazer algo relacionado a desenvolvimento de forma automática, tendem a falhar miseravelmente. é uma boa prática? Não. Vejo como uma péssima prática, tanto do lado do desenvolvedor quanto do lado do cliente que vai utilizar o produto. Dar responsabilidades de desenvolvimento a qualquer ferramenta não é uma boa prática. Boa prática é você ter total controle do produto, desde a forma como é entregue, até a sua arquitetura e code quality. Pense o quão simples é para o hibernate replicar uma linha de código errada sua para o database e dessa forma causar o caos e isso esteve totalmente fora do seu alcance. Mas como falei, podemos gerar boas discussões, pois se formos focar em boas práticas não utilizaríamos ORM, pois é com certeza um anti-pattern para Orientação a Objetos.
[ "stackoverflow", "0050886292.txt" ]
Q: Scanf value is executed as command in terminal I have simple go program that converts miles to kilometers: const kmInMile = 1.609344 func main() { var miles float64 fmt.Print("Enter miles: ") fmt.Scanf("%f", &miles) fmt.Println(miles) km := kmInMile * miles fmt.Println(miles, "miles =", km, "km") } If I pass "lls" as input to scanf: Enter miles: lls Output is: 0 0 miles = 0 km alexandrkrivosheev$ ls hello main.go so the first char of input was taken and all other were executed as command. Why does it happened and how can i prevent this? Full terminal session: alexandrkrivosheev$ ./hello Enter miles: lls 0 0 miles = 0 km alexandrkrivosheev$ ls hello main.go alexandrkrivosheev$ A: When using "plain fmt.Scanf" the input must match the expected format, ie in your case it must be valid float. If it isn't then the scanning is aborted and rest of the input remains in console's input buffer where it is executed as next command after your program exits. To fix this you wrap the stdin into an bufio.Reader or bufio.Scanner: func main() { var miles float64 fmt.Print("Enter miles: ") // reader := bufio.NewReader(os.Stdin) val, err := reader.ReadString('\n') if err != nil { fmt.Println(err) return } if _, err = fmt.Sscanf(val, "%f", &miles); err != nil { fmt.Println(val, err) return } fmt.Println(miles) km := kmInMile * miles fmt.Println(miles, "miles =", km, "km") } This way you consume whole line from input and process it separately.
[ "ru.stackoverflow", "0000570701.txt" ]
Q: Есть ли ошибки вертикального ритма в данном макете и где? Объясните, пожалуйста, какие ошибки присутствуют и как их исправить. A: В целом - хорошо. Проблемное место вижу вот здесь: Какой интерлиньяж вам нужно будет задать для текста? Полагаю, что-то около 2/3 ритма. Я бы сделал текст чуть просторнее и выставил 0.75 ритма, тогда высота для трех строк будет 0.75 * 3 = 2.25, хвостик в 0.25 ритма в целом допустим - и это лучше, чем возможные проблемы с недесятичным ритмом 2/3. Также я бы выделил под заголовки... ...не один ритм, с отступами по одному ритму, а два ритма, с отступами по пол-ритма: В этом случае, если заголовок пойдет в две строки, ему не будет тесно.
[ "judaism.stackexchange", "0000030337.txt" ]
Q: Shalom Bayis story to share at a Chuppah speech I am supposed to give a speech on a chuppah next week BSD. I am totally blank! Have had a few ideas to talk about, focusing on Shalom Bayit, but I cannot pick a nice one so everyone present can learn from it. Would anyone have any good and inspiring Shalom Bayis stories to share so I could pick one? A: I once posted this here: Story with the Lubavitcher Rebbe: A man once asked the Lubavitcher Rebbe if it is true that folding your tallis right after shabbos is a segulah for shalom bayis. The Rebbe answered, "I don't know about that, but rolling up your sleeves and doing the dishes after shabbos is a segulah for shalom bayis". A: Or this story from here It is important not to fall prey to the danger of forfeiting Shalom Bayit in the very process of pursuing the ideal of a blissful Jewish home. The story is told that one Friday night the Chafetz Chaim visited the home of a man who berated his wife for not remembering to cover the challot before the recitation of Kiddush, causing her to leave the table in tears. The Chofetz Chaim, in addressing this uncomfortable situation, was able to use his wisdom to give the intemperate husband a sense of perspective. Drawing from Jewish law sources, he pointed out to the man that one reason that we cover the challot is to shield the challot from the “embarrassment” of not receiving the first brocha of the meal. Accordingly, asked the Chafetz Chaim, how could Kiddush be recited when the man's own wife had been embarrassed? The man immediately understood the error of his ways and begged his wife for forgiveness. The importance of sensitive communications in the frantic frenzy of Shabbat preparations is an obvious application of this principle.
[ "stackoverflow", "0048261119.txt" ]
Q: Regular expression: remove the (* and *)-delimited comment and extract first and last words I am facing an Issue while using regular expression, Eg: I have something like this: Wynk (* it is a Music online music player ; We can listen a song online and offline *) PAID; youtube (* it is video player ; we can see the video online and we can download it *) free; In above mentioned example I need to remove the (* and *)-delimited comment and extract the data "Wynk" and "PAID" from the first line and "youtube" and "free" from the second. I have done something like this ($first_word) =$_ =~ /^\s*(\w+)/; ($last_word) = $_ =~ /(\w+)\s*\;$/; But I am not able to get perfect result for all data which looks similar to above mentioned example. A: You don't need two regexes. #!/usr/bin/perl use strict; use warnings; use feature 'say'; while (<DATA>) { # skip empty lines next unless /\S/; my ($first, $last) = /\b(\w+)\b.*\b(\w+)\b\s*;/; say "$first / $last"; } __DATA__ Wynk (* it is a Music online music player ; We can listen a song online and offline *) PAID; youtube (* it is video player ; we can see the video online and we can download it *) free; Output: Wynk / PAID youtube / free But I think this isn't very different from what you already had. So I suspect you probably need to give us more details about what a "perfect result" is.
[ "stackoverflow", "0062233665.txt" ]
Q: How to use np.random.randint() to roll n dice, noting that each has a potentially different number of faces denoted by a vector f I am trying to simulate the single roll of n dice, where each of the die can potentially have f faces. For example, if =[2,5,7], then three dice with 2, 5 and 7 faces are rolled. Thank you! A: I got it to work with this: f=[3,4,5] outcomes= [] for i in f: out = 1 + np.random.randint(i, size = len(f) ) outcomes.append(out) Thank you!
[ "math.stackexchange", "0003340873.txt" ]
Q: Limit point $p$ of $A \subset 2^\mathbb{R}$ such that no sequence in $A$ converges to $p$. Can $A$ be countable? The problem here is to find a subset $A \subset 2^\mathbb{R}$ and a limit point $p$ of $A$ such that no sequence in $A$ converges to $p$. Here, $2^\mathbb{R}$ is the product $\prod_{\lambda \in \mathbb{R}}\{0, 1\}$ equipped with the product topology. I think I have an example for when $A$ is not countable. Suppose $A$ is the set of all points $(x_i)_{i \in \mathbb{R}}$ such $$ (x_i) = 1 \hspace{0.5cm} \text{ if } i \in \mathbb{Q} \text{ and } \hspace{0.5cm}(x_i) = 0 \text{ or } 1 \hspace{0.5cm} \text{ if } i \in \mathbb{R}\setminus\mathbb{Q}. $$ Consider the point $p \in 2^\mathbb{R}$ such that $$ p(i) = \begin{cases} 1 & \text{for all } i \in \{\pi + q \mid q \in \mathbb{Q} \}\\ 0 & \text{otherwise } \end{cases} $$ Here $p(i)$ indicates the $i$-th coordinate (where $i$ is a real number) of the point $p \in 2^\mathbb{R}$. $\pi$ was chosen randomly; I just needed some irrational. Now any open set of $p$ must be of the form $$ \{(x_i) \in 2^\mathbb{R} \mid x_{\pi + q_1} = x_{\pi + q_2} = \cdots = x_{\pi + q_n} =1 \text{ where } q_1, q_2, \dots, q_n \in \mathbb{Q}\} $$ which will always intersect $A$. Hence, $p$ is a limit point of $A$. By a theorem in topology, if there exists a sequence of points in $A$ which converge to $p$, then $p \in \overline{A}$. And, I already proved that every open set in $2^X$ is closed for any $X$, so $A = \overline{A}$; however $p \not\in A$. Therefore there is no sequence. My questions: Is my work correct? Is it possible to find an example for when $A$ is countable? I've tried but can't seem to find one that works. I think it's supposed to be possible. A: For notational simplicity identify points in $2^\mathbb R$ with subsets of $\mathbb R$ in the natural way, i.e., identify a set with its characteristic function. Let $A$ be the set of all $x\in2^\mathbb R$ such that (1) $x$ is the union of finitely many open intervals with rational endpoints and (2) the measure of $x$ is less than $1$. Then $A$ is countable, and $\mathbb R$ is a limit point of $A$, but no sequence in $A$ converges to $\mathbb R$. (Each element of $A$ is a set of measure at most $1$; it follows from basic properties of Lebesgue measure that the limit of a sequence in $A$, if it exists, has measure at most $1$.)
[ "sharepoint.stackexchange", "0000007590.txt" ]
Q: How to debug a Custom Timer Job in SharePoint 2010? I have vs 2010, moss 2010, and I'm trying to debug a custom timer job, so I've set breakpoints on the feature receiver, but when I run the project or just right click deploy, my break points are never met. Here is the code, as you can see its just a standard feature receiver: public class StructureImportEventReceiver : SPFeatureReceiver { const string List_JOB_NAME = "StructureImporter"; public override void FeatureActivated(SPFeatureReceiverProperties properties) { SPSite site = properties.Feature.Parent as SPSite; // Break point is set on line above ... rest of code below } } I guess if I could get the debugger to stop on this breakpoint, I could step through to the rest of the timer job, but alas... nothing. What am I doing wrong? A: You need to attach to OWSTIMER process instead of w3wp to debug timer jobs. Don't forget to restart the service after deploying latest code to debug. A: There was a well-known technique to debug a custom timer job on MSDN: http://msdn.microsoft.com/en-us/library/cc406686.aspx#WSSCustomTimerJobs_DebuggingCustomTimerJobs The technique should be still valid in SharePoint 2010. Also check out: http://www.codeproject.com/KB/sharepoint/debugging-sharepointjobs.aspx
[ "stackoverflow", "0023248029.txt" ]
Q: How to code of UITableview detailtextLabel value dynamically? i want to code of UISlider Value Changed that time also UItableview detailTextLabel Value also be changed? see below Image. when i am change slider value dynamically change of detailTextLabel of Alert Range ? also store when i am come back with this UIview that also represent old value of slider and detailTextLabel. UISlider *slider = [[UISlider alloc]initWithFrame:CGRectMake(45, 45, 290,20)]; if(indexPath.row == 0) { NSString *sliderValue =[NSString stringWithFormat:@"%d KM",(int)[_defaults floatForKey:@"Slider"]]; cell.detailTextLabel.text = sliderValue; } if(indexPath.row == 1) { slider.minimumValue = 5; slider.maximumValue = 20; slider.value =(int)[_defaults floatForKey:@"Slider"]; cell.accessoryView = slider; } [slider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged]; } cell.textLabel.backgroundColor = [UIColor clearColor]; //[_table reloadData]; return cell; } -(void)sliderValueChanged:(id)sender { UISlider *slider = sender; [_defaults setFloat:slider.value forKey:@"Slider"]; //[_table reloadData]; } Thanks in Advance... A: Call [self.tableView reloadData]; each time the slider moves. Ensure the value you want to be dynamic is a property and is set by the slider. If you do not want to reload the entire tableView you can also reload the cell with this function: - (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation Check out this question for more help on reloadRowsAtIndexPaths: Reload specific UITableView cell in iOS
[ "stackoverflow", "0059898329.txt" ]
Q: Get background color in color picker I have to design a color picker with fixed values. As I'm a newbie to web programming I'm not sure how to proceed. The task is to get background color on selecting a palette's background and with that color, another div element's background has to change. In this HTML #palette has 30 colors, color-1 to color-30. On selecting the color from the palette the background of .color-container has to change. Thanks in advance. <div id="palette"> <div class="row"> <div class="colors" id="color-1"></div> <div class="colors" id="color-2"></div> <div class="colors" id="color-3"></div> <div class="colors" id="color-4"></div> <div class="colors" id="color-5"></div> <div class="colors" id="color-6"></div> </div> <div class="row"> <div class="colors" id="color-7"></div> <div class="colors" id="color-8"></div> <div class="colors" id="color-9"></div> <div class="colors" id="color-10"></div> <div class="colors" id="color-11"></div> <div class="colors" id="color-12"></div> </div> <div class="row"> <div class="colors" id="color-13"></div> <div class="colors" id="color-14"></div> <div class="colors" id="color-15"></div> <div class="colors" id="color-16"></div> <div class="colors" id="color-17"></div> <div class="colors" id="color-18"></div> </div> <div class="row"> <div class="colors" id="color-19"></div> <div class="colors" id="color-20"></div> <div class="colors" id="color-21"></div> <div class="colors" id="color-22"></div> <div class="colors" id="color-23"></div> <div class="colors" id="color-24"></div> </div> <div class="row"> <div class="colors" id="color-25"></div> <div class="colors" id="color-26"></div> <div class="colors" id="color-27"></div> <div class="colors" id="color-28"></div> <div class="colors" id="color-29"></div> <div class="colors" id="color-30"></div> </div> </div> <div class="color-container"> <h1 style="color: black" id="container-text">Text</h1> </div> A: You need to detect which div was clicked, all yours div elements has same colors class so that must be your selector, after that you need to extract the click div id. You can get it doing this: $('.colors').on('click', function () { var colorid = this.id; }); After that you can play with colorid value, I don't know how you going to specify which color is id color-1, color-2, etc. So just as an example I use a switch so your code is the following. $(document).ready(function () { $('.colors').on('click', function () { var colorid = this.id; switch(colorid) { case "color-1": $('.color-container h1').css("color", "red"); break; case "color-2": $('.color-container h1').css("color", "blue"); break; case "color-3": $('.color-container h1').css("color", "yellow"); break; case "color-4": $('.color-container h1').css("color", "orange"); break; } }); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <div id="palette"> <div class="row"> <div class="colors" id="color-1">1</div> <div class="colors" id="color-2">2</div> <div class="colors" id="color-3">3</div> <div class="colors" id="color-4">4</div> <div class="colors" id="color-5"></div> <div class="colors" id="color-6"></div> </div> <div class="row"> <div class="colors" id="color-7"></div> <div class="colors" id="color-8"></div> <div class="colors" id="color-9"></div> <div class="colors" id="color-10"></div> <div class="colors" id="color-11"></div> <div class="colors" id="color-12"></div> </div> <div class="row"> <div class="colors" id="color-13"></div> <div class="colors" id="color-14"></div> <div class="colors" id="color-15"></div> <div class="colors" id="color-16"></div> <div class="colors" id="color-17"></div> <div class="colors" id="color-18"></div> </div> <div class="row"> <div class="colors" id="color-19"></div> <div class="colors" id="color-20"></div> <div class="colors" id="color-21"></div> <div class="colors" id="color-22"></div> <div class="colors" id="color-23"></div> <div class="colors" id="color-24"></div> </div> <div class="row"> <div class="colors" id="color-25"></div> <div class="colors" id="color-26"></div> <div class="colors" id="color-27"></div> <div class="colors" id="color-28"></div> <div class="colors" id="color-29"></div> <div class="colors" id="color-30"></div> </div> </div> <div class="color-container"> <h1 style="color: black" id="container-text">Text</h1> </div> This should solve your problem.
[ "stackoverflow", "0021196745.txt" ]
Q: Set automatic buffer name to folder/filename or clojure namespace I'm new to emacs and wanting my buffers to be automatically named folder/filename or clojure.namespace.filename. I've found Uniquify which will rename conflicting buffers but I can't see how to use it as the default. Is there a way to do this or alternatively, a more idiomatic way of identifying buffers in emacs? A: You can use uniquify M-x customize-group <return> uniquify <return>, which allows including enough of the relative path in the buffer name to differentiate buffers. If you want to use the clojure namespace of the file as the buffer name there is the rename-buffer function, which could be passed a name generated with the help of clojure-mode which can tell you what namespace that file defines via clojure-expected-ns or clojure-find-ns. There is also the option of setting a header or mode-line entry besides the buffer name.
[ "stackoverflow", "0056580962.txt" ]
Q: Does keep alive only matter with outbound requests? If I have a client that may be making a request to an http Google Cloud Function multiple times in a relatively short amount of time how can I use keep-alive? Is having the client send the connection keep-alive header enough? I saw this on the Google docs: https://cloud.google.com/functions/docs/bestpractices/networking const http = require('http'); const agent = new http.Agent({keepAlive: true}); /** * HTTP Cloud Function that caches an HTTP agent to pool HTTP connections. * * @param {Object} req Cloud Function request context. * @param {Object} res Cloud Function response context. */ exports.connectionPooling = (req, res) => { req = http.request( { host: '', port: 80, path: '', method: 'GET', agent: agent, }, resInner => { let rawData = ''; resInner.setEncoding('utf8'); resInner.on('data', chunk => { rawData += chunk; }); resInner.on('end', () => { res.status(200).send(`Data: ${rawData}`); }); } ); req.on('error', e => { res.status(500).send(`Error: ${e.message}`); }); req.end(); }; But, that would only apply to making outbound requests from the cloud function right? There was also something about the global (instance-wide) scope here: https://cloud.google.com/functions/docs/bestpractices/tips Is there anything I need to do to reuse connections on requests sent from the end user? A: When you define agent at the global scope in your function, that is only retained for as long as any given server instance where that is running. So, while your connections may keep alive in that one instance, it will not share any connections with other instances that are allocated when the load on your function increases. You don't have much direct control over when Cloud Functions will spin up a new instance to handle new load, or when it will deallocate that instance. You just have to accept that they will come and go over time, along with any HTTP connections that are kept alive by global scope objects.
[ "stackoverflow", "0059875594.txt" ]
Q: How to test a Spring Controller that is secured I currently have an app built with Spring Boot 2, Spring MVC, Spring Data/JPA and Thymeleaf. I'm writing some unit/integration tests and I'd like to test the controller, which is secured by SpringSecurity backed by a database with registered users. What would be the best approach here to test it? I've unsuccessfully tried a few of them like using annotations like @WithMockUser. Edit: Just a reminder that I'm not testing @RestControllers. I'm directly injecting a @Controller on my test class and calling its methods. It works just fine without Spring Security. One example: @Controller public class SecuredController { @GetMapping("/") public String index() { return "index"; } } The / path is secured by Spring Security and would normally redirect to /login to authenticate the user. My unit test would look like this: @WebMvcTest(controllers = SecuredController.class) class SecuredControllerTest { @Autowired private SecuredController controller; @Autowired private MockMvc mockMvc; @Test @WithMockUser(username = "user", password = "pass", roles = {"USER"}) public void testAuthenticatedIndex() throws Exception { mockMvc.perform(get("/")) .andExpect(status().isOk()) .andDo(print()); } } The first errors I get is that is asks me to inject my UserDetailsService implementation, which is something that I'd like to avoid. But if I do inject the service, the test works, but returns 404 instead of 200. Any ideas? A: You will need to add your security configurations to the Spring context by importing your WebSecurityConfigurerAdapter class. @WebMvcTest(controllers = SecuredController.class) @Import(SecuredControllerTest.Config.class) class SecuredControllerTest { @Configuration @EnableWebSecurity static class Config extends MyWebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("pa$$").roles("USER"); auth.inMemoryAuthentication().withUser("admin").password("pa$$").roles("ADMIN"); } } ... } The embedded static class Config is just to change where we get the users from, in this case an inMemoryAuthentication will be enough.
[ "es.stackoverflow", "0000035380.txt" ]
Q: ¿Qué sucede con el puntero original luego de hacer realloc en uno temporal? Estoy desarrollando una aplicación que exige colocar/liberar y recolocar memoria de forma algo excesiva, pero tengo una duda con respecto al uso de la función realloc(void *, size_t), tengo el siguiente código: void Resize(void *ptr, size_t sz) { if (ptr == NULL || sz == 0) return; /* No se ve afectado. */ void *tmp = realloc(ptr, sz); /* Aquí sucede mi problema. */ if (tmp == NULL) return; /* No pasa nada en caso de NULL */ /* Otra logica... */ } En la línea: void *tmp = realloc(ptr, sz); mi pregunta es la siguiente: Si luego de esta línea libero la memoria de ptr de la siguiente manera: free(ptr); ¿El puntero tmp seguirá siendo válido y apuntará hacia la nueva^ dirección de memoria dada por realloc? ^: Digo nueva porque no sé si realloc funciona como malloc para dar direcciones de memoria al cambiarlas de tamaño. A: Si luego de esa línea liberas ptr, tmp dejará de ser válido. Aquí tienes un ejemplo: #include <stdlib.h> int main(int argc, char *argv[]) { int *ptr; int *tmp; ptr = malloc(128); tmp = realloc(ptr, 256); free(ptr); free(tmp); return 0; } Al ejecutar el código obtienes: Error in `./test': double free or corruption (top): 0x00000000019cb010 realloc funciona como malloc si ptr es NULL. Si size es 0 entonces realloc funciona como free. Aquí otro ejemplo: #include <stdlib.h> #include <stdio.h> int main(int argc, char *argv[]) { int *ptr; int *tmp; ptr = malloc(128); tmp = realloc(ptr, 256); printf("%p == %p\n", ptr, tmp); free(ptr); return 0; } Y verás que ambas direcciones son iguales.
[ "math.stackexchange", "0001985425.txt" ]
Q: Taylor Series of trigonometric function I searched quite a bit online but could only find the MACLAURIN SERIES of $\sin x$ and $\cos x$: $$\sin x = x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!}+\cdots$$ $$\cos x = 1 - \frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!}+\cdots$$ Can anyone explain how we can express the TAYLOR SERIES of $\sin x$ and $\cos x$, and also show me the derivation? Thanks in advance! A: Hint/Partial Solution: Recall the definition of the Taylor Series formula at a point $a$: $$\sum_{k=0}^\infty \frac{f^{(k)}(a)}{k!}(x-a)^k$$ (Note that $f^{(k)}(a)$ is a short-hand for the $k$th derivative of $f(x)$ evaluated at $a$) Letting $f(x)=\sin x$, we note that the numerator of the fraction is the following cycle: $$\sin(c), \cos(c), -\sin(c), -\cos(c), \cdots$$ The rest is just going to be expanding the series. It won't condense well if $a$ is not a rational multiple of $\pi$ though. The same logic follows for the cosine expansion. As an example of this, let $x=1$. Then we get the following series: $$\sum_{k=0}^\infty \frac{\sin^{(k)}(1)}{k!}(x-1)^k$$ Expanded, this becomes $$\sin(1)+(x-1) \cos(1)-\frac{1}{2}(x-1)^2 \sin(1)-\frac 16 (x-1)^3 \cos(1)+\frac{1}{24} (x-1)^4 \sin(1)+\cdots$$ After seeing this, you might think to yourself that this could be broken up into a sum without any derivative symbols. That hypothetical you is right! We can rewrite this as $$\sum_{k=0}^{\infty} \left(\frac{\sin(1)(-1)^k}{(2k)!}(x-1)^{2k}+\frac{\cos(1)(-1)^{k+1}}{(2k+1)!}(x-1)^{2k+1}\right)$$ A similar formula emerges for the cosine expansion, but I leave that up to the OP!
[ "stackoverflow", "0018792877.txt" ]
Q: Find the dominant cyclic substring of a given string I am looking for an algorithm to find the dominant cyclic substring of a given string. A cyclic substring: a substring which is repeated two or more times adjacently. A dominant cyclic substring: The substring which has the most adjacent repetitions is dominant (adjacent repetitions occur an equal number of times) the longest length substring is dominant (on ties of length and adjacent repetitions) the substring that appears first is dominant Example 1: prefixgarbagecyclecyclecyclecyclesufixgarbage returns cycle:=> cycle is the most repeated adjacent substring Example 2: prefixgarbagecyclepadinggarbagecyclesufixgarbage returns g:=> occurrences of cycle are not repeated adjacently, g repeats twice adjacently Example 3: prefixgarbagecyclecyclepadinggarbageprefixgarbage returns cycle:=> cycle & g repeat twice adjacently but cycle is longer then g Example 4: prefixgarbagecyclecyclecycleroundroundroundprefixgarbage returns cycle:=> cycle & round repeat thrice adjacently & same length but cycle appeared first Exampe 5: abcdefghijklmnopqrstuvqxyz returns <empty string> because there is no repeated adjacent substring What is the best approach for implementing this algorithm? A: Cannot find anything better than this quadratic-time algorithm (implemented in Python): IREP, IPER, IPOS = 0, 1, 2 def find_dominant(src): best = (0, 0, 0) # repetitions-1, period, position period = 0 while period < len(src) // max(2, 1 + best[IREP]): period += 1 length = 0 for pos in range(len(src) - 1 - period, -1, -1): if src[pos] == src[pos + period]: length += 1 repetitions = length // period if repetitions >= best[IREP]: best = (repetitions, period, pos) else: length = 0 return best s = "prefixgarbagecyclecyclecyclecyclesufixgarbage" res = find_dominant(s) if res[0] == 0: print("nothing found") else: print(res[IREP] + 1, '*', s[res[IPOS]: res[IPOS] + res[IPER]]) For each possible period scan the string and remember the longest periodic subsequence. Scan it backwards to check less conditions. Stop increasing period when no further improvement could be found. Time complexity is O(N2 / R), where R is the number of repetitions of dominant substring. Space complexity is O(1).
[ "rus.stackexchange", "0000431717.txt" ]
Q: Нужна запятая перед КАК? Друг — это тот, кто всегда поинтересуется как у тебя дела? A: Друг — это тот, кто всегда поинтересуется, как у тебя дела. Запятая ставится перед придаточной изъяснительной частью предложения, КАК — союзное слово, "поинтересуется" — опорный глагол со значением речи. Это сложноподчиненное предложение с двумя придаточными с последовательной связью: 1) местоименно-определительное, 2) изъяснительное.
[ "stackoverflow", "0012345485.txt" ]
Q: concept of Interfaces in C# I am trying to get a better understanding of the interfaces in C# and other OOP languages. What does an interface do? Why is it needed? I know c# and Java do not allow multiple inheritance. Most books say interfaces are the one way to get around the single inheritance restriction and allow different classes to have a common functionality. Interfaces just define the methods and forces the classes to implement them. Why not have the class define and implement methods itself without dealing with an interface? For example: 4: using System; 5: 6: public interface IShape 7: { 8: double Area(); 9: double Circumference(); 10: int Sides(); 11: } 12: 13: public class Circle : IShape 14: { 15: public int x; 16: public int y; 17: public double radius; 18: private const float PI = 3.14159F; 19: 20: public double Area() 21: { 22: double theArea; 23: theArea = PI * radius * radius; 24: return theArea; 25: } . . . Why can't the Circle class define and implement the Area(), Circumference() and Sides() methods itself? If a square class inherits the IShape, the Circumference() methods will have to be unimplemented. Am I way off in my understanding of interfaces? A: Interfaces are for when you want to say "I don't care how you do it, but here's what you need to get done". Refer this link for more clarifications. A: An object in C# may have functions that are actually a composite of different categories; a classic example of this is the Teacher example: In this example, the Teacher has the characteristics of a Person (e.g. Eye Colour) (although I've had some teachers that may break this example) and the characteristics of an Employee (e.g. Salary) C# doesn't allow for multiple inheritance so instead we look to the idea of composition using interfaces. It is often described this way: Inheritance implies that if Cat inherits from Animal then Cat "is-a" Animal Composition implies that if Cat implements Noise then Cat "has-a" Noise Why is this distinction important? Well, imagine our Cat. We could actually have Cat inherit from Feline, which in turn inherits from Animal. One day, we decide that we are going to support other types of Animal, so we decide to revise Animal, but then we realise that we are going to be pushing these changes to every other sub type. Our design, and hierarchy is suddenly quite complicated, and, if we didn't get it right to begin with, we have to extensively redesign all of our child classes. A rule is to Prefer Composition over Inheritance , but note the use of the word Prefer - it's important, because it doesn't mean that we should just use composition, but instead, our design should consider when inheritance is useful and when composition is useful too. It also reminds us that sticking every possible method ever in the base class is a bad idea. I like your shape example. Consider: Our ShapeSorter might have a method like this: public bool Sort(Shape shape) { foreach(Hole hole in Holes) { if(Hole.Type == HoleType.Circular && shape is Circle) { return true; } if(Hole.Type == HoleType.Square && shape is Square) { return true; } if(Hole.Type == HoleType.Triangular && shape is Triangle) { return true; } } return false; } Or, we could do some slight inversion of control: public bool Sort(Shape shape, Hole hole) { return hole.Accepts(shape); //We end up pushing the `if` code into Hole } Or some variant thereof. We are already writing a lot of code that relies on us knowing the exact sort of Shape. Imagine how tedious it gets to maintain when you have one of these: So, instead, we think to ourselves - is there a more generic way we can describe our problem by distilling it down to the relevant properties? You've called it IShape: public interface IShape{ double Area {get;} double Perimeter { get; } //Prefer Perimeter over circumference as more applicable to other shapes int Sides { get; } HoleType ShapeType { get; } } Our Sort method would then become: public Hole Sort(IShape shape) { foreach(Hole hole in Holes) { if(hole.HoleType == shape.ShapeType && hole.Area >= shape.Area) { return hole; } } return null; } Which looks neater, but isn't really anything that couldn't have been done via Shape directly. The truth is that there is no truth. The most common approach will involve using both inheritance and composition, as many things in the real world will be both of a type and will also have other attributes best described by an interface. The most important thing to avoid is sticking every possible method in the base class and having huge if statements to work out what the derived types can and can't do - this is a lot of code that is hard to maintain. Also, putting too much functionality in base classes can lead to setting your code in concrete - you wont want to revise things later because of all the potential side effects.
[ "stackoverflow", "0050269921.txt" ]
Q: Creating an object for one time use When passing an object to a function in Ballerina should we always create a variable then new it and pass it. Can't we create the object for one time use? For example I can call the HTTP respond function as follows: http:Response res; _ = caller->respond(res); But I cannot call it like this: _ = caller->respond(new); Is it mandatory in Ballerina to always define a variable before passing it to a function or is there a simpler workaround? A: The following example works. Did you come across any issues? import ballerina/http; service<http:Service> hello bind {port:9090} { hi (endpoint caller, http:Request request) { _ = caller->respond(new); } }
[ "stackoverflow", "0035772873.txt" ]
Q: Symfony/Doctrine - createQueryBuilder orderBy I have a 'Team' Entity with a property 'budget'. I just want to print the teams properties and i want that the team with the biggest budget appear in first position, the second, the third... (DESC). But with this code, it does not work and i don't understand why. indexAction (controller) $em = $this->getDoctrine()->getManager(); $teams = $em->getRepository('FootballBundle:Team')->getAllTeamsSortedByDescBudget(); return $this->render('FootballBundle:Default:index.html.twig', array( 'teams' => $teams, )); TeamRepository public function getAllTeamsSortedByDescBudget() { $q = $this->createQueryBuilder('a'); $q->select()->from('FootballBundle:Team', 't')->orderBy('t.budget', 'DESC'); return $q->getQuery()->getResult(); } twig view <h1>Teams list</h1> <ul> {% for team in teams %} <li>{{ team.name }} - {{ team.championship }} - {{ team.budget|number_format(2, '.', ',') }}£</li> {% endfor %} <br/> </ul> Team.php entity /** * @var integer * * @ORM\Column(name="budget", type="integer") */ private $budget; And here, the result ... Teams list Manchester City FC - Premier League - 100,000,000.00£ Arsenal FC - Premier League - 50,000,000.00£ Leicester City - Premier League - 20,000,000.00£ Crystal Palace FC - Premier League - 5,000,000.00£ Chelsea FC - Premier League - 100,000,000.00£ Chelsea... lol EDIT : CORRECTED ! See the takeit comment. A: Change your QueryBuilder query in getAllTeamsSortedByDescBudget method to: public function getAllTeamsSortedByDescBudget() { $qb = $this->createQueryBuilder('t') ->orderBy('t.budget', 'DESC'); return $qb->getQuery()->getResult(); }
[ "english.stackexchange", "0000340029.txt" ]
Q: Forest or forests? Which is right? Is "forest" countable or not? Having checked it in dictionary, it is still unclear to me. I'm considering to the following context. Our company owns 20 locations (or places) of forest across the country. A: The noun form of forest is countable, eg "There are many forests in France". However, it can be used as an adjective (meaning 'in a forest', or "from a forest"), and adjectives aren't pluralized. For example, your sample sentence could be rewritten as "Our company owns 20 forest locations across the country." which is using the adjectival form of "forest", and which states that you own locations (eg buildings) which are located inside forests. If you own the forests themselves (which is less likely) you would just say "Our company owns 20 forests across the country."
[ "magento.stackexchange", "0000193728.txt" ]
Q: Magento 2 : Translate string in function in knockout template In a Magento Knockout template I find a function like so: <element data-bind="something: function() { return 'some string'; }" /> How can I translate this string? I tried following, but it does not work: <element data-bind="something: function() { return $t('some string'); }" /> The translation exists and works in other places, so that is not the problem. A: Try adding i18n: in front of the value of data-bind attribute. Something like below; <element data-bind="i18n: something: function() { return $t('some string'); }" /> Note: Please note that the translation for corresponding string should be present in your language translation csv.
[ "stackoverflow", "0006743316.txt" ]
Q: Minimal perfect hash function I have many integers in range [0; 2^63-1]. There is only 10^8 integers, however. There is no duplicates. Full list is known at compile-time but it is just unique random numbers. These numbers never changes. To store one integer explicitly, 8 bytes required, and there is associated 1-byte values, so explicit storing requires about 860 MB. So I want to find minimal perfect hash function to map each of 10^8 integers from [0;2^63-1] to [0;10^8-1]. I should find this function only once, data never changes, and function can be complicated. But it should be minimal, perfect, and calculating should be fast. How I can do this better? Maybe it is possible to find and use some subsequences if they happens? Thanks. A: Let your computer do the work for you: http://www.gnu.org/software/gperf/ Quote: "GNU gperf is a perfect hash function generator. For a given list of strings, it produces a hash function and hash table, in form of C or C++ code, for looking up a value depending on the input string. The hash function is perfect, which means that the hash table has no collisions, and the hash table lookup needs a single string comparison only. " A: I'm working on an algorithm and Java implementation that needs less than 1.6 bits per key. Previously, I have implemented a minimal perfect hash function tool in Java that needs less than 2.0 bits per key. Other algorithms are implemented in CMPH. For example CHD needs about 2.06 bits per key by default. It can be configured to use less space, but generation is then slower.
[ "math.stackexchange", "0001655967.txt" ]
Q: $L^p$ norm of certain trigonometric polynomials bounded by $L^p$ norm of second derivative Let $f$ be a trigonometric polynomial on the circle $\mathbb{T}$ with $\hat{f}(j) = 0$ for all $j \in \mathbb{Z}$ with $\lvert j \rvert < n$. I want to show $$ \|f''\|_p \geq Cn^2 \| f \|_p. $$ for some $C$ independent of $n$ and $f$ and $1 \leq p\leq \infty$. I also have a result that may be useful: if $(a_n)_{n \in \mathbb{Z}}$ is an even ($a_n = a_{-n}$) sequence of nonnegative numbers with $a_n \to 0$ and $$ a_{n+1} + a_{n-1} - 2 a_n \geq 0 \quad \forall n > 0, $$ then there is an $f \in L^1(\mathbb{T})$ with $f \geq 0$ and $\hat{f}(n) = a_n$. I am struggling to find an entrance into the problem. I would most appreciate a hint that allows me to start. I have tried finding a convolution kernel that would give information via Young's inequality, but this seems unlikely. I would appreciate references that contain more detail as well. Update I have the weaker result $\| f'' \|_p \geq Cn^{3/2} \| f \|_p$. My method uses the observation $f = g \ast f''$ where $\hat{g}(j) = 1/j^2$ and Young's inequality. I can take $\hat{g}(j) = 0$ for $\lvert j \rvert < n$, and bounding $\| g \|_1$ by $\|g \|_2 = \| \hat{g} \|_{\ell^2}$ gives my weaker result. A correct method must then bound $\| g \|_1$ directly, perhaps using some sort of positivity coming from the stated result on convex Fourier coefficients. I am working on this now, though I may bounty soon. A generalization of this result: $\| f' \|_p \geq Cn \|f \|_p$ holds, but this is harder to prove. This exercise comes from the book by Schlag and Muscalu. A: If $(a_n)_{n \in \mathbb{Z}}$ is an even sequence of nonnegative numbers with $$ a_{n+1} + a_{n-1} - 2a_n \geq 0 \quad \forall n > 0, $$ then there exists $g \in L^1(\mathbb{T})$ with $g \geq 0$ and $\hat{g}(n) = a_n$. This is lemma 1.12 in Classical and Multilinear Harmonic Analysis Vol 1 by C. Muscalu and W. Schlag. The desired function is $$ g = \sum_{n=1}^\infty n (a_{n+1} + a_{n-1} - 2a_n) K_n $$ where $K_n$ is the Fejér kernel. Define the sequences $(a_{n,j})_{j=0}^\infty$ by $$ a_{n,j} = \begin{cases} \frac{1}{n^2} + \frac{2(n-j)}{n^3},& \text{if } j < n\\ \frac{1}{j^2}, & \text{if } j \geq n \end{cases} $$ for each $n \in \mathbb{N}$. Then (extending to $j \in \mathbb{Z}$ by $a_{n,(-j)} = a_{n,j}$) we can use the lemma to find $g_n \in L^1(\mathbb{T})$ with $g_n \geq 0$ and $\hat{g}_n(j) = a_{n,j}$. By the monotone convergence theorem, we have $$ \|g_n \|_1 = \sum_{j=1}^\infty j(a_{n,(j+1)} + a_{n,(j-1)} - 2 a_{n,j}). $$ A computation will show that $\| g_n \|_1$ is dominated by $n^{-2}$. Furthermore, for any trigonometric polynomial $f$ with $\hat{f}(j) = 0$ for all $| j | < n$, we have $$ f = g_n \ast f'' $$ so that Young's inequality finishes the proof. Someone posted this question at this Math Overflow thread, and another proof has been posted there.
[ "stackoverflow", "0026091648.txt" ]
Q: setTexture changes size of my sprite to smaller, ¿bug? I have a problem with [setTexture:string] because as you can see, sometimes the size of the sprite changes to a smaller one and there's not such that thing in my code. The only weird thing I have found is when I don't move the player, which is when I do touchesBegan() and then touchesEnded() without touchesMoved()it doesn't change size of the sprite, but when I do touchesMoved()and then release the finger, I have this bug and it's like random. Anybody got an idea of what it can be or if there is a bug with setTexture?? A: I was having lots of trouble with this as well. But setting the size after setting the texture fixes the problem (even though the textures are the same size). The thing that caught me most off-gaurd is that even though the sprite becomes smaller, an NSLog of the size outputs the original size (not something smaller). CGSize originalSize = mySprite.size; mySprite.texture = [SKTexture textureWithImage:image]; mySprite.size = originalSize;
[ "stackoverflow", "0011322112.txt" ]
Q: There is a downside to overwrite an object instead of update appengine storage? i have a class like: class myclass{ Long id; String a; Text b; } in the examples in the documentation for appengine, to update an object, we must recover it from the DataStore, modify it and then close the PersistenceManager. what if i overwrite it without recover it from the DataStore? i have that object cached, so i have your id and others properties A: You can overwrite it directly without first loading the previous values. (Blind Update) However, this does not work if you need to know these old values, for example in a partial update of only certain fields.
[ "stackoverflow", "0023493712.txt" ]
Q: Android LatLng parsing I want to display adress on marker clicked on the android map. I used GeoCoder for getting adress but OnMapLongClick function doesn't have lat,long parameters. It's parameter is (LatLng latlng). My code below ; @Override public void onMapLongClick(LatLng latLng) { Geocoder geoCoder = new Geocoder( getBaseContext(), Locale.getDefault()); try { List<Address> addresses = geoCoder.getFromLocation(lat, lng, 1); if (addresses.size() > 0) { for (int index = 0; index < addresses.get(0).getMaxAddressLineIndex(); index++) filterAddress += addresses.get(0).getAddressLine(index) + " "; } }catch (IOException ex) { ex.printStackTrace(); }catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } googleMap.addMarker(new MarkerOptions().position(latLng).title(filterAddress)).showInfoWindow(); markerClicked = false; } How can I parse or how can i convert latlng object to lat, lng parameters? A: try this way extract Latitude and Longitude from LatLng @Override public void onMapLongClick(LatLng latLng) { Double lat=latLng.latitude; Double longi=latLng.longitude; ......... .......... //do your job }
[ "stackoverflow", "0007056958.txt" ]
Q: Mongoid embeds_many with default order How can I set default order to my embeded objects, like: class Post embeds_many :comments, :order => "author" accepts_nested_attributes_for end Now I handle it with passing order straight: f.fields_for :comments, @post.comments.asc(:author) do |comment| ... end A: In mongoid 3.1.2 you can do something like this: embeds_many :favorites, order: :title.desc It also works with :title.asc
[ "stackoverflow", "0024881769.txt" ]
Q: Authorized App prompting with wrong App by Google OAuth login I am trying to use OAuth for Google+ login in my App, the flow working perfectly but the issue facing is very strange. Native App created Client ID: My client ID Secrect: My secrect ID Google+ button to OAuth request token LOgin page Authorize or Grant (below image) have display wrong App. In Google console project I have another client for this App also and this will be used in iOS. For Android OAuth I am using Native client id to obtain Access and Refresh token. I am stuck here Thanks A: I found the solution, actually I created single project under Google Console in that I have set details -> APIs & AUth -> Consent Screen and create Client ID under this project that's why it will displaying this project name instead of What I want for another App. For this type of things need to create separate project in you account and create Client ID or Keys for respective project. Hope this will help to other.
[ "stackoverflow", "0006866467.txt" ]
Q: How to track php functions/codes duration of processing I am developing a browser based game and i'd like to know which functions take the most time to process and so on. Does anyone of you guys know what I can start with ? Using PHP 5.3 A: It sounds like you want xhprof. It excels at profiling.
[ "stackoverflow", "0036772068.txt" ]
Q: 'The given key was not present in the dictionary' - but the key exists I am currently developing a MS Dynamics CRM 2013 - Plugin. When I try to assign a string-value to a key of a field of an entity it gives me the 'keynotfound'-exception. This leaves me clueless, because I can verify the key is existing. The key I give is also written correctly, and the data types are compatible, too. Here's some extra info: I tried resolving the issue with a server reboot. Nothing. Remote Debugging is not an option. I swapped "retrieved.EntityCollection.Entities[i][forField]" with retrieved.EntityCollection.Entities[i]["new_name"] and everything was working fine (kind of pointing out the obvious here, but "new_name" is not the key I try to access). The execution stops @ "if (retrieved.EntityCollection.Entities[i][forField].ToString() != "" && !overwriteExisting)" Have you got an idea to help me out? public void GenerateNumberForEntityCollection(string target) { try { // variables for number generation bool overwriteExisting = (bool)preImageEntity["new_overwriteexisting"]; int suffixstart = (int)preImageEntity["new_suffixstart"]; string forField= preImageEntity["new_forfield"].ToString(); string prefix = preImageEntity["new_prefix"].ToString(); string postfix = preImageEntity["new_postfix"].ToString(); string separator = preImageEntity["new_separator"].ToString(); // Build query to get all the entries RetrieveMultipleResponse retrieved; int PageNumber = 1; string PagingCookie = string.Empty; int PageSize = 5000; string[] Columns = { forField }; QueryExpression query = new QueryExpression() { EntityName = target, ColumnSet = new ColumnSet(Columns), PageInfo = new PagingInfo() { PageNumber = 1, Count = PageSize } }; do { if (PageNumber != 1) { query.PageInfo.PageNumber = PageNumber; query.PageInfo.PagingCookie = PagingCookie; } RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest(); retrieve.Query = query; retrieved = (RetrieveMultipleResponse)service.Execute(retrieve); // Now that all entities are retrieved, iterate through them to gen. the numbers int i = 0; foreach (Entity entity in retrieved.EntityCollection.Entities) { if (retrieved.EntityCollection.Entities[i][forField].ToString() != "" && !overwriteExisting) { //continue; } else { retrieved.EntityCollection.Entities[i][forField] = prefix + separator + suffixstart.ToString() + separator + postfix; } suffixstart++; service.Update(retrieved.EntityCollection.Entities[i]); i++; } if (retrieved.EntityCollection.MoreRecords) { PageNumber++; PagingCookie = retrieved.EntityCollection.PagingCookie; } } while (retrieved.EntityCollection.MoreRecords); } catch (Exception e) { tracing.Trace("GenerateNumberForEntityCollection: Failed: {0}", e.ToString()); } } A: When you are querying data in Dynamics CRM it is important to know that record fields having null values in the database are not included in the Attributes collection of the Entity instances being returned. Getting a value from an Entity's Attribute with this construct: var value = retrieved.EntityCollection.Entities[i][forField].ToString(); succeeds when attribute forField already has a value in the database, but fails when its current value is null. Therefore the preferred method to get the attribute values from an entity is GetAttributeValue<T>, like this: var value = retrieved.EntityCollection.Entities[i].getAttributeValue<string>(forField); This method returns the value when the attribute exists in the attribute collection, otherwise it returns null.
[ "stackoverflow", "0022317870.txt" ]
Q: JTree from ArrayList not displaying nodes I have a custom data structure that is basically just a named ArrayList of ArrayLists. Similar to XML. (have stripped out un-nesecary code) public class Element extends ArrayList<Element> { private String name; public Element(String n){ name = n; } @Override public String toString(){ return name; } } I am trying to display this in a JTree using a custom TreeModel class. However the JTree does not display properley. Only one node is displayed at the end of a branch, when the child node is selected it shows the last child node but when un-selected it shows the first child node, but still at the end of the branch. From extensive de-bugging I can see it reads the all the child nodes and count correctly it just doens't display them. I suspect they are all being displayed on top of each other but don't know why or what to do about it. Any thoughs appreciated. public class TestModel implements TreeModel{ Element data; TestModel(){ data = new Element("data"); data.add(new Element("One")); data.add(new Element("Two")); data.add(new Element("Three")); data.add(new Element("Four")); data.add(new Element("Five")); } @Override public Object getRoot() { return data; } @Override public Object getChild(Object parent, int index) { if(parent instanceof Element){ Element p = (Element)parent; Element child = p.get(index); return child; } return null; } @Override public int getChildCount(Object parent) { if(parent instanceof Element){ Element e = (Element)parent; return e.size(); } return 0; } @Override public int getIndexOfChild(Object parent, Object child) { if(parent instanceof Element){ Element e = (Element)parent; return e.indexOf(child); } return -1; } @Override public boolean isLeaf(Object node) { //List<? super ArrayList> d = (List<? super ArrayList>) node; if(node instanceof Element){ Element e = (Element)node; return e.isEmpty(); } return true; } } A: The problem is the way in which you are using the Element class and extending it from ArrayList. This comes down to how the hashcode is calculated from an ArrayList (or AbstractList to be more accurate. The hashcode is calculted based on the elements in the ArrayList, which is 0 for all the child Elements, resulting in a hashcode of 1 for all of them, which is causing issues with the List look up and uniquely identifying the elements. Personally, I would create a Node class which contained a List member and which provided additional functionality that could work with the TreeModel or just use TreeNode... For example... import java.awt.BorderLayout; import java.awt.EventQueue; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.event.TreeModelListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.MutableTreeNode; import javax.swing.tree.TreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; public class TestTree { public static void main(String[] args) { new TestTree(); } public TestTree() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { } JTree tree = new JTree(new TestModel()); JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(new JScrollPane(tree)); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public static class TestModel implements TreeModel { Element data; TestModel() { data = new Element("data"); data.add(new Element("One")); data.add(new Element("Two")); data.add(new Element("Three")); data.add(new Element("Four")); data.add(new Element("Five")); } @Override public Object getRoot() { return data; } @Override public Object getChild(Object parent, int index) { System.out.println("GetChild from " + parent + " @ " + index); if (parent instanceof Element) { Element p = (Element) parent; Object child = p.getChildAt(index); System.out.println("child = " + child); return child; } return null; } @Override public int getChildCount(Object parent) { if (parent instanceof Element) { Element e = (Element) parent; System.out.println("childCount = " + parent + "; " + e.getChildCount()); return e.getChildCount(); } return 0; } @Override public int getIndexOfChild(Object parent, Object child) { if (parent instanceof Element && child instanceof Element) { Element e = (Element) parent; System.out.println("indexOf " + child + " in " + parent + " is " + e.getIndex((Element)child)); return e.getIndex((Element)child); } return -1; } @Override public boolean isLeaf(Object node) { //List<? super ArrayList> d = (List<? super ArrayList>) node; if (node instanceof Element) { Element e = (Element) node; System.out.println("isLeaf " + e + "; " + (e.getChildCount() == 0)); return e.getChildCount() == 0; } return true; } @Override public void valueForPathChanged(TreePath path, Object newValue) { } @Override public void addTreeModelListener(TreeModelListener l) { } @Override public void removeTreeModelListener(TreeModelListener l) { } } public static class Element implements TreeNode { private List<Element> nodes; private Element parent; private String name; public Element(String n) { nodes = new ArrayList<>(25); name = n; } @Override public String toString() { return name; } protected void setParent(Element parent) { this.parent = parent; } public void add(Element node) { node.setParent(this); nodes.add(node); } public void remove(Element node) { node.setParent(null); nodes.remove(node); } @Override public TreeNode getChildAt(int childIndex) { return nodes.get(childIndex); } @Override public int getChildCount() { return nodes.size(); } @Override public TreeNode getParent() { return parent; } @Override public int getIndex(TreeNode node) { return nodes.indexOf(node); } @Override public boolean getAllowsChildren() { return true; } @Override public boolean isLeaf() { return nodes.isEmpty(); } @Override public Enumeration children() { return Collections.enumeration(nodes); } } } Or you could just use one of the pre-defined TreeNode classes, like DefaultMutableTreeNode
[ "stackoverflow", "0038773815.txt" ]
Q: Alter Table add Foreign Key Reference I'm doing a tutorial to learn perl/catalyst and it seems to be a little out of date. I'm trying to alter an already existing column, which was previously a primary key (Already dropped the primary key), into a foreign key. I've tried a bunch of different configurations of the syntax and can't seem to pin it down. This is my most recent attempt: ALTER TABLE book_author ( MODIFY book_id INTEGER ADD CONSTRAINT FOREIGN KEY book_id REFERENCES book(id) ON DELETE CASCADE ON UPDATE CASCADE ); Any advice is appreciated. A: You use parentheses like you are doing in a CREATE TABLE statement, but not in an ALTER TABLE statement. You are also missing a comma between the MODIFY and the ADD CONSTRAINT lines. And you are missing parentheses around the column book_id which is the subject of the constraint. The following works: ALTER TABLE book_author MODIFY book_id INTEGER, ADD CONSTRAINT FOREIGN KEY (book_id) REFERENCES book(id) ON DELETE CASCADE ON UPDATE CASCADE; This syntax is documented on the official MySQL site: http://dev.mysql.com/doc/refman/5.7/en/alter-table.html
[ "math.stackexchange", "0000801580.txt" ]
Q: Find the Laurent series expansion in powers of z Find the Laurent series expansion in powers of $z$ of $$f(z)=\frac{e^{2z}} {z}$$ valid in the region $|z|>$0. Any help appriciated. Thanks A: The Maclaurin series of $e^{2z}$ is $$ 1 + (2z) + \frac{(2z)^2}{2!} + \cdots = \sum_{k=0}^\infty \frac{2^k z^k}{k!} $$ so the Laurent series you're looking for is simply $1/z$ times this, i.e.: $$ \sum_{k=0}^\infty \frac{2^k z^{k-1}}{k!} = \sum_{k=-1}^\infty \frac{2^{k+1} z^{k}}{(k+1)!}. $$ The Maclaurin series of $e^{2z}$ converges on all of $\mathbb{C}$, since $e^{2z}$ is entire. Hence the Laurent series above converges for $z \neq 0$.
[ "stackoverflow", "0040125508.txt" ]
Q: R - eliminating duplicate values I have an input dataframe like this: I want the output to be like this: For example, I want to take up the first value(mary has life), scan it against all other rows which have duplicate COL1 entries and if a duplicate COL2 value is present I need to eliminate duplicates alone while merging non-duplicates. In other words, I want to do pattern search. If the same pattern is present in another row, I just want to eliminate duplicate patterns and merge non-duplicate patterns. I tried using the grepl and gsub functions but I am not able to get my desired result properly. Inserting a simpler version of input dataset below: COL1 COL2 10 mary has life 10 Don mary has life 10 Britto mary has life 20 push them 20 push them fur 30 yell at this 30 this is yell at this 40 Year 40 Doggy 40 Horse A: After your update: df <- read.table( text = "COL1; COL2 10; mary has life 10; Don mary has life 10; Britto mary has life 20; push them 20; push them fur 30; yell at this 30; this is yell at this", sep = ";", header = TRUE, strip.white = TRUE, stringsAsFactors = FALSE) library(dplyr) res <- df %>% group_by(COL1) %>% do(COL2 = { first_value <- .$COL2[[1]] paste(unlist(Reduce(function(a, b) { new_values <- strsplit(b, first_value)[[1]] c(a, new_values) }, .$COL2)), collapse = ", ") }) res$COL2 <- unlist(res$COL2)
[ "stackoverflow", "0024515791.txt" ]
Q: Get heatmap data without plotting the heatmap I want to extract the structure values of a heatmap plot but I don't need to plot the heatmap. Is there a way to do that? The function I used is heatmap. dm<-matrix(1:100,nrow=10) ht<-heatmap(dm) v1<-ht$rowInd v2<-ht$colInd v3<-ht$rowV v4<-ht$colV as you can see from the above, the heatmap was plotted. I am wondering if there is way to extract v1 to v4 without plot ht. Thanks. A: So you basically just want the dendrogram information. You can just calculate that yourself the same way heatmap() does. dm<-matrix(1:100,nrow=10) Rowv <- as.dendrogram(hclust(dist(dm))) rowInd <- order.dendrogram(Rowv) Colv <- as.dendrogram(hclust(dist(t(dm)))) colInd <- order.dendrogram(Colv) Then if you want to plot the heatmape without recalculating the dendrograms, you can run heatmap(dm, Rowv=Rowv, Colv=Colv)
[ "stackoverflow", "0003244891.txt" ]
Q: What is the better way to switch between portrait and landscape interfaces? I have two different views (portrait and landscape) for each screen (home, user info, etc). The difference between portrait and landscape views is enough to have each one into a different view and view controller because it's not only a relocation and resizing of controls. To perform the switching between the two views I have a container view controller with landscapeView_ and portraitView_ properties and into - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration I do the switching. This behavior is inherited from iPhone programming but now, in iPad, is this approach correct or it's another way to do the switching? A: I'm fairly sure that's the best way to do it. You probably do this, but I would make sure you support all four orientations - they're sticklers for multiple orientations on the iPad. Another place to make sure everything is kosher is in your Info.plist file - adding some keys like "Initial interface orientation", "Supported interface orientations", and/or "Supported Interface Orientations (iPad)" or "... (iPhone)" can add some clarity, i.e. when you submit.
[ "stackoverflow", "0002800321.txt" ]
Q: WCF Service Issue I am facing issue of the WCF Services on staging server. The same service is running perfectly in my local pc. But when i configured the same on staging server it is giving issue saying that: The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication, because it is in Faulted state. Is it related to security or anything else? How can i fix the issue? Regards, Om A: This might have some security issue. See how you have implemented the security. If you are using the default, the windows authentication credentials are used. For doing this, you need both the client and server use the same windows user account. Otherwise, you can use impersonation or if you don't have an issue, use no authentication to test. The channel comes into fault if no fault contract is defined or there is some un-handled exception on the server side. Look at the possible exceptions and try loggin the exceptions on the server side.
[ "academia.stackexchange", "0000015528.txt" ]
Q: Having a lot of papers published in unimportant conferences VS very few in good ones? I'm always confused when I see a lot of PhD students looking to publish papers, even if the papers are not so good. They publish them in not so important conferences or workshops. Is that a good thing? Is it good to have a lot of papers published even in not so popular conferences? Like what is better: to have 10 papers in not so famous conferences or workshops or 1 or 2 in a very famous and good ones? I have never published a paper before and new to this. A: People do things for a variety of reasons. Even writing a paper for smaller workshops has some benefits for everyone (from a PHD student to a professor) Good reason for the affiliation to cover expenses for the suggested trip. Usually CS workshops are co-located with important conferences and even a workshop paper may cover your expenses (not every time if you continuously abuse the system) to actually watch the entire conference. Workshops have limited attendance but may still be organized by reputable professors / scientists close to your area of interest. So, they are very good for networking. In a major conference, it is easier to get "lost" inside the many participants. Practise makes better. If you write 5 papers (even when some of them were for a workshop) writing your 6th paper is going to be easier, instead of trying to write your "seminal" paper. Reviewers have the "strange" habit of sometimes rejecting your paper. In this case, sending your paper to a smaller workshop (after rejection in 1-2 major conferences) where it gets accepted, lessens the sense of rejection and still "patents" your results on which you can expand later. Workshops sometimes have a "best paper award" which may even lead to journal publication, when the same paper might not had a chance in a bigger conference. In workshops the competition is smaller (usually 10-15 accepted papers), so you have something like 5-8% chance for something like that. Sometimes when you work on a specific project you might discover something that although is not good enough for a major conference or later expansion, is still a compact solid idea that may help others. So, a good workshop paper may disseminate this idea to a larger audience. Unfortunately, although quality should beat quantity, this is not the usual case. In some research projects, grants applications it is better to state that "A is the author of more than 50 scientific papers with an h-index of ... " than "B is the author of 2 papers". Same when you look at the Google Scholar / DBLP record of an author. It is better to see 50 papers (which among them are 10 really seminal papers) instead of just 10 perfect papers that usually leave a gap in the author's bibliography (blank years). In this sense, even workshop papers serve their purpose if you treat them as professionally as the rest of your papers (they are well written and still scientifically solid and correct). A: For the purposes of getting a PhD, the quality of the paper is more important than the venue. Quality is always better than quantity, as it will only be your best papers that end up being cited and having an influence on your field of research, so you are better off in the long run focussing on quality work and avoid wasting your time on work that will not give a true account of your ability and that will not be taken up by others in your field. A: There are two objectives in participating for academic conference. First one would be networking. This is getting to know the other academic and industry personals that are working, studying and researching in similar field. This will open many opportunities for PhD students. Other advantage would be constructive criticisms. Experts who take part in such conference will give constructive comments for your presentation. The questions they raise may show you a new way of looking at your research question. Likewise there are many advantages a PhD student may get by taking part in conferences. A good conference is a one which is relevant to your research area, which is popular among the experts in the respective field and one which many expert and interested parties will take part. Thus in my opinion education institutes, supervisors and of course PhD student should prioritize the quality of conference before counting the number of conferences that you attend.
[ "gaming.stackexchange", "0000351726.txt" ]
Q: Do Workshop codes work in multiple platforms? Do custom Workshop game modes work on all platforms or just the one where it was created? As an example, let's say that I create a Workshop gamemode on PC, can my friend use the same code on PS4 to get my Workshop Configuration? A: I have Overwatch on PC and PS4 and the codes work cross-platform. Source: Tested it multiple times myself.
[ "stackoverflow", "0056128724.txt" ]
Q: Mock Document for Jest Testing I have a function like so inside a react component: handleOnScroll = () => { const {navigationSections, setNavigationSectionActive} = this.props; const reversedSections = this.getReversedNavigationSections(); const OFFSET_TOP = 32; const st = window.pageYOffset || document.documentElement.scrollTop; if (st > lastScrollTop) { for (let i = 0; i < navigationSections.length; i += 1) { if(document.getElementById(navigationSections[i].id).getBoundingClientRect().top <= OFFSET_TOP) { setNavigationSectionActive(navigationSections[i].id); } } } else if (st < lastScrollTop) { for (let y = 0; y < reversedSections.length; y += 1) { if(document.getElementById(navigationSections[y].id).getBoundingClientRect().top <= OFFSET_TOP) { setNavigationSectionActive(navigationSections[y].id); } } } lastScrollTop = st <= 0 ? 0 : st; } and some of the tests like so: it('should handle handleOnScroll', () => { instance.handleOnScroll(); expect(instance.getReversedNavigationSections()).toEqual(props.navigationSections.reverse()); }); props.navigationSections.forEach(navSection => { it('should call setNavigationSectionActive', () => { instance.handleOnScroll(); expect(props.setNavigationSectionActive).toHaveBeenCalledWith(navSection.id); }); }); the first test passes but the second one ('should call setNavigationSectionActive') fails as you can see: I think the reason is because the document is not mocked therefore the if fails. However, in the actual implementation when this gets executed: document.getElementById(navigationSections[i].id).getBoundingClientRect().top the DIVs that have these IDs are in another section (not in the wrapper component used for the test in question). should I mock the document to mimic the actual structure for the if statement to pass or am I completely wrong? MY ATTEMPT SO FAR it('should handle custom handleOnScroll', () => { document.body.innerHTML = '<div><div id="id">my div</div><div id="id-1">my div</div></div>'; const div = document.getElementById('id'); div.getBoundingClientRect = () => ({ top: 100 }); // <= mock getBoundingClientRect instance.handleOnScroll(); props.navigationSections.forEach(() => { if (global.document.getElementById('id').getBoundingClientRect().top <= global.OFFSET_TOP) { expect(props.setNavigationSectionActive).toHaveBeenCalledWith('id'); } }); }); A: The default test environment for Jest is jsdom which provides a browser-like environment. If your test requires specific content in document then you can set the document body by using something like document.body.innerHTML. jsdom implements a lot of browser functionality, but not everything. In this case getBoundingClientRect is stubbed to always return 0 so if you want it to return something else you'll have to mock it. Here is a simple working example to get you started: const OFFSET_TOP = 5; const func = () => document.getElementById('theid').getBoundingClientRect().top <= OFFSET_TOP ? 'less' : 'more'; test('func', () => { document.body.innerHTML = '<div id="theid">my div</div>'; expect(func()).toBe('less'); // Success! const div = document.getElementById('theid'); div.getBoundingClientRect = () => ({ top: 10 }); // <= mock getBoundingClientRect expect(func()).toBe('more'); // Success! });
[ "stackoverflow", "0045846182.txt" ]
Q: CI 3.1.0 base url creating issue while opening website with www.domainname.com and domainname.com This is how I define my base URL: $config['base_url'] = 'http://royalarcdevelopments.ca'; Now this is a live link you can test it yourself: what happens is if i open this url using the path http://royalarcdevelopments.ca , royalarcdevelopments.ca it loads fine for both! But when I load it using the URL www.royalarcdevelopments.ca I receive this error: (index):1 Access to Font at 'http://royalarcdevelopments.ca/fonts/Poppins-Medium.ttf' from origin 'http://www.royalarcdevelopments.ca' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.royalarcdevelopments.ca' is therefore not allowed access. now I know that my base URL is not using www so it throws the error to me! My question is, how can we modify base URL so that it accepts a request from every path type! A: Generally speaking, the www and non-www versions of the same domain are two different fully qualified domains. Due to security reasons, some resources (like fonts in your particular case) violate the CORS policy - it results in the error you are receiving. One solution would be to modify your web server's config so it allows the delivery of font files for cross origin requests. A better solution would be (also from a SEO point of view) to redirect one of the domains to the other one, so you have only one "official" domain for your website. This can also be done from your web server's config or even from Codeigniter code, for example via some pre_controller hook. This way, when a visitor tries to access your secondary domain (let's say the www version in your particular case), it gets redirected to your primary domain (the non-www) and there is no more trouble with CORS. Redirect as early as you can: First, if you have access to the web server's configuration, implement redirection there; Second, if you are using Apache as the web server, implement redirection in a .htaccess file; If none of the above options are available for you, then do it from your application code.
[ "stackoverflow", "0004482260.txt" ]
Q: TFS Work items: user in the "Assigned to" field is the only user who can update this work item I am creating my own process template using process editor on Visual Studio 2010 & TFS 2010. I want to modify work item type definition to achieve any of the following: The work item can only be updated by the user assigned to it (the user in the "System.AssignedTo" field). Other users should not modify the work item. Work item state field "System.State" can only be modified by this work item assigned user. Thanks in advance A: It seems that both your questions are the same question: How to restrict the option of changing a work item, or specific fields in a work item, to all users but the one to whom the work item is "Assigned To"?? I have a solution for you, but it will not work in MTM, only in visual studio. 1) You build a simple custom work item control (find samples here - http://witcustomcontrols.codeplex.com/) with no UI. 2) In the control you override the FlushToDatasource method, and code in your condition for saving the work Item, such as - is the current user is the same as the "Assigned To" user? 3) If you condition is not set throw an exception with the proper massage. "You don't Permission to save\change the work item" To get the current user: _workItem.Project.Store.TeamProjectCollection.AuthorizedIdentity.DisplayName; To get the assigned to user: _workItem.Fields.["System.AssignedTo"].Value.ToString(); Good luck! :)
[ "stackoverflow", "0036710604.txt" ]
Q: Format Numeric Strings I want to format an integer so that it appears with the 1000's separator (,) My attempts so far have been: String.Format("{0:#,###.##}", 1234.0); // 1,234 String.Format("{0:#,###.##}", 1234.05); // 1,234.05 String.Format("{0:#,###.##}", 1234); // 1,234 I am Struggling to display the values as output as 1,234.0.. Could you please suggest me how to output the string as 1,234.0 ?? A: The way I understand your question: You want a thousand separator every 3 digits on the integer side You want 1 digit on the fractional side Additionally, I would guess that You want at least 1 digit on the integer side The problem with the format strings you're using is that you're using # to specify digit positions. According to the documentation, this character means: Replaces the "#" symbol with the corresponding digit if one is present; otherwise, no digit appears in the result string. (my emphasis) on the other hand, the 0 character: Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string. (again, my emphasis) So you should use some 0's instead of #'s. Specifically, here is the format string I would use according to the 3 bulletpoints at the top of this answer: #,##0.0 This means: comma means "add a thousand separator" The #,##0 thus means "set aside place for the integer part here, add the thousand separator if necessary, and only add digits after the first if necessary, but always add at least one digit, so that you don't get just .1 as a result" .0 means "1 fractional digit" Your .# mean "add the decimal point and the fractional digit if the fractional digit is other than 0, if it is 0, don't add either", so that's probably the main problem with your formatting strings Here's a .NET Fiddle to try it with.
[ "scifi.stackexchange", "0000126640.txt" ]
Q: How does Gandalf's description of Smeagol relate to the story? I am curious about the relationship between Smeagol's personality and his role in the story as either Smeagol or Gollum. Here is the description of young Smeagol, as told by Gandalf to Frodo in The Fellowship of the Ring: "The most inquisitive and curious-minded of that family was called Smeagol. He was interested in roots and beginnings; he dived into deep pools; he burrowed under trees and growing plants; he tunneled into green mounds; and he ceased to look up at the hill-tops, or the leaves on the trees, or the flowers opening in the air: his head and his eyes were downward." Of course, some of it is fairly self-explanatory. Smeagol liked tunneling and burrowing, and generally preferred the downward direction to upward - and Gollum hid for centuries in a cave. But Gandalf tells us more than that - namely, that Smeagol was an inquisitive creature who was interested in roots and beginnings. Does this play into the story? Is there evidence of this in anything Gollum - or Smeagol - does? Or does this somewhat cryptic description boil down to him burrowing into a cave? A: All I can think of is that Gollum is an astute student of history; during the trek through the Dead Marshes, he takes the role of loremaster, relating some tales of the Great Siege and the Battle of the Last Alliance: The Dead Marshes. There was a great battle long ago, yes, so they told him when Sméagol was young, when I was young before the Precious came. It was a great battle. Tall Men with long swords, and terrible Elves, and Orcses shrieking. They fought on the plain for days and months at the Black Gates. The Two Towers Book IV Chapter 2: "The Passage of the Marshes" 'The old fortress, very old, very horrible now. We used to hear tales from the South, when Sméagol was young, long ago. O yes. we used to tell lots of tales in the evening, sitting by the banks of the Great River, in the willow-lands, when the River was younger too, gollum, gollum.' He began to weep and mutter. The hobbits waited patiently. 'Tales out of the South,' Gollum went on again, `about the tall Men with the shining eyes, and their houses like hills of stone, and the silver crown of their King and his White Tree: wonderful tales. They built very tall towers, and one they raised was silver-white, and in it there was a stone like the Moon, and round it were great white walls. O yes, there were many tales about the Tower of the Moon.' The Two Towers Book IV Chapter 3: "The Black Gate is Closed" However, I hesitate to say this was a reflection on Gollum himself; by his own admission, these tales were told to him back when he was only Sméagol, merely remembered by him centuries later. As far as I can tell, Sméagol's previous interest in "roots and beginnings" did not at all reflect in the Gollum personality, except that he liked to hang out in caves. However, I can say with confidence that Gollum was still curious, at least about one thing: "What iss he, my preciouss?" whispered Gollum (who always spoke to himself through never having anyone else to speak to). This is what he had come to find out, for he was not really very hungry at the moment, only curious [...] He was anxious to appear friendly, at any rate for the moment, and until he found out more about the sword and the hobbit, whether he was quite alone really, whether he was good to eat, and whether Gollum was really hungry. [...] After a while Gollum began to hiss with pleasure to himself: "Is it nice, my preciousss? Is it juicy? Is it scrumptiously crunchable?" He began to peer at Bilbo out of the darkness. The Hobbit Chapter 5: "Riddles in the Dark"
[ "stackoverflow", "0012322562.txt" ]
Q: Why doesn't setting the value property of this UISlider update its position? ...ViewController.h: @property (nonatomic, strong) IBOutlet UISlider *slider; ...ViewController.m: @synthesize slider; - (void)viewDidLoad { [super viewDidLoad]; ... currentValue = 50; self.slider.value = currentValue; // Do any additional setup after loading the view, typically from a nib. } .xib: The UISlider in my interface is connected to the slider property. Behavior: The slider sits all the way to the right at value 100 when it is supposed to be in the middle. An action I set up confirms the value of currentValue is 50. If currentValue is 50 and slider.value is set to 50, why doesn't the position reflect this? P.S. I tried [slider setNeedsDisplay] and it did not affect this behavior. Update: thanks for the quick answers! What a silly thing to do. I print out currentValue as an int elsewhere so I am now setting slider.value with this code: self.slider.value = (float) currentValue/100; A: currentValue = 50; The slider's range is not 0...100 but 0...1. You have to write either currentValue = 0.5; or change the range of the slider: self.slider.maximumValue = 100;
[ "softwareengineering.stackexchange", "0000185109.txt" ]
Q: Why Java does not allow function definitions to be present outside of the class? Unlike C++, in Java, we cannot have just function declarations in the class and definitions outside of the class. Why is it so? Is it to emphasize that a single file in Java should contain only one class and nothing else? A: The difference between C++ and Java is in what the languages consider their smallest unit of linkage. Because C was designed to coexist with assembly, that unit is the subroutine called by an address. (This is true of other languages that compile to native object files, such as FORTRAN.) In other words, an object file containing a function foo() will have a symbol called _foo that will be resolved to nothing but an address such as 0xdeadbeef during linking. That's all there is. If the function is to take arguments, it's up to the caller to make sure everything the function expects is in order before calling its address. Normally, this is done by piling things onto the stack, and the compiler takes care of the grunt work and making sure the prototypes match up. There is no checking of this between object files; if you goof up the call linkage, the call isn't going to go off as planned and you're not going to get a warning about it. Despite the danger, this makes it possible for object files compiled from multiple languages (including assembly) to be linked together into a functioning program without a lot of fuss. C++, despite all of its additional fanciness, works the same way. The compiler shoehorns namespaces, classs and methods/members/etc. into this convention by flattening the contents of classes into single names that are mangled in a way that makes them unique. For example, a method like Foo::bar(int baz) might get mangled into _ZN4Foo4barEi when put into an object file and an address like 0xBADCAFE at runtime. This is entirely dependent on the compiler, so if you try to link two objects that have different mangling schemes, you're going to be out of luck. Ugly as this is, it means you can use an extern "C" block to disable mangling, making it possible to make C++ code easily accessible to other languages. C++ inherited the notion of free-floating functions from C, largely because the native object format allows it. Java is a different beast that lives in an insulated world with its own object file format, the .class file. Class files contain a wealth of information about their contents that allows the environment to do things with classes at runtime that the native linkage mechanism couldn't even dream about. That information has to start somewhere, and that starting point is the class. The available information allows the compiled code to describe itself without the need for separate files containing a description in source code as you'd have in C, C++ or other languages. That gives you all of the type safety benefits languages using the native linkage lack, even at runtime, and is what enables you to fish an arbitrary class out of a file using reflection and use it with a guaranteed failure if something doesn't match up. If you haven't figured it out already, all of this safety comes with a tradeoff: anything you link to a Java program has to be Java. (By "link," I mean anytime something in one class file refers to something in another.) You can link (in the native sense) to native code using JNI, but there's an implicit contract that says that if you break the native side, you own both pieces. Java was big and not particularly fast on the available hardware when it was first introduced, much like Ada had been in the prior decade. Only Jim Gosling can say for sure what his motivations were in making the class Java's smallest unit of linkage, but I'd have to guess that the extra complexity that adding free floaters would have added to the runtime might have been a deal-killer. A: I believe the answer is, per Wikipedia, that Java was designed to be simple and object oriented. Functions are meant to operate on the classes they are defined in. With that line of thinking, having functions outside of a class doesn't make sense. I am going to leap to the conclusion that Java doesn't allow it because it didn't fit with pure OOP. A quick Google search for me didn't yield much on Java language design motivations. A: The real question is what would be the merit of continuing to do things the C++ way and what was the original purpose of the header file? The short answer is that the header file style allowed for quicker compile times on large projects in which many classes could potentially reference the same type. This is not necessary in JAVA and .NET due to the nature of the compilers. See this answer here: Are header files actually good?
[ "gardening.stackexchange", "0000047871.txt" ]
Q: What is going on with my cactus. Someone said miners but idk my night bLooming cactus has its leaves eaten like this. I don’t see a bug on it. Ive Sprayed it with water etc and researched online but just two people answered and they said miners. I don’t know if it’s actually miners. Any help Appreciated please. A: This damage is what's known as 'skeletonized' - it's usually caused by insect larvae that eat between the veins of a leaf, leaving behind this typical 'lacework' look to the leaves. Later, once it becomes an adult, it usually disappears altogether. This is not the same thing as leaf miners - those leave what looks like a trail inside the leaf tissue, rarely causing this skeletonized effect - the larvae which have done this could just as easily have been under or on top of the leaves. Quite which insect has caused the problem is hard to say - have a good look at the leaves, including the backs, as well as the stems with a magnifying glass to see if you can find any larvae or insects anywhere, but its possible they've all gone already. https://www.gardeningknowhow.com/plant-problems/pests/insects/skeletonized-plant-leaves.htm
[ "stackoverflow", "0009567602.txt" ]
Q: Dynamic and static linking and deployment in Visual Studio 2010 I've an unmanaged C++ project in Visual Studio 2010. It uses boost, glut and another library from a vendor. I've set up the project to create a more "dll-indepenendent" executable possible. All the boost libraries are linked statically and there is no need of dll in the directory where the executable stays. Same thing for the Glut, I've linked the static glut32.lib instead of the glut32.dll and again no problem. I've selected for the Runtime libraries the NON-dll version, i.e. Multithreaded Debug (for Debug configuration) and Multithreaded for Release configuration. Now, the vendor I was speaking before, provides two alternatives a Vendor.lib and a Vendor.dll. The Vendor.lib is added in the Linker->Additional dependencies but at runtime I always have to put the Vendor.dll in the same directory of the executable, otherwise the runtime environment complains because it doesn't find the Vendor.dll library. How should I solve this issue? I would like to avoid to put in every directory the .dll file. I don't want to put the dll in the same directory of the exe and in general what are the guidelines to deploy unmanaged c++ console applications in Visual Studio? I know there are many questions and pages about this argument but none of those clarified me this point. Some idea? A: Microsoft is a bit funny in the way it handles this: when you create a .dll, you also create a .lib, which contains the public symbols in the .dll. You must link against the .lib in order to load the .dll at runtime, but this .lib is still not a static library. If your vendor provides a version for static linking, there will either be no .dll, or two .lib (presumably in different directories or with different names). Just another example of Microsoft making serious development more difficult than necessary. A: The Vendor.lib needs to be a statically-compiled library. If when you link this you still need Vendor.dll, it sounds like Vendor.lib is actually an import library rather than a static library. Check to see if the vendor provides another Vendor.lib (which should be a good bit larger than your current .lib) which is a static library and try linking to that. If so, you won't need the dll.
[ "stackoverflow", "0039383294.txt" ]
Q: How session '$config['sess_expiration']' expires in codeigniter I want to know how session expires in CodeIgniter, because before $config['sess_expiration'] expires ie destroys, I want to insert the logout time of the particular user.I want to know where the flow goes so that I can write a query to insert user logout data.In which file session destroy code is. A: Here you go: if($login_var) { $this->session->sess_expire_on_close = TRUE; } else { $this->session->sess_expire_on_close = FALSE; }
[ "stackoverflow", "0050369823.txt" ]
Q: Fingerprint at pipeline Jenkins job How can I add fingerprint to artefact at pipeline Jenkins job? I added the needed plugins and used the parameters as described at the documentation. withMaven(options: [artifactsPublisher(disabled: false), dependenciesFingerprintPublisher(disabled: false)]) A: I found the answer. The fingerprint is done by a special command step([$class: 'ArtifactArchiver', artifacts: '**/*.jar', fingerprint: true]) It is recommended to do it in a dedicated step, this is what I did: stage('arch') { step([$class: 'ArtifactArchiver', artifacts: '**/*.jar', fingerprint: true]) } More details can be found here
[ "stackoverflow", "0056228480.txt" ]
Q: compare two dataframes and get maximum values I am trying to compare two data frames (df1, df2) of same structure (same dimensions, column names, row names, etc) and keep the maximum values between the two data frames. I actually have hundreds of columns and rows, but here is some pretend data: df1: Date Fruit Num Color 2013-11-24 Banana 2 Yellow 2013-11-24 Orange 8 Orange 2013-11-24 Apple 7 Green 2013-11-24 Celery 10 Green df2: Date Fruit Num Color 2013-11-24 Banana 22 Yellow 2013-11-24 Orange 8 Orange 2013-11-24 Apple 7 Green 2013-11-24 Celery 1 Green There are many examples on SO doing similar things but in python not R: Comparing two dataframes and getting the differences, Compare two dataframes to get comparison value in in another dataframe etc. I tried a dplyr approach but I don't know how to do this correctly for all the columns (hundreds). library(dplyr) test <- rbind(df1, df2) test2 <- test %>% group_by(Date) %>% summarise(max = max(.)) Given my pretend data above, the desired output should be: new.df: Date Fruit Num Color 2013-11-24 Banana 22 Yellow 2013-11-24 Orange 8 Orange 2013-11-24 Apple 7 Green 2013-11-24 Celery 10 Green Thanks for the help. A: One possibility is grouping by all the non-numeric columns and then getting the max for numeric ones: library(tidyverse) rbind(df1, df2) %>% group_by_at(vars(one_of(names(select_if(df2,negate(is.numeric)))))) %>% summarise_if(is.numeric, max) #> # A tibble: 4 x 4 #> # Groups: Date, Fruit [4] #> Date Fruit Color Num #> <fct> <fct> <fct> <dbl> #> 1 2013-11-24 Apple Green 7 #> 2 2013-11-24 Banana Yellow 22 #> 3 2013-11-24 Celery Green 10 #> 4 2013-11-24 Orange Orange 8 Created on 2019-05-20 by the reprex package (v0.2.1) You can also try joining two dataframes and then keeping the maximum values: df1 %>% right_join(df2, by=c("Date","Fruit","Color")) %>% mutate(Num = pmax(Num.x, Num.y)) %>% select(-Num.x, -Num.y)
[ "stackoverflow", "0054099757.txt" ]
Q: What to do when library function parameters aren't const Most of my code-base is immutable; however, due to quirks of the language design, I'm unable to mark my variables const. In a vast majority of cases, especially when inter-operating with C code, I find function parameters not marked const, even though they provably do not modify them. One such example is fts_open(...). At this point the compiler forces me to tediously remove const qualifiers from large parts of my code, and thereby removing the safety it offered. One trivial solution is to compile with -fpermissive, but this is completely contrary to my intent. Apart from rewriting every single C library ever written, what can I do to still get the benefits from leaning on the compiler? i.e. this type of code does not work: void function(immutable_type const &param) { char const * const fts_arg[2]{std::data(param.path), nullptr}; FTS *tree = fts_open(fts_arg, FTS_OPTIONS, nullptr); ... } At this point I have to: Remove const from the fts_args variable. Remove const from the function parameter. Remove const from path inside the datatype definition. Remove const from the variable being passed to function. Recursively remove consts from the entire call chain. Thank you. :) A: This is exactly what const_cast is for. If you absolutely know that a function won't change the pointed/referenced object, then it is OK to const_cast the constness of your pointer/reference away in order to pass it into that function, despite referring to a const object. isn't const_casting from const undefined behavior? No. const_cast itself is never UB. But modifying a const object is. So if you cannot prove that a function taking a non-const pointer/reference doesn't modify the object, then it is not safe to pass the const_casted reference into that function. Also consider whether the implementation might be changed in future to use non-constness. In case where you cannot prove that the non-constly referred/pointed object won't be modified, you can make a local copy of the constly referred argument of your wrapper function. The overhead of this copy may be trivial (int) or non-trivial (long std::vector). If you cannot prove that the object won't be modified, and copying is expensive (or not possible), then as last resort, you have to get rid of constness of your own argument (and propagate the change up the call chain). Or use another API in the implementation.
[ "stackoverflow", "0002869829.txt" ]
Q: _REQUIREDNAME always nil I'm trying to use the method for naming a lua package after the filename mentioned here, however _REQUIREDNAME is never defined. For example I have these two files samplePackage.lua: print("_REQUIREDNAME: ", _REQUIREDNAME) return nil; packageTest.lua: require "samplePackage" And when I run packageTest.lua it outputs > _REQUIREDNAME: nil I also couldn't find any mention of _REQUIREDNAME in the Lua 5.1 Refrence manual, so was this removed from the language, or am I missing something? A: The way that packages and modules work underwent some major changes in Lua 5.1, making the first edition of Programming in Lua mostly obsolete regarding that subject. In 5.1, the module name is passed as an argument to the module by require. You can access it with ...: print("Module name: ", ...) The second edition of Programming in Lua covers Lua 5.1. It isn't free, but the chapter about packages and modules is available as a sample (PDF).
[ "stackoverflow", "0053122191.txt" ]
Q: object changed after being passed to another function How an object can be changed after being passed to another function ? For example : var app = require('express')(); var http = require('http').Server(app); app.get('/', function (request, response) { response.sendFile(__dirname + '/index.html'); }); 'http' is already created, using the previously defined 'app'. Then, a route is set using app.get. But how is that possible ? How the http server will have access to this route defined after assignment ? A: When you pass an object variable as an argument to a function in Javascript , it is passed by reference. So when you make changes to app outside of http the changes are visible in http because you made changes to the same old object reference of which was passed to http. Consider this example: function print(obj) { // -- this is Http in your case setTimeout (()=> { console.log(obj.a); } , 1000); } var my_obj = { a: 100 }; // -- this is app in your case print(my_obj); // -- this is passing app to http in your case my_obj.a = 101; // -- this is adding a route to app in your case There will be 101 logged into console. Because actual object changes before 1000 milliseconds pass. Global context and a function both still reference to the same object. This proves that objects are passed by reference in Javascript. If you remove the setTimeout, then there will be 100 logged in to console, here is the snippet: function print(obj) { console.log(obj.a); } var my_obj = { a: 100 }; print(my_obj); my_obj.a = 101;
[ "reverseengineering.stackexchange", "0000013477.txt" ]
Q: How to multiply an SSE float with a hardcoded value using MULSS? I have the following line of code in a game: movss xmm0,[eax+000000F0] It basically loads the float speed of the current speed category into the XMM0 register. I already made a jump to an empty code section to get some more space, because I now want to multiply this speed by a hardcoded value of 2 after it was loaded. Sadly, easy-thinking like this doesn't work: movss xmm0,[eax+000000F0] mulss xmm0,2 I can't simply multiply an XMM register with an integer or float immediate. I read that I can only multiply with another XMM register. But then again I can't push and pop an existing XMM register to the stack to abuse it for that operation temporarily. How would I create such a simple multiplication operation? A: Although you indeed cannot use mulss with an immediate value like you've pointed out, you are allowed to pass an 32bit offset as mulss's second operand: Multiplies the low single-precision floating-point value from the source operand (second operand) by the low single-precision floating-point value in the destination operand (first operand), and stores the single-precision floating-point result in the destination operand. The source operand can be an XMM register or a 32-bit memory location. The destination operand is an XMM register. The three high-order double-words of the destination operand remain unchanged. You could then just point to any offset you control, if code is not relocated. If it is, you could simply use 'lea' if in 64bit mode or do the call $+5 / pop trick in x86. I'll assume x86 because it makes it a bit more complicated. The patch should look something like the following (this wasn't tested): push edx call next next: pop edx movss xmm0,[eax+000000F0] mulss xmm0,[edx+float-next] pop edx <return to previous location> float: <float as 32bit data> There might be better solutions, but nothing pops at me.
[ "ell.stackexchange", "0000187121.txt" ]
Q: Should I use "in" or "of"? Which one is correct This is the last November of our college life. This is the last November in our college life. A: The second one is incorrect as you can’t be in your college life as college life is not an object. In the first one you are not referring to it as an object so it is correct
[ "stackoverflow", "0036566456.txt" ]
Q: JavaScript does not sleep at the right position I have a little problem. In my homepage i have a button. This Button calls a function up by onclick (onclick="showhidelogin()"). the function looks like this: function showhidelogin() { document.getElementById("null").id = "menu-sticky"; sleep(1000); document.getElementById("loginform").id = "loginformview"; } Why did the page wait as first, and then execute the two "getElementById"-Statements? (setTimeout does not work too) A: There is no sleep function in Javascript. You must do this using setTimeout. function showhidelogin() { document.getElementById("null").id = "menu-sticky"; setTimeout(function () { document.getElementById("loginform").id = "loginformview"; }, 1000); }
[ "stackoverflow", "0050338249.txt" ]
Q: Printing first N natural numbers function not working Why is this python code returning 1 for any input? #code for a function which prints the first n natural numbers n = raw_input("Enter n") n = int(n) def printint(p): for i in range(1 , n+1): return i print printint(n) A: What you want is to print the numbers, not to return them: def printint(p): for i in range(1 , p+1): print i Then just call the function alone, since it is printing inside: printint(n) Here you have a live example EDIT: Your final code should look like this: def printint(p): for i in range(1 , p+1): print i n = int(raw_input("Enter n")) printint(n)
[ "stackoverflow", "0007633739.txt" ]
Q: Hibernate custom HQL for this mapping I have following tables ------------ BAR ------------ ID number ------------ ZOO ------------ ID ------------ FOO ------------ ID ------------ MAPPER ------------ ID FOO BAR ZOO Now I want to fetch all ZOO for particular FOO So I will do select ZOO from MAPPER where zoo = someZoo but now I want these ZOO sorted based on vote number so SQL would be SELECT FOOBAR.ZOO FROM mapper AS mapper, BAR AS bar WHERE mapper.FOO=SOME_VALUE AND mapper.BAR=bar.id order by bar.number desc But now I want to do it in DB independent way in Hibernate How would I go ? I have entities mapped setup I am using Spring Hibernate Template Support public class Foo{ Long id; } public class Zoo{ Long id; } public class Bar{ Long id; Long num; } public class Mapper{ Long id; Long foo; Long bar; Long zoo; } A: Class Mapper should be: public class Mapper { Long id; Foo foo; Bar bar; Zoo zoo; } Now, you can write the following HSQL query: select mapper.zoo from Mapper mapper where mapper.foo=:foo order by mapper.bar.num desc
[ "math.stackexchange", "0003021145.txt" ]
Q: The lift and the right hand sides for Piecewise limit Considering this limit : $\lim\limits_{x \to 1} = \begin{cases} x+1, & \text{x≠1} \\[2ex] \pi , & \text{x=1} \end{cases}$. from the lift : $\lim\limits_{x \to 1-} (x+1) = 2 $ from the right: $\lim\limits_{x \to 1+} (\pi) = \pi $ I'm assuming that this limit is not exist since the left hand side limit does not equal the right hand side limit (From my current knowledge). The Book that i use telling me not what i expected !: $\lim\limits_{x \to 1} = \begin{cases} x+1, & \text{x≠1} \\[2ex] \pi , & \text{x=1} \end{cases}$ = $\lim\limits_{x \to 1} (x+1) = 2 $ I think i miss some things about Piecewise limits. anyone explain to me why this limit end up with 2 ? A: Recall that, according to the definition, when we take the limit $x\to 1$ we are assuming $x\neq 1$, that is $$\forall \varepsilon>0 \quad \exists \delta>0 \quad \text{such that}\quad \color{green}{\forall x\neq1}\quad|x-1|<\delta \implies|f(x)-2|<\varepsilon$$ therefore since $x\neq 1$ $$\lim\limits_{x \to 1} f(x)=\lim\limits_{x \to 1} (x+1) = 2$$ In other words, the value for the limit at a point is not affected by the value of the function at that point. The function could be also not defined at that point (e.g. $\sin x/x$ as $x \to 0$). Your evaluation would be correct for the following function $$g(x)= \begin{cases} x+1, & \text{$x<1$} \\[2ex] \pi & \text{$x\ge1$} \end{cases}$$
[ "stackoverflow", "0012717522.txt" ]
Q: Non-browser sent HTTP request and PHP sessions Is PHP able to maintain a session with devices that aren't using a browser to communicate with the server? I know that any application is capable of adhering to the HTTP protocol, but for languages like Actionscript3 and Java that consist of HTTP request classes in their frameworks, do they send the necessary parameters for PHP to hold a session like it does with a browser? A: Any HTTP client library can support cookies (which is how PHP maintains session token state across requests by default). Some will handle cookies automatically, some will require it to be turned on in a preference, some will just provide an API to access the headers (which include the cookies).
[ "stackoverflow", "0016936498.txt" ]
Q: Query to find the average of the rows excluding the top 5% in hiveQL select perecentile(time,0.95) from sometable; gives the 95th percentile. I want average of all the rows whose time values are below this value. In oracle it would be something like this:- select avg(time) from sometable where time<(select percentile(time,0.95) from sometable); But in hive it is not possible to use subqueries in the where clause.When i am using union all I am not able to isolate the tuple that i need to compare the other tuples with. A: you can do a Cartesian join with the result of the percentile and then filter all the smaller values. Something like this : select avg(time) from sometable a join (select percentile(time,0.95) perc from sometable) b on (1=1) where a.time < b.perc; Its not the most efficient way but that's the first that comes in mind..
[ "stackoverflow", "0026830117.txt" ]
Q: Gradle compatible Maven repository or alternative for local usage The situation: We have several apps, which use a library developed by ourselves. All app projects as well as the library are under constant development. Our goal is to have a local maven repository, which allows us to always build the apps with the latest library version, like all those dependencies listet in the Android-Studio dependency chooser here We don´t want to use the central maven repository, as it makes our code public. Is there any chance to have a lokal maven repository which is going to be fully compatible with Android Studio and Gradle or is there any other (easy) alternative? A: Yes, you can use a local Maven repository manager, which will let you maintain a set of private artifacts for your organization. There's some documentation here: http://maven.apache.org/repository-management.html but the brief explanation is that you can set up a repository that's similar to Maven Central except it's private. There are various repository manager software packages, including Apache Archiva, Artifactory, and Sonatype Nexus.
[ "stackoverflow", "0004757890.txt" ]
Q: When the use of a AntiForgeryToken is not required /needed? UPD: Same question asked on security.stackexchange.com and the answer I got is different. Please follow there, to get the correct answer! I'm running a rather large site with thousands of visits every day, and a rather large userbase. Since I started migrating to MVC 3, I've been putting the AntiForgeryToken in a number of forms, that modify protected data etc. Some other forms, like the login / registration also use the AntiForgeryToken now, but I'm becoming dubious about their need there in the first place, for a couple reasons... The login form requires the poster to know the correct credentials. I can't really think of any way an csrf attack would benefit here. Especially if I check that the request came from the same host (checking the Referrer header) The AntiForgeryToken token generates different values every time the page is loaded.. If I have two tabs open with the login page, and then try to post them, the first one will successfully load. The second will fail with a AntiForgeryTokenException (first load both pages, then try to post them). With more secure pages - this is obviously a necessary evil, with the login pages - seems like overkill, and just asking for trouble :S There are possibly other reasons why would one use/not use the token in their forms.. Am I correct in assuming that using the token in every post form is bad / overkill, and if so - what kind of forms would benefit from it, and which ones would definitely NOT benefit? A: Anti forgery tokens are useless in public parts of the site where users are not yet authenticated such as login and register forms. The way CSRF attack works is the following: A malicious user sets a HTML form on his site which resembles your site. This form could contain hidden fields as well. He tricks one of your site users to visit his malicious url. The user thinks that he is on your site, fills the form and submits it to your site. If the user was already authenticated on your site the form submission succeeds and the unsuspecting user have deleted his account (or whatever you can imagine). So you could use anti forgery tokens on authenticated parts of your site containing actions that could modify somehow the user state. Remark: checking the Referer header for identifying that a request came from your site is not secure. Anyone can forge a request and spoof this header.
[ "stackoverflow", "0058891594.txt" ]
Q: applying current code to another data frame below is my current code, how do i apply the same code to another Data Frame (importing another excel sheet and apply the same below code to it) import pandas as pd import numpy as np book= pd.read_csv("book.csv") book=book.dropna() book.sort_values("Market Cap", ascending=False, inplace=True) book = book.head(500) book["EY"] = (book["Earnings Per Share LTM"] / book["Start Price"]) book["ROIC"] = (book["EBIT"]/ book["Invested Capital"]) book["Price Change"] =((book["Close Price"] - book["Start Price"]) / book["Start Price"]) book['EY Rank'] = book['EY'].rank(ascending=False) book['ROIC rank'] = book['ROIC'].rank(ascending=False) A: You can define a function and call it as many time as you like: import pandas as pd import numpy as np def some_func(file_name): book= pd.read_csv(file_name) book=book.dropna() book.sort_values("Market Cap", ascending=False, inplace=True) book = book.head(500) book["EY"] = (book["Earnings Per Share LTM"] / book["Start Price"]) book["ROIC"] = (book["EBIT"]/ book["Invested Capital"]) book["Price Change"] =((book["Close Price"] - book["Start Price"]) / book["Start Price"]) book['EY Rank'] = book['EY'].rank(ascending=False) book['ROIC rank'] = book['ROIC'].rank(ascending=False) return book file_name = "book.csv" some_func(file_name) file_name = "next_book.csv" some_func(file_name) Is this what you look for?
[ "stackoverflow", "0059365679.txt" ]
Q: Swift - Pass multiple arguments in whereField clause to retrieve from firebase I am new to swift and trying to do some basic operations. My scenarios here is, i am trying to fetch data from firebase by passing arguments as a search criteria. For example i am looking for a blood donors in my database filtered out by blood group and city, i need to pass two arguments as my search criteria. But in a whereField method i can only pass one argument. Is there a way or another method that i can use to pass multiple arguments? below is the code that i have till now @IBAction func fetchDataButtonTapped(_ sender: Any) { let db = Firestore.firestore() db.collection("users").whereField("bloodgroup", isEqualTo: "A-").getDocuments { (snapshot, error) in if error == nil && snapshot != nil { self.resultArray.removeAll() for document in snapshot!.documents { let dict = document.data() let x = dict["firstname"] as? String self.resultArray.append(x!) self.myTableView.dataSource = self self.myTableView.reloadData() } } } } A: To filter on both blood type and city, you can just add multiple calls to whereField( to the question. So for example: db.collection("users") .whereField("bloodgroup", isEqualTo: "A-") .whereField("city", isEqualTo: "Chicago") .getDocuments { (snapshot, error) in If you want to filter for multiple blood types, you can use the (quite new) in queries: db.collection("users") .whereField("bloodgroup", in: ["A-", "A+"]) .whereField("city", isEqualTo: "Chicago") .getDocuments { (snapshot, error) in
[ "stackoverflow", "0009184284.txt" ]
Q: Where can I find a very simple jQuery/AJAX Coldfusion tutorial? Edit: After following a few tutorials I am stuck here I am new to jquery but have some experience with Coldfusion. I have been desperate for an easy tutorial that shows how jQuery/AJAX pulls a query from a ColdFusion9 CFC and displays it on the HTML calling page. I tried following this ben_tutorial but it is too complex for me. There is also a another tutorial, but I do not want to install a plugin. Where should I be looking? I am googling "jquery ajax coldfusion" A: You didn't elaborate on what you want to update on the client side. Forms are common, so if you have client side html form like: <input type="text" name="title"> <input type="text" name="date"> <input type="text" name="author"> You would generate and send a JSON string with coldfusion. The JSON string could look something like: {"title" : "mytitle", "date" : "mydate", "author" : "myauthor"} To update the data on the client side you would execute (coldfusion-page.cfm is the name of your server side ajax responder): jsonOBJ = {}; $.ajax({ type: "GET", url: "coldfusion-page.cfm", cache: false, success: function(data){ jsonOBJ = jQuery.parseJSON(data); for (var key in jsonOBJ) { $("input[name=" + key + "]").val(jsonOBJ[key]); } }, }); OR, If you just want to update a div or textarea like: <div id="uniquedivname"></div> you just send the html/text and replace the success function in the ajax call with: success: function(data){ $("#uniquedivname").html(data); },
[ "stackoverflow", "0034769267.txt" ]
Q: NoClassDefFoundError: roboguice.inject.ContextScopedRoboInjector on android 4.3 (Jelly Bean API 18) I have an app which is using roboguice 3 and it crashes on start on devices with API 18. Same app works perfect on android 23. Stack trace: java.lang.NoClassDefFoundError: roboguice.inject.ContextScopedRoboInjector 01-12 16:53:31.285 12710-12710/com.package.app E/AndroidRuntime: at roboguice.RoboGuice.getInjector(RoboGuice.java:197) 01-12 16:53:31.285 12710-12710/com.package.app E/AndroidRuntime: at roboguice.activity.RoboActionBarActivity.onCreate(RoboActionBarActivity.java:85) any ideas? A: As stated in their GitHub page RoboGuice is no longer supported. [..] There are now many other excellent DI frameworks for Android, please consider migrating to one of them.
[ "rpg.stackexchange", "0000144610.txt" ]
Q: Does making a Feral Tiefling in AL require SCAG to be your "+1" book? Does making a Feral Tiefling in AL require SCAG to be your "+1" book? My gut is leaning towards yes since those are variants on a PHB race, yes, but the variants themselves are only in that one book. A: Yes, sadly it does count for the +1 rule. You can't use Xanathar's subclasses without choosing Xanathar's Guide as your "+1" book, even though the base class is in the PHB. It should be the same with races, too. And, according to the quote from NautArch's answer to the linked question: The variant or optional rules are available when creating your character: [...] Half-Elf and Tiefling Variants (SCAG/ToF) Option: Human Languages (SCAG) [This option isn't subject to PHB+1] Seeing as it was not specified to deny the rule, it stands to reason the rule still applies.
[ "stackoverflow", "0033347484.txt" ]
Q: Skipping to a specific page in a ViewPager from a Navigation Drawer I'm a little confused with what I should be doing here so was hoping someone could point me in the right direction. I have a Viewpager that has around 25 pages to it, I can swipe left and right through it fine. I also have a navigation drawer that I want to use to jump to a specific page within the 25 pages. I.e. say Page 1, 5 ,15 and 25. I've been having a look at the setCurrentItem() and getCurrentItem() methods but not really sure how to implement them or if that's what I should be using. My idea was to use the setCurrenItem() within the onNavigationDrawerItemSelected() method via a switch statement. Would that work? If so, I presume I'd need to give each of my fragments an int argument to specify each page and then use that from setCurrentItem()? Any advice would be appreciated! A: ViewPager setCurrentItem method is not abstract, you don't have to implement it. Just call it from your activity/fragment/etc whenever you detect click on NavigationDrawer menu item. However you may want to have scrolling animation. In this case you need to provide your custom scroller to achieve smooth scroll effect: ViewPager setCurrentItem(pageId, true) does NOT smoothscroll Speaking of page selection you should know which fragment fragment is on which pager page, so that shouldn't be a problem as well.
[ "ru.stackoverflow", "0000814836.txt" ]
Q: Объясните логику работы выражения Объясните пожалуйста, как работает это выражение !(a & (a - 1)) В плюсах совершенно не понимаю, в Java ! нельзя применять к int. private int isPow2(int a) { return !(a & (a - 1)); } A: Возьмем два числа A и B. Выражение A & B будет равно 0 только тогда, когда числа А и B не содержать единичных бит на одних и тех же позициях. Если (a & (a - 1) = 0, то a и a-1 не содержат общих единичных бит. Давайте возьмем число а и попробуем вычесть одну единицу. Когда мы отнимаем единицу, смотрим на младший бит. если он равен 1 то мы просто заменяем его на 0. Но если там стоит 0, то мы должны заимствовать из старшего бита. Мы заменяем каждый бит с 0 на 1 до тех пор, пока не найдем бит, равный 1. Затем вы инвертируем найденную единицу в ноль. То есть чтобы получить ноль при выполнении операции &, нам нужно, чтобы младшие нули в a соответствовали единицам в a - 1, а последний(и единственный) единичный бит в a(если существует) стал бы нулем в a - 1 - только таким образом во всех позициях будут отсутствовать единичные биты. Это условие выполняется только, если число является степенью двойки, например 1000 & 0111 = 0 10000 & 01111 = 0 число равно 0 0000 & 1111 = 0 Поэтому (a & (a - 1)) = 0, если а - степень двойки или ноль A: Операция a&(a-1) обнуляет крайний справа единичный бит или дает 0, если такового нет: a = 01011000 a-1 = 01010111 a&(a-1) = 01010000 Таким образом, для всех a, являющихся степенями двойки (у которых только один бит - единичный, остальные - нулевые) и 0, выражение дает 0, для чисел, таковыми не являющимися - ненулевое значение. ! инвертирует полученное логическое значение (0 - false, не нуль - true), так что ваша функция дает 1, если a - степень двойки или нуль, и нуль в противном случае.
[ "stackoverflow", "0039854014.txt" ]
Q: Issues of executing remote powershell script using cake-build I am trying to execute following test.ps1 script param([string]$name,[string]$password); write-Output "Hello $($name) my password is $($password)"; dir c:\ New-Item c:\HRTemp\test.txt -ItemType file on remote server using following command StartPowershellScript("Invoke-Command", args => { args.Append("ScriptBlock", "{{c:\\test.ps1 -name dato -password test}}" ); }); I was able to successfully invoke this command from command line and now I want the same using cake script. I am using Cake.Powershell addin. When I try to execute it with one curly brace {c:\\test.ps1 -name dato -password test} , I am getting error: Error: Input string was not in a correct format. When I try it with two curly brace {{c:\\test.ps1 -name dato -password test}} output is the following Executing: Invoke-Command -ScriptBlock {{c:\test.ps1 -name dato -password test}} but, when I check on remote server test.txt file is not created. Do you have any ideas why this is happening? A: This is caused by the different handling of curly braces by the ProcessArgumentBuilder used internally by the Cake.Powershell addin, and the format parser used internally in Cake's internal logger. I submitted a PR to Cake.Powershell which has now been merged and a new release published, so upgrading to version 0.2.7 will resolve this issue for you. You should then be able to use something like the following: StartPowershellScript("Invoke-Command", args => { args.Append("hostname").Append("-ScriptBlock {c:\\test.ps1 -name dato - password test}"); }); And while the log will include double braces, the actual command will only use single braces and should run correctly.
[ "stackoverflow", "0054857366.txt" ]
Q: Write an ini key with name of variable value I am trying to create an ini-database for every user that typed /boot (something). But the problem is that I cannot write to ini. I need to do that: Write into an ini section "boots" a key with a name of value of variable bootuserid. This is what I tried: boots.'${bootuserid}' boots.$bootuserid boots.${bootuserid} boots.(bootuserid) All the scripts failed. So how do I make an ini key name of a value of variable? A: You can use bracket notation to access a variable name with another variable: boots[bootuserid] I.e. a={b:1} myvar="b" a[myvar] //returns 1
[ "stackoverflow", "0029687253.txt" ]
Q: Bootstrap list-group-items flush with list-group container This is nitpicky; I'm working in Bootstrap with a fixed-sized list-group. When it starts, it has a nice outline/bottom border, but when I scroll the list, I lose it. I've tried breaking the top list-group-item from the rest of the group using a <p>, but I'm not satisfied with how that looks either. Above: The nice-looking space between list-group and list-group-item When the two elements are flush, the bottom outline of the list-group-item above goes away A: From what I can see the top element has position set to fixed. It looks like you need to apply margin (or margin-bottom) to the top element as it looks like it has a negative margin of -1px which would could be a reason as to why that border disappears.
[ "stackoverflow", "0004758020.txt" ]
Q: jqGrid: Problem with select-element If the select element doesn't have any options the name of the select-list won't be rendered. As I fill the select automatically on one paritcular event I can not save the selected value because the select has no name. Is there a jqGrid-property to manage this? A: I assume that you have problem with cell editing and you created column in colModel something similar: {name:'strType', index:'strType', width:70, sortable:false, editable:true, edittype:'select', editoptions: { value: "" }} Everything you would like to know about this feature is written in docs and there is: The editoptions value must contain a set of value So I would set name attribute by myself. If you do something in javascript that add option to select box, setting name attribute is simple. $('#1_strType').attr('name', 'strType') I haven't tested yet this solution, but I assume that this could work :)
[ "stackoverflow", "0059153898.txt" ]
Q: TypeError: Cannot read property 'match' of undefined when using useParams from react-router I can't understand why it gives me the above error. I used the props way with props.match.params.languagename and it works just fine. I did not include all imports in the code below. import { useParams } from 'react-router'; const App = () => { const topicsState = useSelector(state => state.topics); const dispatch = useDispatch(); const { languagename } = useParams(); useEffect(() => { dispatch(fetchGitHubTrendingTopics()); }, [dispatch]); const handleRepositoryPages = () => { const repositoryPages = topicsState.find( topicState => topicState.name === languagename ); if (repositoryPages) return <RepositoryPage repositoryPages={repositoryPages} />; }; return ( <> <Router> <Header topics={topicsState} /> <Switch> <Route path="/" exact> <Dashboard topics={topicsState} /> </Route> <Route path="/language/:languagename" exact render={handleRepositoryPages()} /> <Redirect to="/" /> </Switch> </Router> </> ); }; A: You can only use useParams in a component that is a child of your Router component, but App is the parent in your case. The Router component injects the context containing the match into the tree below it which will be read by the useParams hook by internally using the useContext hook.
[ "stackoverflow", "0057250798.txt" ]
Q: Use Cell Value as Address in Formula I have a cell that contains a number - C2 I need to use that number as part of an address in a formula. Here's the formula it needs to go in: =COUNT(SEARCH(B$1:B$ 'NUMBER HERE',A1)) UPDATE: I needed it for conditional formatting - to highlight cells that contain specific keywords. The keywords are manually set in column B. The number in C2 determines how many of the keywords will be used. (I found the formula online and seems to work pretty well when the address is manually set) UPDATE: I was able to get it working using the Indirect function as Mikku suggested. A: Try : =COUNT(SEARCH(Indirect("B$1:B$" & INDIRECT("C2",TRUE)),A1)) Indirect gives you the value of a Cell in reference, like in the above formula it will put the value of C2 in this formula Sample Use:
[ "stackoverflow", "0052546268.txt" ]
Q: What is the @ symbol used for in Octave? What is the @ symbol used for in Octave? For example, in the code: [theta, cost] = fminunc(@(t)(costFunction(t, X, y)), initial_theta, options); I have a general understanding of what the code is doing but I don't get what the @(t) is there for. I've looked around the octave documentation but the @ symbol seems to be a hard term to search for. A: @ precedes the dummy variable in the definition of anonymous functions, for instance: f = @(x) x.^2; y=[1:3]; f(y) returns 1 4 9 a quick look at help fminunc shows that FCN in your example is @(t)(costFunction(t, X, y)) A: From the console: octave:1> help @ -- @ Return handle to a function. Example: f = @plus; f (2, 2) => 4 (Note: @ also finds use in creating classes. See manual chapter titled Object Oriented Programming for detailed description.) See also: function, functions, func2str, str2func. More info in the manual: https://octave.org/doc/interpreter/Function-Handles.html In your specific code, the '@' syntax is used to create an "on-the-spot" implementation of a function (in the form of an anonymous function), that takes a single argument, as opposed to the three required by your costFunction one. This is because fminunc expects a function that takes a single argument to work, and therefore one effectively 'wraps' the more complex function into a simpler one compatible with fminunc.
[ "stackoverflow", "0038678695.txt" ]
Q: Advice for best path to working with Amazon Web Services For the last 10+ years I have been developing desktop software. I have successfully avoided learning most Web technologies. Specifically: ASP (any version) HTML5 MVC MVVM I do know a modicum of other Web technologies, like REST and SOAP services, Javascript, and altering a Web Config file. I'd like to be able to move my career towards Web, especially these Amazon Web Services (AWS). Having looked around, it seems that they are being developed by hardcore Web developers. To be able to develop AWS, what is my shortest (or best) path through learning some of these other Web technologies? A: Developing software on Amazon Web Services is, in general, no different to developing software on other computers. You use the same operating systems, programming frameworks and networking standards. The benefits of choosing to use a cloud vendor like AWS are: Easy access to resources on a pay-as-you-go model (eg use a virtual machine for a few hours, then turn it off and stop paying) The ability to scale-out to add extra capacity when needed, then scale-in to remove excess resources when they are not needed (thereby saving money) Taking advantage of application services such as a queueing service, notification service and database service rather than having to deploy and manage the yourself The ability to script the deployment of resources so they can be automated in an easily repeatable manner Cloud vendors take care of the boring activities of deploying and managing systems so that you can concentrate on the more-interesting, value-added activities such as writing code and delivering business value. Bottom line: It doesn't matter whether you use a cloud service like AWS. You'll be using the same technologies, but you'll be able to avoid the boring bits. As to which technologies you should learn, that question is too open-ended for a forum like StackOverflow, which is setup to answer specific questions around software development.