text
stringlengths
70
452k
dataset
stringclasses
2 values
How Does The Debugging Option -g Change the Binary Executable? When writing C/C++ code, in order to debug the binary executable the debug option must be enabled on the compiler/linker. In the case of GCC, the option is -g. When the debug option is enabled, how does the affect the binary executable? What additional data is stored in the file that allows the debugger to function as it does? -g tells the compiler to store symbol table information in the executable. Among other things, this includes: symbol names type info for symbols files and line numbers where the symbols came from Debuggers use this information to output meaningful names for symbols and to associate instructions with particular lines in the source. For some compilers, supplying -g will disable certain optimizations. For example, icc sets the default optimization level to -O0 with -g unless you explicitly indicate -O[123]. Also, even if you do supply -O[123], optimizations that prevent stack tracing will still be disabled (e.g. stripping frame pointers from stack frames. This has only a minor effect on performance). With some compilers, -g will disable optimizations that can confuse where symbols came from (instruction reordering, loop unrolling, inlining etc). If you want to debug with optimization, you can use -g3 with gcc to get around some of this. Extra debug info will be included about macros, expansions, and functions that may have been inlined. This can allow debuggers and performance tools to map optimized code to the original source, but it's best effort. Some optimizations really mangle the code. For more info, take a look at DWARF, the debugging format originally designed to go along with ELF (the binary format for Linux and other OS's). Just to add to this, it can also slow down the executable. I was testing some OpenMP code with the Sun Studio compiler, and with debugging information the code ran much slower. Just something to keep in mind. Unless the -g flag in the Sun compiler disables some optimizations, debug info should NOT slow down your code. This is OpenMP code, and it did slow it down. I was playing with fractals, and working on using the OpenMP compiler extensions. The code on a single thread, ran slower than the non OpenMP code on a single thread. I disabled debugging and the speed equalised. Noted. That's actually kind of interesting. Maybe it's putting extra stuff in there to tell the debugger about parallel regions... They say here (http://docs.sun.com/source/819-3683/OpenMP.html) that you can get map the master thread back to source but not slaves, which seems odd, too. I think that's the case, doesn't affect GCC of course, certainly gave me a surprise when the single thread code went from 11secs to 22. :/ With debugging disabled and 4 threads (I have a Q6600) it dropped to about 3 secs. gcc4 actually supports OpenMP, so it's possible you'd see similar issues there. I hear the performance isn't that good to begin with, though. Just out of curiosity, did you supply additional optimization options when you compiled with -g (e.g. -g -O3) or did you just add -g without explicitly specifying -O[123]? The former could drop you to -O0, at least on icc. I did have the project setup for maximum optimisation (with debugging), SSE, MMX, etc, when I get home I'll post the exact options, maybe there's something I missed. Ok, using -# to list what -fast expands to: cc -xopenmp -fast -# Expands to: -D__MATHERR_ERRNO_DONTCARE -fns -nofstore -fsimple=2 -fsingle -xalias_level=basic -xarch=ssse3 -xbuiltin=%all -xcache=32/64/8:4096/64/16 -xchip=core2 -xdepend -xlibmil -xlibmopt -xO5 -xopenmp -xregs=frameptr The -g flag is included as well, comments just don't give me the space to post the full line. :) Debug version: real time: 6.060s user time: 22.815s Release version: 3.774s user time: 13.902s (Both using 4 threads) A symbol table is added to the executable which maps function/variable names to data locations, so that debuggers can report back meaningful information, rather than just pointers. This doesn't effect the speed of your program, and you can remove the symbol table with the 'strip' command. In addition to the debugging and symbol information Google DWARF (A Developer joke on ELF) By default most compiler optimizations are turned off when debugging is enabled. So the code is the pure translation of the source into Machine Code rather than the result of many highly specialized transformations that are applied to release binaries. But the most important difference (in my opinion) Memory in Debug builds is usually initialized to some compiler specific values to facilitate debugging. In release builds memory is not initialized unless explicitly done so by the application code. Check your compiler documentation for more information: But an example for DevStudio is: 0xCDCDCDCD Allocated in heap, but not initialized 0xDDDDDDDD Released heap memory. 0xFDFDFDFD "NoMansLand" fences automatically placed at boundary of heap memory. Should never be overwritten. If you do overwrite one, you're probably walking off the end of an array. 0xCCCCCCCC Allocated on stack, but not initialized -g adds debugging information in the executable, such as the names of variables, the names of functions, and line numbers. This allows a debugger, such as gdb to step through code line by line, set breakpoints, and inspect the values of variables. Because of this additional information using -g increases the size of the executable. Also, gcc allows to use -g together with -O flags, which turn on optimization. Debugging an optimized executable can be very tricky, because variables may be optimized away, or instructions may be executed in a different order. Generally, it is a good idea to turn off optimization when using -g, even though it results in much slower code. There is some overlap with this question which covers the issue from the other side. Some operating systems (like z/OS) produce a "side file" that contains the debug symbols. This helps avoid bloating the executable with extra information. Just as a matter of interest, you can crack open a hexeditor and take a look at an executable produced with -g and one without. You can see the symbols and things that are added. It may change the assembly (-S) too, but I'm not sure.
common-pile/stackexchange_filtered
"Failed to load resource: net::ERR_HTTP2_PROTOCOL_ERROR" for React app after upgrading to Visual Studio 2019 16.10.0 After upgrading to VS 16.10.0 (and then 16.10.1) Community Edition a React website no longer runs w/in Visual Studio/IIS Express. The exact same code was just deployed to an Azure app service and works correctly. The home page is blank and the following error is displayed in the Chrome (Version 91.0.4472.77 (Official Build) (64-bit)) debugger console "Failed to load resource: net::ERR_HTTP2_PROTOCOL_ERROR" The solution consists of: C# class library (.NET Core 3.1) C# Web API (.NET Core 3.1) React website I have tried the following: Cleaned and rebuilt solution Cleared browser cache Uninstalled and re-installed Visual Studio Upgraded Visual Studio from 16.10.0 to 16.10.1 Ran npm run build which ran with no errors Additional Note: I was able to restore a virtual machine w/ Visual Studio 2019 v16.9.4 instead of v16.10.1. Then step by step I installed the latest Windows updates and the exact code base. The site runs correctly in v16.9.4. So the problem seems to be in Visual Studio v16.10.0/v16.10.1 Go to the VS Developer Community and up vote this problem https://developercommunity.visualstudio.com/t/Failed-to-load-resource:-net::ERR_HTTP2_/1446262 Do you have KB5003637 windows update installed. If you do uninstall it. @SpeedOfSpin Uninstalled KB5003637 and the same problem still exists. I'm also getting random Blue screen error SYSTEM_THREAD_EXCEPTION_NOT_HANDLED on HTTP.sys This error was driving me nuts too. Windows 10 was updated 2 days ago and I also updated Visual Studio to version 16.10.1. After that, I got the errors, images, CSS not loading correctly. As SpeedOfSpin mentioned in a comment in a previous post, uninstalling KB5003637 worked instantly for me, no more errors! Everything loads perfectly now. It wasn't necessary to go back to an earlier version of Visual Studio, it seems it was Windows OS related. @SpeedOfSpin: Thnx a lot! :) UPDATE ON ISSUE 1 Today there was a new update KB5004476, I don't see the previous KB5003637 anymore here. KB5004476 is causing the same errors. When installed I get the exact same error "Failed to load resource: net::ERR_HTTP2_PROTOCOL_ERROR", uninstalling solves it instantly again. I have asked the Microsoft forum what is going on here: https://answers.microsoft.com/en-us/windows/forum/windows_10-networking/kb5003637-and-the-new-kb5004476-gives-error-failed/db2f2f73-7f5c-477a-b212-5f13c998a09a UPDATE ON ISSUE 2 As they couldn't provide a solution in the first MS forum (previous link), the same question has been asked here: https://learn.microsoft.com/en-us/answers/questions/440339/kb5003637-and-the-new-kb5004476-gives-error-34fail.html Updating Visual Studio to version 16.10.2. doesn't solve the issue either. UPDATE ON ISSUE 3 After some more testing, it seems it affects the browser Chrome only (As I only use Chrome, as most people do). In Firefox, Edge, and IE it seems I'm not having this issue. It was confusing as I tried so many things and the only solution I still have is uninstalling the KB5003637 or the new version KB5004476. So I guess something is wrong with Chrome after all. For now, I will keep the updates uninstalled, I don't feel like changing my preferred browser. UPDATE ON ISSUE 4 It is indeed not a Chrome-only issue, sorry guys. Saw the same error in Edge this morning too. It took a long while to recreate the problem, while in Chrome I have it every single time. :( UPDATE ON ISSUE 5 As asked in the first post here by ChrisP, go to the VS Developer Community if you experience this issue too, and please upvote this problem. I asked the question there also, but still no solid solution at this point. https://developercommunity.visualstudio.com/t/Failed-to-load-resource:-net::ERR_HTTP2_/1446262 UPDATE ON ISSUE 6 Two days ago after 1 single refresh (F5), when testing my web application, aside from the HTTP/2 errors, I also had the same blue screen like people are starting to mention. It showed the error "System Thread Exception not Handled" in file "HTTP.sys" and restarted, amazing! Also, 2 new updates were installed KB5003690 and KB5003537, but nothing changed, I still have the annoying errors. Previous updates KB5003637 and KB5004476, where it started to go wrong, are gone here. Uninstalling these updates as a workaround isn't the best solution for me, as they get reinstalled when wanting to update Windows 10 (No option anymore to exclude/hide the updates). For me the easiest/quickest workaround at this point, to test locally with no “Failed to load resource: net::ERR_HTTP2_PROTOCOL_ERROR” errors, no "System Thread Exception not Handled" BSoD! error and most important no stress anymore :), is disabling SSL in the debug settings of your project in Visual Studio. (Right-click Project, Properties, Debug, Web Server Settings below). Hope this gets fixed quickly! UPDATE ON ISSUE 7 (SOLVED!) Microsoft finally released a fix that works for me, more information here (last post): https://developercommunity.visualstudio.com/t/Failed-to-load-resource:-net::ERR_HTTP2_/1446262?viewtype=all Installing the most recent update KB5004237 solves the problem in my case. No more "Failed to load resource: net::ERR_HTTP2_PROTOCOL_ERROR" errors, no more “System Thread Exception not Handled” error so far too! This should be marked as the correct answer. This saved me ages of looking around for some other error. ThankS! I uninstalled KB5003637 and still had the problem. Eventually converted project to .NET 5 as @speedofspin suggested below and it now works. However, I did see the error one time after refreshing the browser so something isn't 100% correct. This was so helpful as i ran into the same issue. Thank you for posting this. Not correct in my situation, this is not only a Chrome issue. I have tried in Chrome, Edge, Firefox and IE and get exactly the same error no matter. Same problem with the July Security Update KB5004945 :( I previously uninstalled the June update KB5003637 which resolved the problem, but seeing the same symptoms after installing the July update. I tried everything including rolling back updates and a full reinstall of Windows. Finally, a Microsoft support rep posted a workaround for this that involves disabling HTTP2. This seems to have worked for me as a temporary solution. In summary: Start the Windows Registry Editor Navigate to the registry key HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\HTTP\Parameters Add 2 new REG_DWORD values, EnableHttp2Tls and EnableHttp2Cleartext, to this registry key Set both values to 0 Reboot the machine The rep notes: The registry values disable HTTP/2 on the machine. You can remove those values when the fix to https.sys is published. We had the same issue on only the machines that had that KB5003637 installed. We uninstalled it and everything was fine. We decided to upgrade to .net 5 in the end which fixes the issue as it was fairly painless for our projects. If you can't upgrade try disabling HTTP/2 serverOptions.ConfigureEndpointDefaults(lo => lo.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http1); Mine looks like this for .net core 3.1 public static IHostBuilder CreateWebHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.ConfigureKestrel(serverOptions => { serverOptions.Limits.MaxRequestBodySize = int.MaxValue; serverOptions.Limits.MinResponseDataRate = null; serverOptions.ConfigureEndpointDefaults(lo => lo.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http1); }) .UseStartup<Startup>(); }); } I wish this would made any difference in my case, but it didn't - requests were still being made as HTTP/2 and the ERR_HTTP2_PROTOCOL_ERROR error persisted. @speedofspin I get the same error even after adding your code above to Program.cs @speedofsping also tried uninstalling KB5003637 which did not work. Finally, upgraded project to .NET 5 and it now works. Disable the SSL from the project properties it will automatically down to http/1 and then enable the javascript debugger for the browser Hope this will help In my case it was ASP.NET Core Identity that caused the trouble: I had too many roles (user claims) which were stored as session cookies in my browser and caused a "HTTP 400 Bad Request - Request header too long" error. This was showing as HTTP2 protocol error in Chrome and SSL certificate error in Firefox since I was using HTTPS redirection. This was my issue as well. I had some related entities loading via EF core and the string was too long so Chrome was blocking it. Once I removed the related entities that were potentially making an infinite loop, it resolved the issue. Voting up for anyone working in .Net API who might face a similar issue. In my case it was actually a HTTP Error 400 - The size of the request headers is too long, but I kept getting this ERR_HTTP2_PROTOCOL_ERROR message instead. In order to find out the real error message, I had to disable HTTP/2 in IIS(right click your site in IIS, open Edit Bindings, double click your HTTPS binding and check Disable HTTP/2). After fixing the HTTP Error 400 I could enable HTTP/2 again and it worked correctly. I found that disabling SSL (which I think results in IIS Express dropping down to HTTP 1.1) is a workaround. Unfortunately, this is not an option as the site is configured to use SSL. Thanks for the thought. In my case, upgrading the project to .Net core 5.0 (as @SpeedofSpin suggested) did not help - I had the same issue. Disabling SSL (as @samejeep suggested) for application was demanding, because my projects uses IdentityServer4 and it just stopped authenticating after that - so I didn't continue that path. But as a workaround I have changed all requests for css, js, and static files via non-SSL http:// requests. So for example, instead of this <link rel="stylesheet" href="~/css/site.css"> Which would use the current request's protocol https://, I've used absolute paths, e.g.: <link rel="stylesheet" href="http://localhost/css/site.css"> Note, that I'm stating "http" (not "https") explicitly. I did that for css styles and js scripts and that was enough for me. I didn't have to do it for images though. For me this is just a dirty workaround (I'll be waiting for MS to release a patch), but at least it allows me to keep doing my work. Update: I've found a better way to disable HTTP/2 via registry on my localhost and that solves the problem too. this issue (on iis express) on only the OS that had that KB5003637 installed. if you unable delete this update first upgrate windows 10 to last by https://www.microsoft.com/en-ca/software-download/windows10 then you can delete kb5003637 (don't forget disable windows auto update) this didn't work for me, upon updating to the latest windows that KB disappeared so could not uninstall it. Even tried applying it manually to then try uninstalling it but it says the KB was not supported on that version of windows I got this error creating a new blazor app vs2019/windows10 update to latest versions. After looking at a prior working blazor project Startup.cs I fixed by commenting out //app.UseHttpsRedirection(); I think this maybe a new project template problem
common-pile/stackexchange_filtered
DetailViewController Dumb Question I'm working on an iPhone app that has a UITableView with multiple entries and when you click on each, it takes you to the same view using a navigation controller. This is good, I want the same view every time, except for one of my entries I want to hide a text label. I have succeeded in doing this, except I did it in the viewDidAppear method, so when I push the view from the side, it shows up for just a split second before it disappears. How do I fix this so that it never shows up? Thanks, VectorWare Check the answer to this question: http://stackoverflow.com/questions/5630649/what-is-the-difference-between-viewwillappear-and-viewdidappear Have you tried using viewWillAppear, instead? did you try in viewWillAppear, or do it on ViewDidDisappear of your table view. Yes, I have it didn't seem to work i am talking about viewDidDisappear or viewWillDisappear of your table view controller No I haven't tried that yet, I'll do it now I tried and it still isn't working, for some reason my instance variables aren't passing right That requirement calls for the viewWillAppear method. You can and should do all kinds of modifications to your view inside that method. All modifications will be applied to the objects in the current view before it gets shown via the loadView or viewDidLoad methods. From the docs: http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html viewWillAppear: Notifies the view controller that its view is about to be become visible. (void)viewWillAppear:(BOOL)animated Parameters animated If YES, the view is being added to the window using an animation. Discussion This method is called before the receiver’s view is about to be displayed onscreen and before any animations are configured for showing the view. You can override this method to perform custom tasks associated with presenting the view. For example, you might use this method to change the orientation or style of the status bar to coordinate with the orientation or style of the view being presented. If you override this method, you must call super at some point in your implementation. For more information about the how views are added to windows, and the sequence of messages that occur, see the information on presenting a view controller’s view in “Custom View Controllers” in View Controller Programming Guide for iOS Got it. I found the problem and it was resolved, thanks How did you fix it and what was it? For some reason my instance variables weren't passing right
common-pile/stackexchange_filtered
SFTP Issues in Micro Integrator 1.1.0 with WSO2EI 7 Integration Studio I am New to and using WSO2EI Integration Studio 7.0.0 I am getting an error while moving files from my local to SFTP but files are moving to SFTP in this scenario i have used send mediator. Also i am unable to move sftp to local it showing fully error only. 1. VFS Parameters File URI not working 2. VFS Parameter Move after process not working I have used Micro Integrator 1.1.0 Please help me to fix the issues. You should provide some more information, eg. logs. Now it's impossible to determine if the problem is in the application or in network or in SFTP-servers Please attach the carbon.log files to pin point the root cause for this issue.
common-pile/stackexchange_filtered
Using backslashes in Groovy I'm using groovy to write a script that replaces UNC server names and a part of the directory structure. I have the following: def patternToFind = /\\\\([a-zA-Z0-9-]+)\\share\\([a-zA-Z]+)/ def patternToReplace = '\\\\\\\\SHARESERVER\\\\share\\\\OPS' This works, but all those \'s are pretty ugly. I understand in the regex why \\\\ is used to find \\, but what is confusing me is why in the replacement I'm doing I have to use four \'s to equal one \. If anyone has a nicer way to do this I would greatly appreciate it. The goal is to replace \\<server>\share\<env> with the correct value for <server> and <env> Thanks! EDIT: I guess I should clarify. SHARESERVER and OPS are actually variables. So truly the end result would be something like: def serverName = //some passed in server def env = //some passed in env def patternToFind = /\\\\([a-zA-Z0-9-]+)\\NAS\\([a-zA-Z]+)/ def patternToReplace = '\\\\\\\\' + serverName + '\\\\share\\\\' + env So the only way I think of doing it is building a string literal to replace the section I'm looking for with. And I'll be the first to admit that I suck at reg ex, so if you can use them to capture a value in a string and replace just that value with another, I'm all ears. Thanks for the edit! Was trying to figure out how to escape those characters Can't you use the same slashy string format used for patternToFind? /\\\\SHARESERVER\\share\\OPS/ Doesn't it work with def patternToReplace = $/\\SHARESERVER\share\OPS/$ Yup it should assert ($/\\SHARESERVER\share\OPS/$ ==~ /\\\\SHARESERVER\\share\\OPS/). Forgot about the $/ dollar slashy string. :) If you want to use a literal replacement string (as opposed to one that involves $n backreferences) with a regular expression in Java then the safest thing to do is use Matcher.quoteReplacement: def patternToReplace = Matcher.quoteReplacement(/\\SHARESERVER\shares\OPS/) Ha... well spotted. According to my experiments this doubles single backslashes. Despite the method name... and despite the slightly cryptic Javadoc: "Slashes ('') and dollar signs ('$') will be given no special meaning"
common-pile/stackexchange_filtered
Declaring Encryption in a ASP.NET Web App Im receiving the following error "Name 'Encryption' is not declared." On Line If reader_login("password").ToString() = Encryption.Rijndael.Encrypt(Password, "SHA1", 2, 256) Then Locally it is fine just seeing this error now on my development machine. Any Ideas ? What do you mean by "locally it is fine just seeing this error now on my development machine"? Normally "local" does refer to one's development machine. Ok..sorry for the typo I meant on the production server im seeing the above error. What is your Encryption class? You probably forgot to copy a DLL or a file in App_Code to the server. I dont actually have an Encryption class but I see there is a dll in the bin folder EncDec.dll which I believe holds this class. Could it be an issue reading this dll ? Copy that DLL to the bin folder in the server. In Visual Studio, right-click on Rijndael and click Go to Definition to find out where it's defined. Can you find out where the Encryption class is located in your development machine? If it's a 3rd party component that's installed in the GAC, you'll need to install that component on the server too, or if possible copy its assembly (.dll) to the bin folder of your application on the production server.
common-pile/stackexchange_filtered
Filter elements on data-attribute instead of class in jQuery I am working on a simple method for filtering elements depending on their class. The user checks a checkbox and the jQuery does it's thing fine and turns off any element depending on the class. The line that turns off the element, and how the elements look is: $('#ItemList div:not(.' + Filter + ')').hide(); <div class="1 2 3">asdf</div> However I want to be able to use the data-xxxx attribute to do this instead of the class attribute, but I am having problems actually selecting the elements this way. What I have is below: $("#ItemList div:not([data-filter'" + Filter + "'])").hide(); <div data-filter="1 2 3">asdf</div> So, how do I go about selecting the element using the data-filter attribute instead of the class? The methods I have found on here are not working for me! Many thanks. UPDATE Okay, so James Allardice's reply did the trick. But has caused another issue that I probably should I said in the original post. Each data-xxxx attribute can have a number of values, I need this filter to work so that if any one of the value shows up it will not hide the element. $('#Filters input').change(function() { $('#ItemList div').show(); $('input').each(function() { var Checked; if(Checked = $(this).attr('checked')) { var Filter = $(this).attr('data-filter'); $("#ItemList div:not([data-filter='" + Filter + "'])").hide(); }; }); <div data-filter="1">1</div> <div data-filter="1 3">1 3</div> So for example if a checkbox with the following attribute is checked it will show both divs: data-filter="1" But if the attribute is like this it will only show the second: data-filter="3" You can use the jQuery filter function like this: $("#ItemList div").filter(function() { var attr = $(this).attr('data-filter'); var filterArr = attr.split(" "); return $.inArray(Filter, valArr) == -1; } ).hide(); I haven't tested this but it should work. You can find the inArray documentation from the this link and the documentation for the filter function from this link You were close. You're just missing the = character: $("#ItemList div:not([data-filter='" + Filter + "'])").hide(); // ^ You missed this Here's a working example. Thats the one! Nice one, however I now have another problem, that I didn't count on. Shall update the job. jQuery('[data-name=something]') or for not, jQuery('[data-name!=something]') Check out the attribute selectors available here: http://api.jquery.com/category/selectors/
common-pile/stackexchange_filtered
Are all principal curvatures equal at an isotropy point? Suppose $M$ is a hypersurface embedded in a Riemannian manifold $(N, g)$ and there exists $p\in M$ s.t. for any two tangent vectors $u,v\in T_pM$ we can find an isometry $\phi$ of $M$ fixing $p$ s.t. $d\phi_p u=v$. Because there is no preferred direction, it seems intuitive that all principal curvatures of $M$ at $p$ are equal. An identity that would immediately prove this hypothesis would be $$ s \phi_* v=\phi_* sv,$$ Where $s$ is the shape operator of $M$. This equation is equivalent to $$h(\phi_* v, \phi_* w) = g(s \phi_* v, \phi_*w) = g(\phi_* sv,\phi_*w) = g(sv,w)=h(v,w),$$ Where $h$ is the scalar second fundamental form of $M$. Since $h$ is related to the Levi-Civita connection, which is invariant under isometries, I would expect $h$ to also be preserved under $\phi$, but the fact that we also need to consider the connection in the ambient manifold $N$ confounds me. Is the claim even true?
common-pile/stackexchange_filtered
morphia query against relationship/reference I have a product document which has a reference to review array - Review[] Reviews. Review has ranking 1-5. How do I go about query against review for this product that is 4 stars ranking and above? I tried criteria("Reviews.ranking").Equal(4).asList() It complaint that it couldn't find Reviews. Only embedded objects can be filtered using this way see http://stackoverflow.com/questions/25180853/filter-list-of-embedded-documents-with-reference-field and see also link
common-pile/stackexchange_filtered
Aspect ratio not same after resizing thumbnails in PHP (GD) I am resizing an image to make thumbnails in PHP, but the aspect ratio is not same. I have gone from the code but I can't figure out what the problem is. Here is the code I am using. <?php $idir = "gallery/"; $tdir="gallery/thumbs/"; if(!file_exists($tdir)){ mkdir($tdir); } chmod($idir,755); /* It creates new thumbnails here */ function createThumbs($idir, $tdir, $tw, $th){ $dir=opendir($idir); global $fname; while(($fname = readdir($dir)) != false){ if($fname!='.' && $fname != '..'){ $img = imagecreatefromjpeg($idir.$fname); $width = imagesx($img); $height = imagesy($img); if($width>$height){ $nw=$tw; $nh=$height*($th/$width); } if ($width < $height) { $nw=$width*($tw/$height); $nh=$th; } if ($width == $height) { $nw=$tw; $nh=$th; } $tmp_img = imagecreatetruecolor($nw, $nh); imagecopyresampled($tmp_img, $img, 0,0,0,0, $nw, $nh, $width, $height); imagejpeg($tmp_img, $tdir.'tn_'.$fname); } } closedir($dir); } if (!file_exists($tdir.'tn_'.$fname)) { createThumbs($idir,$tdir,903, 603); } ?> Please help me find out what the problem is. Also, Please share any other effective way to create thumbnails in php. Try using imagecopyresampled() rather than imagecopyresized(). I tried but it is still not maintaining the aspect ratio I've found out what I was doing wrong. The formula to calculate the new aspect ratio was wrong the new formula would be like this: if($width>$height){ $nw=$tw; $nh=$height*($tw/$width); } if ($width < $height) { $nw=$width*($th/$height); $nh=$th; } if ($width == $height) { $nw=$tw; $nh=$th; }
common-pile/stackexchange_filtered
java keyPressed event I have read many answer from stack overflow but can't solve my problem so i am posting question i have written code for Key Press Action in java swing but nothing is happening when ever i am pressing key so please advice where i have written wrong codes my codes are as under textField_1.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if(e.getKeyCode()==KeyEvent.VK_TAB){ try{ String query="select * from checklist where sbno='"+sb+"'"; PreparedStatement pst=connection.prepareStatement(query); ResultSet rs=pst.executeQuery(); while (rs.next()){ Shipping_Marks.setText(rs.getString("smarks")); Shippername.setText(rs.getString("shipper")); } rs.close(); }catch (Exception e1){ e1.printStackTrace(); } } add only System.out.print("pressed"); and test again its also not working yes so when you post a question post only relavant minimum code.the database part doesn't requred here "I have read many answer from stack overflow .." Link the top 3, and explain why they did not work for you. Note that if you saw 'many answers' it is likely that some of them mentioned component focus, as well as components consuming the event. OTOH there is nothing in that uncompilable code snippet which might tell us if either of those things is happening. For better help sooner, post a [MCVE] or Short, Self Contained, Correct Example. It is also common for answers related to Swing and KeyListener to mention key bindings. Have you tried them? @AndrewThompson feel free to join us in campaigns for java closing anytime Tab is intercepted before it goes to the field. If you want to intercept Tab you have to use work around or, better, don't use Tab as the Key to intercept. No Tab key-pressed or key-released events are received by the key event listener. This is because the focus subsystem consumes focus traversal keys, such as Tab and Shift Tab. General idea is that Tab is used to switch between components. That's the main function of it. Another approach (for you) could be to exclude this field from traveling by Tab like this: text_Field1.setFocusTraversalKeysEnabled(false); or you can use the fact that this field loses focus and use methods which catch this event. Here is some tutorial to do so. how to use container i m new pls saw some example sir i have tried action event performed for this and it is working with enter key but i want set this to tab key Tab is used to move between fields. Field itself doesn't see it. thank you sir text_Field1.setFocusTraversalKeysEnabled(false); worked perfectly for my app thank you very much
common-pile/stackexchange_filtered
FTPClient downloads a 0 byte file I'm trying to download a file from a server, but it get 0 bytes... this is my FTPDownload class public boolean getFile(String filename){ try { FTPClient ftpClient = new FTPClient(); ftpClient.connect(ftpAddress, ftpPort); ftpClient.login(ftpUser, ftpPass); int reply = ftpClient.getReplyCode(); //FTPReply stores a set of constants for FTP reply codes. if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); return false; } ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.setBufferSize(1024*1024); String remoteFile = serverPath + filename; logger.debug("remote file is: "+remoteFile); //correct path File tempFile = new File(downloadDir+"temp.jar"); logger.debug("file will be "+tempFile.toString()); //correctly created OutputStream os = new BufferedOutputStream(new FileOutputStream(tempFile)); ftpClient.retrieveFile(remoteFile, os); os.close(); String completeJarName = downloadDir+jarName; //delete previous file File oldFile = new File(completeJarName); FileUtils.forceDelete(oldFile); //rename File newFile = new File(completeJarName); FileUtils.moveFile(tempFile, newFile); if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException e) { // TODO Auto-generated catch block logger.error("errore ftp", e); return false; } return true; } Basically, the temp fie gets created, then the previous file gets cancelled and the temp file renamed, but it is 0 bytes... i cannot understand where something goes wrong... I'm not sure but try to flush the output stream os.flush() after ftpClient.retrieveFile but before os.close(). you can resolve this? i used apache.common for FTP download. here is the code, you can try public class FTPUtils { private String hostName = ""; private String username = ""; private String password = ""; private StandardFileSystemManager manager = null; FileSystemOptions opts = null; public FTPUtils(String hostName, String username, String password) { this.hostName = hostName; this.username = username; this.password = password; manager = new StandardFileSystemManager(); } private void initFTPConnection() throws FileSystemException { // Create SFTP options opts = new FileSystemOptions(); // SSH Key checking SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking( opts, "no"); // Root directory set to user home SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, false); // Timeout is count by Milliseconds SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000); } public void onUpload(String ftpfolder, String localFilePath, String fileName) { File file = new File(localFilePath); if (!file.exists()) throw new RuntimeException("Error. Local file not found"); try { manager.init(); // Create local file object FileObject localFile = manager.resolveFile(file.getAbsolutePath()); String remoteFilePath = "/" + ftpfolder + "/" + fileName; // Create remote file object FileObject remoteFile = manager.resolveFile( createConnectionString(hostName, username, password, remoteFilePath), opts); // Copy local file to sftp server remoteFile.copyFrom(localFile, Selectors.SELECT_SELF); System.out.println("Done"); } catch (Exception e) { // Catch and Show the exception } finally { manager.close(); } } public static String createConnectionString(String hostName, String username, String password, String remoteFilePath) { return "sftp://" + username + ":" + password + "@" + hostName + "/" + remoteFilePath; } } are you sure this is for downloading and not uploading a file to a server? yes this is my existing code. i have used for my purpose BufferedOutputStream writes data to an internal buffer, so you probably need to flush the outputStream before closing: OutputStream os = new BufferedOutputStream(new FileOutputStream(tempFile)); ftpClient.retrieveFile(remoteFile, os); os.flush(); os.close(); Another tips: Always give the Buffered streams a buffer size (typically a multiple of 8Kb). Always use the try-with-resources instruction when instantiating streams, and let them be automatically closed. Do not leave a catch clause without proper treatment. An exception should either fixed (if you want your program to recover from that exception) either propagated upwards (by default, propagated). Only a log is not likely to be the best treatment.
common-pile/stackexchange_filtered
Calculating memory requirements for HashMap in Java I have a ConcurrentHashMap like so: HashMap<String, Integer> fruitMap = new ConcurrentHashMap<>(); The key is a String of 10 characters, the value is an Integer. Assuming there is no other memory consuming code in my application, how do I calculate the number of entries that can be stored in the HashMap on a server with 10GiB memory? It'll be great if you can mention how we can calculate it for both Java 7 and Java 8 or later. PS: I found this, but I didn't understand how the 6.75KB memory usage for hashmap of 100 ints mapped to ints was arrived at. it depends on the JVM version, on how big your heap is going to be, on some enabled/disabled flags. there is no X answer. And of course HashMap is not assignable to ConcurrentHashMap And you will not get an exact number, but a ballpark figure, is that enough for you, e.g. 10M entries vs. 100m entires vs. 1B entries!? 6.75KB is because, its not the primitive type that gets stored but the Integer objects which has some overhead. Refer this - https://stackoverflow.com/questions/8419860/integer-vs-int-with-regard-to-memory . Additionally, hash map internally stores data in buckets...All keys that maps to same hash code will be in same bucket. That too has some overhead. @luk2302 why do you say that? of course you can compute the exact size under a specific JVM version with specific flags enabled. @Eugene The exact size will depend on the exact content (effect on buckets, chains, etc), load factor, concurrency level, initial size, etc, so it is hard to generalize. @MarkRotteveel agreed, my point was that for a very specific case - this is totally doable. If this answered your question, you can accept it. I will only provide you an example against jdk-15 using JOL (that is the only reliable tool I would ever trust for this), for a ConcurrentHashMap with 10 entries, it is up to you from there. Map<String, Integer> throttleMap = new ConcurrentHashMap<>(); for(int i = 0; i< 10; ++i){ throttleMap.put((""+i).repeat(10), i); } System.out.println( GraphLayout.parseInstance((Object)throttleMap).toFootprint()); This will output: COUNT AVG SUM DESCRIPTION 10 32 320 [B 1 80 80 [Ljava.util.concurrent.ConcurrentHashMap$Node; 10 16 160 java.lang.Integer 10 24 240 java.lang.String 1 64 64 java.util.concurrent.ConcurrentHashMap 10 32 320 java.util.concurrent.ConcurrentHashMap$Node 42 1184 (total) Understanding the above is not trivial. Integer is the easiest one: 12 bytes for two headers 4 bytes for the inner int field So 16 bytes for one, you have 10 of those, thus that line: 0 16 160 java.lang.Integer an instance of String is more involved: 12 bytes for headers 4 bytes for hash field 1 byte for coder field 1 boolean for hashIsZero field (what is hashIsZero?) 2 bytes for padding 4 bytes for value (byte []) So 24 bytes * 10: 10 24 240 java.lang.String That inner byte [] will also add: 12 bytes of headers (byte[] is an Object). 4 bytes for the length field 10 bytes for each of the 10 bytes 6 bytes padding Thus that: 10 32 320 [B Getting the overall picture is left as an exercise to you. What are the other lines in the output indicating? 10 32 320 [B 1 80 80 [Ljava.util.concurrent.ConcurrentHashMap$Node 1 64 64 java.util.concurrent.ConcurrentHashMap Does the final output line mean that a total 1184 bytes are used?: 42 1184 (total) @seeker yes, that means 1184 bytes. Thanks. I'm still wondering what's the difference between the 1st line in the output and 6th line in the output. Why is 320 bytes used twice? @seeker different Objects, exactly as the Description field says? Right. I'm trying to understand what is [B (bytes[]) used for and what is java.util.concurrent.ConcurrentHashMap$Node used for? One of them is probably to store the bucket information of the HashMap, but which one is it and what is the other one used for. @seeker did you actually read what I wrote in the answer? I did explain what that byte[] is for, at the very end. That Node is an internal class in CHM, that stores the key value pairs ( which you would find out by simply looking at the source code of it )
common-pile/stackexchange_filtered
Command Parameter Datagrid SelectedItems is null So I found this answer Pass command parameter from the xaml which I think got me most of the way there. The problem I am having is when I select a row in the datagrid it triggers the command but the selected items is null. What I don't know, and suspect is the issue, is what type should I be passing the selecteditems to in the view model? Currently I am using IList as shown in my viewmodel code: namespace Project_Manager.ViewModel { public class ProjectSummaryViewModel : ObservableObject { public ProjectSummaryViewModel() { ProjectSummary = DatabaseFunctions.getProjectSummaryData(); } private ObservableCollection<ProjectSummaryModel> projectsummary; public ObservableCollection<ProjectSummaryModel> ProjectSummary { get { return projectsummary; } set { projectsummary = value; OnPropertyChanged("ProjectSummary"); } } public ICommand DeleteRowCommand { get { return new ParamDelegateCommand<IList<ProjectSummaryModel>>(DeleteRow); } } private void DeleteRow(IList<ProjectSummaryModel> projectsummaryselected) { string name = projectsummaryselected[0].ProjectName; } } } The XAML view code for the datagrid looks like this: <Window x:Class="Project_Manager.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <!--<Window.Resources> <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" /> </Window.Resources>--> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <!--Menu row--> <RowDefinition Height="Auto"/> <!--button row--> <RowDefinition/> <!--Current projects--> <RowDefinition/> <!--Completed projects--> </Grid.RowDefinitions> <!--<Menu> <MenuItem Header="File"> <MenuItem Header="New Project Management" CommandTarget="{Binding NewTable}"/> <MenuItem Header="Open Project Management"/> <Separator/> <MenuItem Header="Exit"/> </MenuItem> <MenuItem Header="View"> <MenuItem x:Name="ViewCompleted" IsCheckable="True" IsChecked="True" Header="View Completed Projects List"/> </MenuItem> <MenuItem Header="Project Management"> <MenuItem Header="New Project"/> </MenuItem> </Menu>--> <StackPanel Grid.Row="1" Orientation="Horizontal"> <Button Content="Create New Project" Command="{Binding Path=NewProjectCommand}"/> <!--<Button Content="View Details" Visibility="{Binding Source={x:Reference Name=CurrentProjectsDataGrid}, Path=IsSelected, Converter={StaticResource BooleanToVisibilityConverter}}"/>--> </StackPanel> <Grid Grid.Row="2"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition/> </Grid.RowDefinitions> <TextBlock Text="Current Projects" Background="LemonChiffon"/> <DataGrid x:Name="SummaryDataGrid" ItemsSource="{Binding ProjectSummary}" Grid.Row="1" AutoGenerateColumns="True" Style="{StaticResource DataGridStyle}"> <DataGrid.ContextMenu> <ContextMenu> <MenuItem Header="Delete Row" Command="{Binding DeleteRowCommand}" CommandParameter="{Binding SelectedItems, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}"/> </ContextMenu> </DataGrid.ContextMenu> </DataGrid> </Grid> <!--<DataGrid.Columns> <DataGridTextColumn Header="Project Name" Binding=""/> <DataGridTextColumn Header="Team Name"/> <DataGridTextColumn Header="Latest Update"/> <DataGridTextColumn Header="Date Started"/> </DataGrid.Columns>--> <!--<Grid Grid.Row="3"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition/> </Grid.RowDefinitions> --><!--<TextBlock Text="Completed Projects" Background="LightGreen" Visibility="{Binding Source={x:Reference Name=ViewCompleted}, Path=IsChecked, Converter={StaticResource BooleanToVisibilityConverter}}"/> <DataGrid Grid.Row="1" AutoGenerateColumns="False" Style="{StaticResource DataGridStyle}" Visibility="{Binding Source={x:Reference Name=ViewCompleted}, Path=IsChecked, Converter={StaticResource BooleanToVisibilityConverter}}"> <DataGrid.Columns> <DataGridTextColumn Header="Project Name"/> <DataGridTextColumn Header="Team"/> <DataGridTextColumn Header="Date Completed"/> </DataGrid.Columns> </DataGrid>--><!-- </Grid>--> </Grid> And just in case this is a command implementation problem here is the custom Delegate Command that I am using: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Input; namespace Project_Manager.Common { public class ParamDelegateCommand<T> : ICommand { public event EventHandler CanExecuteChanged; private Action<T> executeMethod; //private Func<T, bool> canExecuteMethod; public ParamDelegateCommand(Action<T> executeMethod) //, Func<T, bool> canExecuteMethod) { this.executeMethod = executeMethod; //this.canExecuteMethod = canExecuteMethod; } public bool CanExecute(object parameter) { return true; //canExecuteMethod((T)parameter); } public void Execute(object parameter) { executeMethod((T)parameter); } } } I have searched around and can find plenty of examples for the XAML binding I just can't seem to find the other half of it. So what type should be in the viewmodel? Alternatively what is the actual problem? Edit: Just noticed an error the debug window that might help someone System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.DataGrid', AncestorLevel='1''. BindingExpression:Path=SelectedItems; DataItem=null; target element is 'MenuItem' (Name=''); target property is 'CommandParameter' (type 'Object') If you are using context menu please refer the below code to get SelectedItems. <ContextMenu> <MenuItem Header="Delete Row" Command="{Binding DeleteRowCommand}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.SelectedItems}"/> </ContextMenu> Also Selecteditems is an IList so change the code like below. public ICommand DeleteRowCommand { get { return new ParamDelegateCommand<IList>(DeleteRow); } } private void DeleteRow(IList projectsummaryselected) { string name = (projectsummaryselected[0] as ProjectSummaryModel).ProjectName; } that mostly worked! I am now getting the selecteditem but if I use 'string name = projectsummaryselected[0].ProjectName;' I get an error object does not contain a definition for ProjectName and no extension method could be found. Which is strange because if I look at 'projectsummaryselected[0].ToString();' then I see ProjectName with a value. How do I get to it? edit my answer. you need to typecast to get the list. In case anyone else finds this and gets to the same point; with the help of the answer here: How to get single value of List I was able to figure it out. I ended up using a 'foreach (ProjectSummaryModel item in projectsummaryselected) { item.ProjectName} got me the value. Thank you for everyones help!!! sorry just saw your comment. That worked too! And is a lot nicer than a foreach loop. Thank you again!!! I tried this and the IList if always empty. How are the selected items be cleared everything I right click? Try this <MenuItem Header="Delete Row" Command="{Binding DeleteRowCommand}" CommandParameter="{Binding SelectedItems, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}"/> Thank you @Muds for the response but I am still getting null. I edited my post with an error message that I just noticed in the debug window. Not sure if that would help or not. I have slightly changed the code , and this works for me if it still wont work, post some more code to understand I am still getting null. I have posted more code. It is a small project so there isn't too much more. I included the DelegateCommand class in case that is causing the problem
common-pile/stackexchange_filtered
Creating a file based on the byte() in VB.NET I am retrieving an image from the SQL database into Byte() variable in VB.NET. Dim img as byte() = dr(0) How do I create a file in my C:\images\ directory from the above img. I want to read the img and then create a file with name bimage.gif. The easiest way is to use File.WriteAllBytes Dim img as byte()=dr(0) File.WriteAllBytes("C:/images/whatever.gif", img) It's still weird to me how forward slashes work the same as backslashes in Windows now (unless it's always been that way). @MusiGenesis, agreed, afaik not everything supports forward slashes, but .NET does and they doesn't require escaping. System.IO.File.WriteAllBytes(@"c:\whatever.txt", bytes) Try: Dim ms as MemoryStream = New MemoryStream(img) Dim bmp as Bitmap = CType(Bitmap.FromStream(ms), Bitmap) bmp.Save(@"C:\images\name.gif", ImageFormat.Gif); bmp.Dispose() ms.Dispose()
common-pile/stackexchange_filtered
How to update regex to allow empty value or alphanumeric only I'm trying to modify a regex so it will allow an empty value or alphanumeric only. I currently have this, but it only validates the alphanumeric if (ruletype eq "alphanumeric") { bMatch = true; variables.fieldName = listGetAt(arguments.rules[nRow],2,","); if (structKeyExists(arguments.form, "#variables.fieldName#")){ if (NOT RefindNoCase("[[:alnum:]]",arguments.form[variables.fieldName])) { lstError = listAppend(lstError,nRow,","); } } else { lstError = listAppend(lstError,nRow,","); } } I tried converting to rematch to find the empty value, but that also accepts the value 1234^%^&& which contains special characters. I'm not sure how to fix that. Alpha-numeric only and allow the empty string is ^[[:alnum:]]*$ but when adding the one u gave @sln, it also verifies the value as: test123%^&**&^& - which is wrong If the ^[A-Za-z0-9]*$ does not work, the code is wrong. Which version of ColdFusion? Lucee, its not ACF Do I understand correctly, from the value you mention, that arguments.form[variables.fieldName] is a comma-delimited list? If so, then what is to be matched is each list-item.(Incidentally, the # in sdkfk364563!@#$% has to be delimited). A possible answer is then: if (structKeyExists(arguments.form, variables.fieldName)){ // Assuming arguments.form[variables.fieldName] is a comma-delimited list fieldNameArray=listToArray(arguments.form[variables.fieldName], ',', true); for (fieldValue in fieldNameArray) { fieldValue=trim(fieldValue); if (fieldValue eq "" or REfindNoCase("^[a-zA-Z0-9]*$",fieldValue) eq 0) { lstError = listAppend(lstError,nRow); } } } [[:alnum:]] is POSIX syntax, which may not be supported. Use the universal ASCII syntax, [a-zA-Z0-9]. Also modify your code to account for the presence of an integer and to rule out any possible space character. if (structKeyExists(arguments.form, variables.fieldName)){ if (REfindNoCase("^[a-zA-Z0-9]*$",trim(arguments.form[variables.fieldName])) eq 0) { lstError = listAppend(lstError,nRow); } } btw i want to allow an emptyvalue to e passed and not validated, but the value is: sdkfk364563!@#$%, then it should fail
common-pile/stackexchange_filtered
How to right join a date table in T-SQL? I have done RIGHT JOINS in the past with no problems. However, for some reason now, I am not able successfully join a date table on the date field. In summary, I have two tables. The first table has one date column and a couple more non-date columns. Then I have a date table, which just has two date columns. I initialize this date table by inserting into it first of month dates for 13 consecutive months. But my other table only has 9 months of data. So table A looks like: col_A col_B col_C ----- ------ ------- sfds jkjlj 7-1-2009 rewr sfsfsd 5-1-2009 xcxvg sdfsfk 4-1-2009 ... But table B looks like: StartDate EndDate --------- --------- 7-1-2009 7-31-2009 6-1-2009 6-30-2009 5-1-2009 5-31-2009 ... But when I right join table B onto A like so: SELECT * FROM TABLE_A A RIGHT JOIN TABLE_B B ON A.COL_C = B.StartDate I expect to get 12 months of data since Table_B has 13 months/records. However, instead I am only getting 9 months total. Does anybody understand why this would be? And other things I might try to achieve the same result? My main goal is to make Table_A include every month for past 13 months, even if there are null values. Right now though, it just includes 9 months since there no records for the other 4 months. TSQL for Sybase or SQL Server? Version would help too You sure the full version doesn't have a where clause? Can you give us all data in both tables and the actual query please? If there are 13 rows in B you'd get 13 rows out unless you've filtered them out with a WHERE or something I'm thinking something is confused. If you do SELECT * FROM TABLE_B do you actually get 13 rows? Joining on date columns can be problematic if there is a time portion to the dates (and there often is!). It's safer to use DATEPART() or CONVERT() (or other date functions) to extract just the date portion but this will probably exclude using indexes. one way is to use: DATEADD(day, DATEDIFF(day, 0, DateColumn), 0) i.e. SELECT * FROM TABLE_A A RIGHT JOIN TABLE_B B ON DATEADD(day, DATEDIFF(day, 0, A.COL_C), 0) = DATEADD(day, DATEDIFF(day, 0, B.StartDate), 0) There is also this form: CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME) but I prefer the former. Thanks, you just reminded me. The date column in Table_A is actually a CASTed date, where it casts the date into the first day of that month, but it still remains a date datatype. Thanks for the tips though. I am not at my work computer now, but I will try this tomorrow and let you know. Even if they didn't match he should have the records since it is an outer join. Thanks Mitch, but I actually need the first day of month from Table_A. And your code just gives me that same day. How would I do this for first day of month? thanks i modified my description. Can u look? still < 13 months. I just tried this and got all months, columns col_A, col_B and col_C being null where there wasn't a match. Are you sure all your dates are there and there isn't a where clause affecting this? SELECT * FROM TABLE_A A sfds jkjlj 2009-07-01 00:00:00.000 SELECT * FROM TABLE_B B 2009-07-01 00:00:00.000 2009-07-31 00:00:00.000 2009-06-01 00:00:00.000 2009-06-30 00:00:00.000 2009-05-01 00:00:00.000 2009-05-31 00:00:00.000 SELECT * FROM TABLE_A A RIGHT JOIN TABLE_B B ON A.COL_C = B.StartDate sfds jkjlj 2009-07-01 00:00:00.000 2009-07-01 00:00:00.000 2009-07-31 00:00:00.000 NULL NULL NULL 2009-06-01 00:00:00.000 2009-06-30 00:00:00.000 NULL NULL NULL 2009-05-01 00:00:00.000 2009-05-31 00:00:00.000 thanks i modified my description. Can u look? still < 13 months. i removed the where clause in 2nd insert. What I usually do when joining on dates is to convert them to integers first since joining on dates (1) often gives unexpected results, and (2) it is slow. I would do the join like so: Select * From TABLE_A A Right Join TABLE_B B On ((Year(A.COL_C)*10000) + (Month(A.COL_C)*100) + Day(A.COL_C)) = ((Year(B.StartDate)*10000) + (Month(B.StartDate)*100) + Day(B.StartDate)) However it seems you really want to join the year and month since the date on Table_A is always the 1st. I would do that like so: Select * From TABLE_A A Right Join TABLE_B B On ((Year(A.COL_C)*100) + Month(A.COL_C)) = ((Year(B.StartDate)*100) + Month(B.StartDate)) Hope this helps.
common-pile/stackexchange_filtered
How to display time in hours overshooting 24 hours in SSRS I have a report with a column displaying time cumulatively overshooting 24 hours. I'd like it to be displayed in hours. I've found a solution that when time exceeds 86400 seconds (number of seconds in a day), it'll display number of days and time but I want only time in hours to be displayed. =IIF(Fields!TotalTime.Value < 86400, Format(DateAdd("s", Fields!TotalTime.Value, "00:00:00"), "HH:mm:ss"), Floor(Fields!TotalTime.Value / 86400) & " days, " & Format(DateAdd("s", Fields!TotalTime.Value, "00:00:00"), "HH:mm:ss") Please provide sample data and expected results based on the sample data is my desired outcome. You could do this with expressions only but this way is a little bit more reusable.. Add the following code to your Report's custom code (apologies to the original author who's blog I based this on years ago... I can't find your post) Public Function SecondsAsHHMMSS(ByVal secs) As String Dim h As String =INT(secs/3600) Dim m as string Dim s as string If Len(h) <2 Then h = RIGHT(("0" & h), 2) End If m = RIGHT("0" & INT((secs MOD 3600)/60), 2) s = RIGHT("0" & ((secs MOD 3600) MOD 60), 2) SecondsAsHHMMSS= h & ":" & m & ":" & s End Function This function will take a number of seconds and convert to to HH:MM:SS format. Now all we have to do is pass in the cumulative number of seconds for each row. We can use System.TimeSpan for this. This assumes the database field is a TIME datatype =Code.SecondsAsHHMMSS(RunningValue(Fields!TimeInOffice.Value.TotalSeconds, SUM, Nothing)) Starting from the middle and working out.... We get the value of the TimeInOffice field and, as it's a Time datatype we can use the TotalSeconds property to get the number of seconds this time represents. We get the running sum of these number of seconds ('Nothing' is the scope, if you want to limit the scope within a rowgroup etc, put the name of the rowgroup, in quotes, in place of the Nothing keyword) New we have the number of seconds, we pass this to our custom function The result looks like this.
common-pile/stackexchange_filtered
Jenkins - Unexpected executor death I see all my executors frequently changing to Dead state in one of my Jenkins slave machine(Windows 2008 R2 SP2). Jenkins ver. 1.651.3 I have restarted Jenkins server as well as the service. error logs- Unexpected executor death java.io.IOException: Failed to create a temporary file in /var/lib/jenkins/jobs/ABCD/jobs/EFGH/jobs/Build at hudson.util.AtomicFileWriter.<init>(AtomicFileWriter.java:68) at hudson.util.AtomicFileWriter.<init>(AtomicFileWriter.java:55) at hudson.util.TextFile.write(TextFile.java:118) at hudson.model.Job.saveNextBuildNumber(Job.java:293) at hudson.model.Job.assignBuildNumber(Job.java:351) at hudson.model.Run.<init>(Run.java:284) at hudson.model.AbstractBuild.<init>(AbstractBuild.java:167) at hudson.model.Build.<init>(Build.java:92) at hudson.model.FreeStyleBuild.<init>(FreeStyleBuild.java:34) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:526) at jenkins.model.lazy.LazyBuildMixIn.newBuild(LazyBuildMixIn.java:175) at hudson.model.AbstractProject.newBuild(AbstractProject.java:1018) at hudson.model.AbstractProject.createExecutable(AbstractProject.java:1209) at hudson.model.AbstractProject.createExecutable(AbstractProject.java:144) at hudson.model.Executor$1.call(Executor.java:364) at hudson.model.Executor$1.call(Executor.java:346) at hudson.model.Queue._withLock(Queue.java:1365) at hudson.model.Queue.withLock(Queue.java:1230) at hudson.model.Executor.run(Executor.java:346) Caused by: java.io.IOException: Permission denied at java.io.UnixFileSystem.createFileExclusively(Native Method) at java.io.File.createNewFile(File.java:1006) at java.io.File.createTempFile(File.java:1989) at hudson.util.AtomicFileWriter.<init>(AtomicFileWriter.java:66) ... 21 more I see this error log in my slave machine INFO: File download attempt 1 Oct 17, 2017 10:32:00 AM com.microsoft.tfs.core.clients.versioncontrol.VersionControlClient downloadFileToStreams INFO: File download attempt 1 Oct 17, 2017 10:32:00 AM com.microsoft.tfs.core.ws.runtime.client.SOAPService executeSOAPRequestInternal INFO: SOAP method='UpdateLocalVersion', status=200, content-length=367, server-wait=402 ms, parse=0 ms, total=402 ms, throughput=913 B/s, gzip Oct 17, 2017 10:32:00 AM com.microsoft.tfs.core.clients.versioncontrol.VersionControlClient downloadFileToStreams INFO: File download attempt 1 Oct 17, 2017 10:32:00 AM com.microsoft.tfs.core.clients.versioncontrol.VersionControlClient downloadFileToStreams INFO: File download attempt 1 Oct 17, 2017 10:32:00 AM com.microsoft.tfs.core.clients.versioncontrol.VersionControlClient downloadFileToStreams INFO: File download attempt 1 You said that it's a Windows slave, but the stack trace shows it trying to create a Unix file. Where has that message been generated? This error message is from Jenkins Server Log UI And your server is Linux right? My Jenkins server is Ubuntu 14.04.2-server-amd64 and my slave is Windows 2008 R2 You could investigate why you're getting a Caused by: java.io.IOException: Permission denied When creating a temporary file in /var/lib/ @Spangen How this will impact my slave machine to go in Dead state Are there any logs from the slave machines them selves you could add to the original post? I added them in original post Same problem, same callstack. Jenkins 2.90. However, "caused by" is different: Input/output error @Kally Re "How this [Permission denied] will impact my slave machine to go in Dead state": If a file that's necessary for a job to run on a slave can't be created due to a general, unspecific IOException, compared to its specific derivatives, it's reasonable that the slave goes to Dead state, rather than to try again, and again, and again, and ... Can you please check the owner of the path /var/lib/jenkins/jobs/ABCD/jobs/EFGH/jobs/Build ? By any chance if it is created manually, you will get permission denied error if the owner is not Jenkins. Also check for free disk space on server as well as agent and try rebooting the slave agent. It has helped it at times. ls -l <folder > gives the result: total 17 drwxr-xr-x 2 root root 0 Dec 1 14:17 builds -rwxr-xr-x 1 root root 4507 Dec 1 13:57 config.xml lrwxrwxrwx 1 root root 22 Dec 1 14:15 lastStable -> builds/lastStableBuild lrwxrwxrwx 1 root root 26 Dec 1 14:15 lastSuccessful -> builds/lastSuccessfulBuild -rwxr-xr-x 1 root root 3 Dec 1 14:15 nextBuildNumber But that does not explain why restart works. The 2 things are totally different. First is of permission denied and second is of dead slaves. Permission denied can be resolved by changing the owner to jenkins user and the dead slave issue is resolved by freeing up disk space(in case slave is running out of space) and restarting the slave. No, there is plenty of free space. Ok. Is the issue resolved? or are you still facing it? I guess restart resolved it. No, it is not resolved. It happens from time to time, and I don't know 1) what causes it 2) how to prevent it. Permissions are correct, disk space is enough. Your permissions are not set correctly. Please change the owner of the directory to jenkins user from root. Also everything under jenkins home should be owned by jenkins user, not root user. Change the owner of jenkins home directory recursively to jenkins. you can use command -- sudo chown jenkins:jenkins <JENKINS_HOME> Let us continue this discussion in chat. How long are the real job names for ABCD and EFGH? I've run into the 260 character maximum path length with Jenkins on Windows 2008 R2 before. The path in: java.io.IOException: Failed to create a temporary file in /var/lib/jenkins/jobs/ABCD/jobs/EFGH/jobs/Build with the three /jobs in it seems strange to me. In Jenkins it normally should rather be: +- /var/lib/jenkins/jobs +- ABCD | +- builds | | +- ... | +- ... +- EFGH | +- builds | | +- ... | +- ... +- Build +- builds | +- ... +- ... Maybe there's some misconfiguration concerning paths and Jenkins tries a mkdir /var/lib/jenkins/jobs/ABCD/jobs/EFGH/jobs/Build and the Jenkins user or the user under which the job runs doesn't have permissions to do that. See also File permissions and attributes: |   w   |   ...   | The directory's contents can be modified (create new files or folders; [...]); requires the execute permission to be also set, otherwise this permission has no effect. | I think the CloudBees Folder plugin organizes in "jobs" folders. I think OP may be using that or a similar plugin to organize jobs. In my situation, this happened because the server was very low on space. Click on "Build Executor Status" from the dashboard and see if there is low disk space or 0 swap space. Try to free up some space. Then restart the Jenkins server / service and try again.
common-pile/stackexchange_filtered
Storing relation in RavenDB without manually storing the related documents? TLDR: Is it possible to: store a document (Article) with a relation (Tags) in one Store/StoreAsync call to RavenDB, but into separate collections? then fetch the parent document (Article) including the related documents (Tags) in one query (without including/loading the tags separately)? Explanation AFAIK the only way to store data to RavenDB which have a relation into separate collections is to store them individually. When you read the data, you need to Include the related documents and call Load to get them. I wonder if there is a way to simplify this by storing and querying Articles and related Tags in one go. I have a idea how I wish it would work (but it does not), as well a working but cumbersome example. The examples below are split into these steps POCOs Storing data Index definition Querying the index I put the broken-but-I-wish-it-would-work and the working examples next to each other. I think it is easier to understand it that way. POCOs broken-but-I-wish-it-would-work namespace Articles { public class ArticlePersistance { public string Id { get; set; } public string Title { get; set; } public List<TagPersistance> Tags { get; set; } // Specify TagPersistance here } [DearRavenDBStoreToSeparateCollectionPlease] // Does not exist public class TagPersistance { public string Id { get; set; } public string Name { get; set; } } } working namespace Articles { public class ArticlePersistance { public string Id { get; set; } public string Title { get; set; } public List<string> Tags { get; set; } // Specify string here } public class TagPersistance { public string Id { get; set; } public string Name { get; set; } } } Storing data broken-but-I-wish-it-would-work Storing ArticlePersistance and TagPersistance into their own collections with one call to StoreAsync. AFAIK this stores the Article and Tags into the same collection. var tag = new TagPersistance() { Name = "Tag1" }; var article = new ArticlePersistance() { Title = "aaa", Tags = new List<TagPersistance> { tag } // Embed the full Tag here }; await session.StoreAsync(article); // Only one call to StoreAsync await session.SaveChangesAsync(); working Storing the Article and Tags separately: var tag = new TagPersistance() { Name = "Tag1" }; await session.StoreAsync(tag); // Store Tag separately var article = new ArticlePersistance() { Title = "aaa", Tags = new List<string> { tag.Id } // Embed only the tag id }; await session.StoreAsync(article); await session.SaveChangesAsync(); Index definition broken-but-I-wish-it-would-work Index on ArticlePersistance which stores the full Tag objects public class Articles_Test : AbstractIndexCreationTask<ArticlePersistance> { public Articles_Test() { Map = articles => from article in articles let tags = article.Tags.Select(t => LoadDocument<TagPersistance>(t)) // Load the related Tags select new { Title = article.Title, Tags = tags // Store the full Tag objects here }; } } working Index which holds only the Tag names, not the full Tag objects: public class Articles_Test : AbstractIndexCreationTask<ArticlePersistance> { public Articles_Test() { Map = articles => from article in articles let tags = article.Tags.Select(t => LoadDocument<TagPersistance>(t)) // Load the related Tags select new { Title = article.Title, Tags = tags.Select(t => t.Name) // Store only the Tag name }; } } Querying the index broken-but-I-wish-it-would-work Finally querying the index and getting the article with the tags back. I hoped for fetching the Article and the Tags in one go here // This does not work var article = await session .Query<ArticlePersistance, Articles_Test>() .Where(a => a.Title == "aaa") .ToListAsync(); working This is working, but cumbersome. You need to care about the relation between Article and Tags which could already be specified in the Index definition. var article = await session .Query<ArticlePersistance, Articles_Test>() .Where(a => a.Title == "aaa") .Include(t => t.Tags) // Include the tags .ToListAsync(); // Query the tags separatelly var tags = await session.LoadAsync<TagPersistance>(article.SelectMany(a => a.Tags)); This is not an answer, but maybe this Query can give you an idea. The RawQuery returns an object that contains full documents. Look at the example in this section: https://ravendb.net/docs/article-page/5.4/csharp/client-api/session/querying/how-to-stream-query-results#stream-related-documents Do I understand the example correctly, that it does not use an index? Which could be really slow... yes, but this dynamic query triggers the creation of an Auto-Index, so you will have an index after all. A simple Auto-index explanation is here: https://demo.ravendb.net/demos/csharp/auto-indexes/auto-map-index1
common-pile/stackexchange_filtered
How to use variable inside for loop I have 50 rows in google spreadsheet. User use these rows as input. But not all 50 rows are shown. When user input number in A2 cell then only that number of the rows are visible. I was able to do the task. But there is one problem inside for loop. I think problem is in this line for(var i = 2; i < fillingRows; i++){ //This is my full code. function onEdit(e) { //Logger.log("Previous value was - " + e.oldValue); //Logger.log("New value is - " + e.value); var range = e.range; var rowNumber = range.getRow(); var columnNumber = range.getColumn(); //Logger.log("Row - " + rowNumber); //Logger.log("Column - " + columnNumber); if (rowNumber == 2 && columnNumber == 1){ //Logger.log(e.value); var fillingRows = e.value + 2; //Hide rows from 3 to 51 var spreadsheet = SpreadsheetApp.getActive(); spreadsheet.getRange('3:51').activate(); spreadsheet.getActiveSheet().hideRows(spreadsheet.getActiveRange().getRow(), spreadsheet.getActiveRange().getNumRows()); Logger.log(fillingRows); for(var i = 2; i < fillingRows; i++){ spreadsheet.getActiveSheet().showRows(i, 1); } } } When I change that line to something like this for(var i = 2; i < 10; i++){ Then it works correctly. But I can't use constant number here. Isn't it possible to use variable inside a for loop. But there is one problem What is the problem? Is there a error? Does it not do what it's supposed to do? See [mre] and [edit] your question. Try this: function onEdit(e) { var sh=e.range.getSheet(); if(sh.getName()!="Your sheet name")return;//Edit this. Add your sheet name if(e.range.rowStart==2 && e.range.columnStart==1 && e.value>=1 && e.value<=50){ //e.source.toast('Value: ' + e.value); sh.hideRows(3,50); sh.showRows(3,e.value); //sh.getRange(1,1).setValue(e.value); } } Thank you very much. I was able to solve it using some techniques used in your answer. It's probably because fillingRows is no greater than 2, and therefore, I suggest printing & checking fillingRows.
common-pile/stackexchange_filtered
Skip instance in conditional callback block (lambda or Proc) I noticed that almost all people use Proc.new instead of lambda (I guess because of how it cares/or not about arity) and also it's common to pass the current instance as an argument. However I checked and it works also without |instance| passed as an arg. See the example below class SomeModel < ActiveRecord::Base has_many :associated_objects before_save :do_something, if: -> { associated_objects.empty? } end According to official guide and most posts found on the Internet it seems that I should write before_save :do_something, if: Proc.new { |instance| instance.associated_objects.empty? } Is there something wrong with my example using -> and no argument? It's similar to skipping the self as the receiver in self.some_method inside model's code and using the implicit receiver. yes, I keep using the short version I shown in my first post You've got it right, the scope of what's evaluated in the Proc or lambda is automatically set to the current instance of the object you're about to save. From the rails docs you can see if you wanted to define your own callbacks you have the option to use a Proc or a lambda with the object in scope. If a proc, lambda, or block is given, its body is evaluated in the context of the current object. It can also optionally accept the current object as an argument. I find it interesting that the Rails Guides recommend passing in the current instance into the Proc when (as you outlined) it is very common place to leave that info out elsewhere when self is implied.
common-pile/stackexchange_filtered
Efficient way to bin data ranges in R I have several hundred variables in a data frame which need to be binned into buckets. Currently, I'm using code similar to the following: idx <- list() idx[[1]] <- which(df$myVariable < 628 & df$myVariable >= 0) idx[[2]] <- which(df$myVariable < 774 & df$myVariable >= 628) idx[[3]] <- which(df$myVariable < 885 & df$myVariable >= 774) idx[[4]] <- which(df$myVariable <= Inf & df$myVariable >= 4819) idx[[5]] <- which(df$myVariable < 0) df$myVariable[idx[[1]]] = 1 df$myVariable[idx[[2]]] = 2 df$myVariable[idx[[3]]] = 3 df$myVariable[idx[[4]]] = 4 df$myVariable[idx[[5]]] = 0 In reality, there are 21 ranges of values for each of the variables, and the cut points may vary between the variables. So, in full, this code is over 30,000 lines long (I have a script which generates it). Is there a better way to represent this code? Ideally it would make use of dplyr, since I intend to run this code in sparklyr, but if that is not possible, native R code is fine (thanks to the spark_apply function). The cut() function is one way to bin the data. dplyr::cut would help simplify some of the code. Though you will have to explain why you need to generate the code using a script. The OP is unclear about how the cut points are calculated for each variable. I looked into the cut function but had two concerns: 1) it converted the data to a factor (really more of an annoyance than a problem since as.numeric can fix that), and 2) the intervals must always be open/closed on the same side. That is, there is no way for it to handle the example given above: (-Inf, 0] -> 0 [0, 628) -> 1 ... [4819, Inf] -> 4 Note the the intervals are not always open/closed on the same side. Amongst the several hundred variables are there likely to be commonalities? I see that you say they are not all the same but are there at least groupings? I would think that a combination of case_when and mutate_at (new version across) might at least be more efficient and be less than 30,000 lines of code. Unfortunately there are not that many groupings. Since the original data is continuous, the ranges are fairly unique for all of them. They all start with 0 as a lower boundary and end with infinity as an upper boundary, but between those two it is very rare for the cut points to be the same. Many of the variables have cut points using decimals, not just integers. @RobertWilson Sorry I forgot to respond to your post. I have a table that has these cut points. They can be changed from time to time as the underlying distribution changes. For my purpose here it doesn't really matter how the underlying cut points are computed, merely how they are applied. The reason a script is used to generate this code is because I'm lazy and don't want to make it by hand for hundreds of variables. (The end code would be the same regardless) @ChuckP, however, maybe something like df <- df %>% mutate(myVar = case_when(myVar >= 0 & myVar < 628 ~ 1, ...)) @ChuckP, your suggestion led me to the correct answer. I've rewritten the code to use mutate and case_when. If you want to create an answer out of your suggestion I'll accept it so you can get credit. I'm good glad I was a little helpful.
common-pile/stackexchange_filtered
How to traverse for duplicates and create mappings in python I have a dictionary with values as below test_dict = {"key" : {"Apple", "Appl", "phone", "case", "APPLE"}} Using fuzzy matching will find whether two strings are equal similar to below. Expected output is to create a map of duplicates in a single group keeping the first comparing duplicate as a key. What is the best way to get to this solution. for k, value in test_dict.items(): for val in values: if fuzzy_score(val[0], val[1]) > 95: final_dict[val[0]].append(val[1]) values.remove(val[1]) # Remove since we already found val[1] is a duplicte of val[1] if fuzzy_score(val[0], val[2]) > 95: final_dict[val[0]].append(val[2]) values.remove(val[2]) # Remove since we already found val[1] is a duplicte of ...... Excepted output: >> print(final_dict) "Apple" : {"Appl", "APPLE"} Do you have a solution that is not the best way? What is the problem with it? I was more stuck with writing the more optimal recursive functions which would work for larger lists does your real data look like test_dict = {"key" : {"Apple", "Appl" ... }}? everything is in single dict key ? Input data is provided by you? Can you change the initial structure? @luvatar, Yes it would be single dictionary for now and the input is provided by me. There is this data structure trie tree. If you normalize words(lower case) it should be perfect for these values. Not sure about performance but it would group data in similar sets
common-pile/stackexchange_filtered
How would white light cavities (WLC) work for gravitational wave detection? A study done by Michael A. Page, Maxim Goryachev, Haixing Miao, and peers states that WLCs can be used to improve the sensitivity of LIGO. LIGO currently uses photons (for very constant speed at which they travel in a vacuum), but if the phononic crystals were integrated into the structure of LIGO itself how would the phonons travel in a vacuum (considering they're mechanical waves). My physics teacher mentioned something about it travelling on the g-wave but refused to elaborate. Link to Study (https://www.nature.com/articles/s42005-021-00526-2) Link to Article (https://theconversation.com/a-tiny-crystal-device-could-boost-gravitational-wave-detectors-to-reveal-the-birth-cries-of-black-holes-155125) Well, the crystal isn't in the interferometer arms and it is still the interferometer that is generating the signal. @GursimranRandhawa the phononic crystal is a thin, mostly transparent sheet suspended transverse to the light beam inside the 30 cm long resonator ("negative dispersion filter cavity") shown at the bottom right of Figure 1 a/b of your linked Page et al. 2021 . It will certainly be vacuum inside that cavity outside of that thin sheet. As ProfRob points out, this cavity is a reflector in the recirculator, off to the side of the interferometer, not in it. I'm not sure if that helps though. A quick skim of your links suggests that the photon-phonon interaction takes place entirely within the thin-sheet phononic crystal. Think of that crystal as an amplifier/filter for all the photons which interact with it.
common-pile/stackexchange_filtered
Why setter methods don't update Object? I want to update the Contact object, which has 2 fields - name & phoneNumber. Unfortunately I don't know why setter methods don't work. Firstly I tried with the #1 version of updateContact() method - code below. I think that it may have something with updating reference of an object, not the object itself? I'm not sure. If anybody could explain me that, why the code with setters doesn't work... - I mean it updates the 'contact' within the function, but doesn't update contact in the ArrayList - contacts. The #2 method works, but I'm not sure if it's a good idea/solution - well, it works... but I think that with setters it should work as well. 1 public void updateContact(String name) { Contact contact = findContact(name); System.out.print("Enter new name: "); contact.setName(scanner.nextLine()); System.out.print("Enter new phone number (9 numbers): "); contact.setPhoneNumber(scanner.nextLine()); } 2 public void updateContact(String name) { Contact contact = findContact(name); String replaceName; String replaceNumber; System.out.print("Enter new name: "); replaceName = scanner.nextLine(); System.out.print("Enter new phone number (9 numbers): "); replaceNumber = scanner.nextLine(); Contact replace = new Contact(replaceName, replaceNumber); contacts.set(contacts.indexOf(contact), replace); } findContact method public Contact findContact(String name) { Contact currentContact = null; for (Contact contact : contacts) { if (contact.getName().equals(name)) { currentContact = new Contact(name, contact.getPhoneNumber()); } } return currentContact; } Thanks for help in advance. You're just creating a new Contact object that's only in scope within the method. It looks like you're shadowing a variable Use currentContact = contact; so that the returned object reference is the one in the list. Everything works, thanks! Your findContact() method is not returning a reference to a Contact object in the ArrayList, instead you are creating a new object with a copy of the data and then returning it. Change it as follows and your first approach should work: public Contact findContact(String name) { Contact currentContact = null; for (Contact contact : contacts) { if (contact.getName().equals(name)) { currentContact = contact; break; } } return currentContact; } Of course, the findContact method was likely explicitly coded to return a copy, so a caller couldn't update the contact without the class knowing about it, e.g. to apply validation constraints, so changing the method to not return a copy is likely with wrong thing to do. Instead, the class should implement a updateContact(String name, String phoneNumber) method. @Andreas I'm not sure that I totally understand. Shouldn't he return a reference to the object in the ArrayList to be able to update it even if he adds the method to the class for validation purposes? or Are you favouring returning a copy then updating it then following his second approach, for example, to update the ArrayList? The purpose of setter methods, instead of public fields, is to allow the class to add logic when a value it set, e.g. for validation or to calculate derived values. The contacts list, and everything in it, is managed by the given class, so to fully (deeply) encapsulate the data, the class should return copies of any mutable objects. E.g. if the class wanted to ensure that names are unique, it cannot allow a caller to change the name of a Contact object directly. ... Or if the class decided to change implementation from List to a Map, keyed by name, then a caller that updated a Contact object would not cause the Map to be updated, breaking the code. --- Of course, you wouldn't have these issues if Contact was immutable, which is why immutable classes are so desired. And you wouldn't care if you trust the caller to not update the object, or if you knew that the class would never need to replace List with Map, but since you can't know the future, defensive programming states to return copies. @Andreas Thanks for your detailed explanation. My knowledge about best programming practices is still quite limited, so I really appreciate it. Complete solution by using different class Name.. Above solutions doesn't Continued old Data.. System.out.println("Enter Id OF student"); String inputId = sc.next(); for(Student std : list ) { if(std.getId().equals(inputId)){ Student newdata = std; System.out.println("Enter New Marks and Phone Number:"); Student update = new Student(newdata.getId(),newdata.getCourse(),sc.nextDouble(),sc.next(),newdata.getEmail()); list.set(list.indexOf(newdata), update); break; } }
common-pile/stackexchange_filtered
R refers to non exisiting files during R CMD check I want to R CMD check with RStudio my package (for this question I call it pkg). But I get the following error message: * preparing 'pkg': * checking DESCRIPTION meta-information ... OK * installing the package to build vignettes * creating vignettes ...Error in find_vignette_product(name, by = "weave", dir = docdir, engine = engine) : Failed to locate the 'weave' output file (by engine 'utils::Sweave') for vignette with name 'my-vignette'. The following files exist in directory 'C:/Users/name/AppData/Local/Temp/RtmpQLnSjE/Rbuild244434d45c05/pkg/vignettes': 'my-vignette.R', 'my-vignette.Rmd' Execution halted Error: Command failed (1) In addition: Warning message: `cleanup` is deprecated Execution halted Exited with status 1. One first thing, where something might got wrong is that there is no folder called RtmpQLnSjE in my C:/Users/name/AppData/Local/Temp/ directory. Running my Rmd file by hand, does not generate any errors. I update RStudio to the latest version 1.1.423 and this is my SessionInfo(): R version 3.4.3 (2017-11-30) Platform: x86_64-w64-mingw32/x64 (64-bit) Running under: Windows >= 8 x64 (build 9200) Matrix products: default locale: [1] LC_COLLATE=German_Germany.1252 LC_CTYPE=German_Germany.1252 LC_MONETARY=German_Germany.1252 [4] LC_NUMERIC=C LC_TIME=German_Germany.1252 attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] MCMCglmm_2.25 ape_5.0 coda_0.19-1 lme4_1.1-15 Rcpp_0.12.15 Matrix_1.2-12 hmi_0.9.4 loaded via a namespace (and not attached): [1] lattice_0.20-35 corpcor_1.6.9 digest_0.6.15 withr_2.1.1 MASS_7.3-48 grid_3.4.3 [7] nlme_3.1-131 cubature_1.3-11 minqa_1.2.4 nloptr_1.0.4 devtools_1.13.4 splines_3.4.3 [13] tools_3.4.3 yaml_2.1.16 parallel_3.4.3 compiler_3.4.3 memoise_1.1.0 tensorA_0.36 The temp directory is probably unlinked upon the crash. Do you have any code inside the vignette that navigates directories or such? Concluding as an answer: Failed to locate the 'weave' output file This error can have several root causes and is not always easy to trace down. However, there is a good chance that it is related to code inside the vignette, in particular code navigating directories and such (e.g. setwd() or other functions that may rely on relative paths that could differ between a stand-alone run and the more involved R CMD check) A supplementary note to the solution of the problem: I sourced some R-files in the vignette. Some of these files moved/were renamed. After changing file-path in the source() command, it worked perfectly. Now, I have the problem again, even after removing all source() commands. Any idea? Hard to say- what have you changed otherwise? From what I could see, e.g. bad vignette names could lead to this problem as well I have one vignette called my-vignette.Rmd Ok, that's fine. Probably have to scan through your modifications to see what might raise any suspicions? I recently ran across this when a vignette file had a space in the name (like "My Vignette.Rmd"). It was creating an html file called My-Vignette.html. I think it's the hyphen in the name that was causing issues (based on the answer above along with what I'm seeing.)
common-pile/stackexchange_filtered
modalSession has been exited prematurely - check for a reentrant call to endModalSession: I am developing a NSDocument based application. We are showing a window as modal window closing the window on a button action.(calling abortModal).This is working properly. But when saved document opens it launches the application with opened document i am getting a this warning and making the window stale when user clicked on the button to close. Please help me understand this. The window isn't shown as a modal window so you can't close it with abortModal. Usually documents aren't modal. You can open multiple documents in multiple windows and switch between them. Don't use NSDocument based application for one modal document.
common-pile/stackexchange_filtered
Ubuntu 12.04 LTS login loop I'm asking this because initially, my problem was a power failure during installation so I typed the following instructions in the maintenance shell: sudo mount -o remount,rw / sudo dpkg --configure a sudo mount -o remount,ro / sudo sync sudo reboot The first three lines worked, afterwards, my computer (a Dell Inspiron 530) got stalled for several hours, so I unplugged it. When I turned it on, the log in screen appeared, and after I try to write my password, it leads me back to the log screen. I must note that when I typed the first three lines during the maintenance shell mode, it said that the errors which were encountered during processing were: initscripts bluez gnome-bluetooth Also, I must add that I've tried other solutions I've found, such as changing the .Xauthority file and when I type that it says: `W: Not using locking for read only lock file /var/lib/dpkg/lock` So, what should I do to get rid of this issue? It's driving me crazy. Also, if it can't be fixed, then what should I do to reinstall Ubuntu without losing my /Home files? I've tried the abovementioned instructions and still it doesn't work. It marks certain problems with bluez and gnome-bluetooth. Above are the screens: first screen second screen Is Ctrl+Alt+F1 what you're looking for? Also, if you can get into the terminal, try running sudo apt-get install ubuntu-desktop. If it claims it's already installed, just remove it and install it again (won't cause any harm). If it sends you back to the login screen, your home directory could not be written to. Is root still mounted as ro? Is your disk full? No, my disk isn't full. Root appears as root@username-Inspiron-530. I presume you meant that the power failure happened during upgrades, not during a new installation. Try the following. Go into recovery mode. mount --options remount,rw / mount --all sudo apt-get --fix-broken install sudo dpkg --configure --pending Reboot, log in and open a terminal. (If you can't log in, reboot to recovery mode with networking, repeating steps 2 and 3 above.) sudo apt-get update sudo apt-get upgrade Let us know if this works. I edited my main entry, adding some screens about the commands you suggested, Paddy. They didn't work out entirely, unfortunately. @Narida I don't see any screens about those commands. Did you try all of the commands, in the correct order? If they didn't work, we need to know exactly what happened. I finally added the screens correctly. Sorry for the mistake OK, @Narida. Did you try the commands that I gave you? What happened when you did? See 'first screen' and 'second screen' at the first post. It didn't react correctly. OK, @Narida. Your second screen shows the prompt (root@adria-Inspiron-530s:~#). That's where you start entering the commands that I gave you. I don't know if they'll work, but please try. I tried it. And now the login screen appears but when I write my passwords it still gets stuck on a loop. It happens the same even with 'Guest Session'. (btw i was unable to reply during these past months due to an illness) Also when I try to register my password it says 'having multiple values in isn't supported and may not work as expected' @Narida, I need to be very clear: Did you run each command, in order? Did every command finish successfully? You might want to repeat the process in case something was left over. I did it. Just after writing sudo apt-get --fix-broken install nothing was upgraded nor installed and it said: Setting up bluez (4.101 0ubuntu13) ... runlevel:/var/run/utmp: No such file or directory. reload: Unknown instance: invoke-rc.d: initscript dbus, action "force-reload" failed. runlevel:/var/run/utmp: No such file or directory. start: Job failed to start. invoke-rc.d: initscript bluetooth, action "Start" failed. dpkg: error processing package bluez (--configure): subprocess installed post-installation script returned error exit status 1 ... `dpkg: error processing package gnome-bluetooth (--configure): dependency problems - leaving unconfigured No apport report written because the error message indicates its a followup error from a previous failure. Errors were encountered while processing: bluez gnome-bluetooth E: Subprocess /usr/bin/dpkg returned an error code (1)` Narida, sorry about your illness; I hope that you are getting better. You have been having this computer problem for a long time. I think that your easiest way forward is to boot with a Live CD, back up all your data onto external storage, reinstall Ubuntu from scratch, and restore your data. I know that this is not what you want to hear, but it's what I would do. I'm sorry that I can't be of more help. So, if I boot through a Live CD, how I'm able to see/retrieve all my files? Also, I was checking similar cases as mine through StackExchange and in one it was suggested to switch to VT (Cntrl+Alt+F1/6), and stop LightDM. I managed to do the first one, and the interesting thing is that it points out that my flaw lies in this: *¨Starting SMB/CIFS File and Active Directory Server [fail] @Narida, when you boot from a Live CD (or Live USB), you will start up in a "temporary" Ubuntu. If you open Files (a.k.a. Nautilus), you will see your hard drives listed on the left-hand side. Simply click whichever one you want in order to view it. You can copy files from there onto an external USB drive. If your home folder is on a separate partition, you can reinstall Ubuntu without overwriting your data; but, as this is susceptible to human error, back your data first anyway. (This all assumes that you had not used encryption in your home folder.)
common-pile/stackexchange_filtered
Spring Boot Selenium - Github Dropdown Cannot Work. How can I fix it? I tried to implement a logout test method through selenium in Spring Boot but I cannot detect dropdown menu located top right hand side. How can I fix it? Here is the test method shown below. @Test @Order(4) public void logout() throws InterruptedException { login(); driver.get("https://github.com"); Thread.sleep(1000); // Header-item position-relative mr-0 d-none d-md-flex WebElement profileDropdown = driver.findElement(By.cssSelector(".Header-item.position-relative.mr-0.d-none.d-md-flex")); // cannot work // dropdown-item dropdown-signout WebElement signOutButton = driver.findElement(By.cssSelector(".dropdown-item.dropdown-signout")); // cannot work profileDropdown.click(); Thread.sleep(1000); signOutButton.click(); } Here is the error part shown below java.net.SocketException: Connection reset org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":".dropdown-item.dropdown-signout"} 1st Edited String xpathProfile = "//*[@aria-label='View profile and more']"; WebElement profileDropdown = driver.findElement(By.xpath(xpathProfile)); String xpathSignOut = "//button[contains(@class,'dropdown-signout')]"; WebElement signOutButton = driver.findElement(By.xpath(xpathSignOut)); I got this issue shown below. org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//button[contains(@class,'dropdown-signout')]"} Here is the answer shown below public void logout() throws InterruptedException { login(); driver.get("https://github.com"); Thread.sleep(1000); // Header-item position-relative mr-0 d-none d-md-flex WebElement profileDropdown = driver.findElement(By.cssSelector(".Header-item.position-relative.mr-0.d-none.d-md-flex")); profileDropdown.click(); Thread.sleep(1000); // dropdown-item dropdown-signout WebElement signOutButton = driver.findElement(By.cssSelector(".dropdown-item.dropdown-signout")); signOutButton.click(); Thread.sleep(2000); } This is a bad practice to try to locate elements like this, you should be more specific. Given this DOM that you are working with I would try using a selector somewhat like this: String xpathProfile = "//*[@aria-label='View profile and more']"; String xpathSignOut = "//button[contains(@class,'dropdown-signout')]"; As you can see it's an xpath type selector and I would recommend learning xpath as it is far more readable once you get used to it and it also works in a few edge cases where you wouldn't be able to use css selector. Also I've noticed that if you make the window size smaller, at some point the profile button you are trying to click is hidden in github, so maybe that is why your button is not getting clicked. You could try setting a specific bigger window size using chromeOptions: ChromeOptions options = new ChromeOptions(); options.addArgument("--window-size=1920,1080"); ChromeDriver driver = new ChromeDriver(options); Can you actually see the button when the test is running? I edited my post. I tried it but I got this error message. What about the screen size? Do you actually see the button when the test is running? I set to maximize the screen through driver.manage().window().maximize(); dropdown-signout cannot be detected. Maybe you would be able to click on the form that contains the button ("//form[contains(@class, 'js-loggout-form')]")?
common-pile/stackexchange_filtered
Write bytes data into a data frame I scraped one site and I get the data in bytes and I do not know how I can write them into a DF in some efficient way. Here is a piece of my data: b'[{"ID":"1","A":"2021-08-04 11:00:00","B":"2021-08-05 10:52:30","C":"","D":"2021-08-05 10:51:00","E":"","F":"Mark","G":"","H":"BOSTON"}]' Your problem is not how to transform bytes into a df, but how to transform bytes into a data structure that is "friendly" to df. "eval" will try to transform the string/bytes into a data structure; in this case: a list of dictionaries pd.DataFrame(eval(a), columns=eval(a)[0].keys()) note: if the bytes are valid jsons, its more efficient to use "json.loads" instead of "eval" OP's bytes are valid JSON, so I recomment replacing eval with json.loads. good point timgeb.
common-pile/stackexchange_filtered
recursively combining elements across several arrays of integers in Python The problem: given an arbitrary number of arrays of positive integers, find all combinations of their elements, one from each array, such that the numbers' set bits do not overlap (A & B == 0 for every two elements A and B of a resulting combination): [[1, 2, 4], [8, 16]] => [[1, 8], [1, 16], [2, 8], [2, 16], [4, 8], [4, 16]] [[55, 49, 5, 61], [8, 97], [70, 20, 50]] => [[49, 8, 70], [5, 8, 50]] [[180, 44], [9, 182], [115, 110]] => [] So far I've managed to come up with this code: from itertools import chain def find_combos(sets, combo=[], used_bits=0): set_idx = len(combo) if set_idx == len(sets): return [ combo ] to_try = filter(lambda n: not n & used_bits, sets[set_idx]) # return [ c for n in to_try for c in find_combos(sets, combo+[n], used_bits|n) ] return list(chain.from_iterable(find_combos(sets, combo+[n], used_bits|n) for n in to_try)) Only, I don't particularly like the look of it, what with all the constant unwrapping and rewrapping. I feel like there must be a more elegant/efficient solution, a clever itertools trick maybe. Anyone? what does "such that their set bits do not overlap" mean? Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. A & B == 0 means that the intersection is empty? @cards Sorry, I've reworded the question. The & is bitwise.
common-pile/stackexchange_filtered
How to handle user functions with unkown number of arguments for performance measurements? I am trying to write a performance test that can run functions with different number of arguments. Something like this: // optimization.cpp struc Command{ unkown_type fun; } command1; perf_test(Command exec){ unkown_type ptr = exec.fun // start timer ptr(); // stop timer } // main.cpp user_function1(double x[], double y[]); user_function2(double x[], double y[], int z, double A[]); // somehow bind function command1.exec = user_function1 perf_test(command1); Is there somehow a way of doing this and getting good results e.g. function inlining and so on or is this simply not possible? I know about std::function and std::bind but unfortunately std::function has a large overhead which makes no sense for my performance measurements. How will you be passing arguments to the function wrapped in your hypothetical perf_test? Until I now we did not have a variable number of arguments, simply passed them along with the Command struct and then called the function with them like this command1.exec(exec.A, exec.B); First I was thinking that we could use a function without arguments and then somehow bind them or use lambdas but I cannot get my head around it. You are making this more complicated than it needs to be. template <class Function, class ...Args> auto perf_test(Function &&f, Args && ...args) { // start timer std::forward<Function>(f)(std::forward<Args>(args) ...); // stop timer //print or return or store time } To be used like auto passed_time = perf_test(user_function1, somex, somey); If you really must have your Command struct you can store the args in a std::tuple and then use std::apply to call the function. If you put the time measuring code around the function and then assign it to an std::function you can use the convenience of std::function without its overhead influencing your measurement. This can look something like template <class Function, class... Args> std::function<std::chrono::nanoseconds()> make_perf_test(Function &&f, Args &&... args) { return [f = std::forward<Function>(f), args = std::make_tuple(std::forward<Args>(args)...)]() mutable { const auto start = std::chrono::high_resolution_clock::now(); std::apply(std::forward<decltype(f)>(f), std::move(args)); return std::chrono::high_resolution_clock::now() - start; }; } to be used like auto uf1 = make_perf_test(user_function1, x, y); std::cout << "user_function1 took " << uf1().count() << "ns\n"; This gives you an easy to store type std::function<std::chrono::nanoseconds()> that type-erases the parameters and arguments away while not including that overhead in the measurement. There is are some tweaking spot. Maybe the lambda should not be mutable so that the arguments cannot change so that you can repeat the measurement. Also due to limitations of std::function, this requires that the function and parameters are copyable. I thought vardict arguments would change the performance measurements? I Will definitely try it. Surely templates are compile time? i.e. no runtime performance. Maybe I'm wrong That is exactly what I need as I have two unknown and one known function in my performance test. The unknowns are called inside the known. I updated my question with what I have so far. Can you clarify how to put the time measuring code around the desired function before wrapping it into a std::function, so that I can close the question? Thank you so much You can use a variadic template for this. template<typename F, typename... Args> void invoke_func(F func, Args&&... args) { func(std::forward<Args>(args)...); } You can then call that directly within your performance measuring code.
common-pile/stackexchange_filtered
Confusion regarding DNS query vs HOSTS file With the subject, I have windows/linux machine and In which installed virtualbox and setup <IP_ADDRESS> ip and entry www.abc.com in hosts file. We have setup DNS server/filter on network and setup DNS on every machine. Now problem is that, Why DNS query to DNS server of www.abc.com,because which already resolved using hosts file. What order of HOSTS file and DNS server ? Does the query occur only when navigating from the VM, or also from the host? @user2313067 Query from hosts Q. Why DNS query to DNS server of www.abc.com,because which already resolved using hosts file. A. Your computer should use the hosts file first and not do a lookup. Just like how you seem to want it do be doing. This saves bandwidth and useless queries etc... Testing: If you pick a new ip address (or flush the dns cache) and test it you should see. Here is an example that mixes up Free Software Foundation and Google's addresses. We can get the ip for www.fsf.org: nslookup fsf.org Gives the answer: server:<IP_ADDRESS> nslookup <IP_ADDRESS> name = google-public-dns-a.google.com 1) Put the incorrect record in the hosts file. <IP_ADDRESS> www.fsf.org in the hosts file ( /etc/hosts possibly). This is google's ip address, for the free software foundation.org name. 2) restart the computer or the networking service. 3) ping www.fsf.org You should see that your computer pings <IP_ADDRESS>, which is google. If it pinged <IP_ADDRESS>, you would know it was using dns. I just did the test on my computer. Of course the point of dns is that it is scalable so that you don't have to write that down anymore and it gets updated automatically, but you may find the hosts file useful for internal network use or as shorthand external addresses. Cheers. Checked, Hosts entry correct and If i try to nslookup then get " Server: UnKnown Address: <IP_ADDRESS> Name: www.abc.com.corp.domain.com Addresses: <IP_ADDRESS> <IP_ADDRESS> why? Can you see what your dns address is and if you can ping it? yes and <IP_ADDRESS> my DNS server and setup only this in system for internet, It's working fine CAn you check the the computer hostname is a fully qulified domain name: computer.corpdomain.com? (not just "computer"). What do you get from nslookup <IP_ADDRESS>? Can you make a new hosts entry and ping the name? Something new. The hosts file should work regardless of dns or not. Now system in domain but win server not connected 2) nslookup response UnKnown can't find ip(nxfilter). 3) problem is not a domain name resolve etc. but why www.abc.com(<IP_ADDRESS>) is try to resolve on nxfilter(<IP_ADDRESS>)? on system, www.abc.com is working fine !! Just to be clear, is abc.com an external ip address or internal? I was assuming it was external. Your hosts file should work fine with or without dns. Have you tried to ping the entry in the hosts file? nslookup and dig will always ask the dns server because they are dns tools. Let us continue this discussion in chat.
common-pile/stackexchange_filtered
How to complete this Jquery string I'm looking to use this piece of Jquery to open a lightbox gallery on page load IF the class .w-condition-invisible is appended to the #script-test div. This is what I've come up with but upon testing in the console it's not working... Any ideas? $( "#script-test" ).hasClass( "w-condition-invisible" ){ $('.w-lightbox').first().trigger('tap'); }); if($( "#script-test" ).hasClass( "w-condition-invisible" )){$('.w-lightbox').first().trigger('tap');} As @Satpal suggested, you need to use conditional statement Create a class to show Popup and when remove popup will hide using this You can open lightbox(popup) $(document).ready(function(){ $( "#script-test" ).addClass("showpopup"); }); According to your question, what i understood is in the below code, please have a look: $(window).load(function() { if($( "#script-test" ).hasClass( "w-condition-invisible" )){ $('.w-lightbox').first().trigger('tap'); } }); Please have a look on this. Hope, this may be helpful to you. Please have a look on this, this much i am able to get from your question, if this does not work, please provide your html code also, where you to do click event, then only i could be able to help in a much better way. Check by length $(window).load(function() { if($( ".w-condition-invisible" ).length){ $('.w-lightbox').first().trigger('tap'); } });
common-pile/stackexchange_filtered
Numpy value assignment by indexing or slicing, duplicate memory allocation? import numpy as np a = np.array([0.,0.,0.,0.]) b = a c = a d = a.copy() a[0] = 2. print(a) print(b) print(c) print(d) The result is [2. 0. 0. 0.] for ALL a,b and c, which is very weird. d still correctly retains the values as zeros though. Is it an intended behavior? Yes it is an intended behaviour as all of a, b and c share memory and can be easily verified by simply checking a is b etc. Why is it weird? That's normal Python behavior. b is a as is c. They all reference the same array object. d is a copy, the others are not. It is intended behavior, a, b, c all point to the same underlying array's memory location, while d points to a new copy of a when it looked like np.array([0.,0.,0.,0.]) since you numpy.ndarray.copy. thank you, could you post as an answer so I could accept it? @hpaulj Not having a rich Python experience, and coming from MATLAB, it looks totally weird to me... My MATLAB experience is old (though occasionally I'll fireup an Octave session). Yes assignment there does make a copy. Python on the other hand is object-oriented from the ground up, so variables are just names used to reference objects. Copying has to be explicitly done. Yes it is an intended behaviour as all of a, b and c are essentially the same python object in memory and can be easily verified by simply checking a is b etc. Only d is assigned a separate copy of a in memory. >>> import numpy as np >>> a = np.array([0.,0.,0.,0.]) >>> b = a >>> c = a >>> d = a.copy() >>> a is b True >>> b is c True >>> c is a True >>> a is d False It's more than share memory. They are the same Python object. Sharing memory is a better description of a numpy view. That's a new array object, but with a shared data buffer (the underlying 1d c array where values are stored).
common-pile/stackexchange_filtered
How do I prove I can integrate over a triangle with two different parametrizations? This seems like a simple thing that has been eluding me. Consider the two integrals: $I_1 = \int_t^{t'} ds \int_s^{t'} ds' \; g(s',s)$ and $I_2 = \int_t^{t'} ds' \int_t^{s'} ds \; g(s',s)$ where g(s',s) is any function of the variables. It seems to me that the two integrals should be the same, as I'm running over the same triangle in the $(s,s')$ space, but I cannot find the appropriate change of variables to prove it. Is that true? What is the change of variables? We can use the following trick: define $$G(s', s) = \begin{cases} g(s', s) & (s', s) \in D \\ 0 & \text{otherwise}, \end{cases}$$ where $D$ is the triangular region that we want to integrate over. Thus $I_1 = \int_t^{t'} ds \int_t^{t'} ds' \; G(s',s).$ Similarly, $I_2 = \int_t^{t'} ds' \int_t^{t'} ds \; G(s',s).$ Now, Fubini's theorem says that these two integrals are equal. Source: http://ksuweb.kennesaw.edu/~plaval/math2203/doubleintgen.pdf I'm not sure, because in this case the limit of integration for the inner integral depends on the variable of the outer integral, so they cannot be simply exchanged Oh, I see, oops. You're right. I just found an actual solution online, hope this helps! Of course, this is conceptually the same as Fubini's theorem, i.e. that the two-dimensional integral over a region $D$ is independent of which direction you slice it (so long as the boundary curves are graphs over the axis perpendicular to the slice direction). The usual way of reducing this "stronger" notion of Fubini to the classical, rectangular definition is to introduce an indicator function $$\chi(s,s') = \begin{cases}1, & s \geq t, s' \leq t', s'-s \geq 0, \\0, & \mathrm{otherwise},\end{cases}$$ so that \begin{align*} I_1 &= \int_t^{t'} ds \int_s^{t'} ds' \; g(s',s)\\ &= \int_t^{t'} ds \int_s^{t'} ds' \; g(s',s) \chi(s,s')\\ &= \int_t^{t'} ds \int_t^{t'} ds' \; g(s',s) \chi(s,s')\\ &= \int_t^{t'} ds' \int_t^{t'} ds \; g(s',s) \chi(s,s')\\ &= \int_t^{t'} ds' \int_t^{s'} ds \; g(s',s) \chi(s,s')\\ &= \int_t^{t'} ds' \int_t^{s'} ds \; g(s',s) = I_2. \end{align*} The nontrivial steps here are Fubini's theorem (in the middle step) and the insertion and removal of $\chi$, which requires carefully checking that for all points in the domain of integration, $\chi(s,s') = 1$. To be fully rigorous you'd also need to prove that $g\chi$ is integrable.
common-pile/stackexchange_filtered
why i cannot make hole on the mesh? why i cannot make hole on the mesh?. I have check both mesh rotation scale, Face pointing outside. No double verts seen. I want to make a cylinder hole but it creates a square hole. Any suggestion or help whats going wrong with my mesh. Thanks I believe it's because of N-gon topoology. It's a bug in Boolean modifier I think, but still. I see 4 solutions: Retopo your mesh so it contains only quads. You can use Fast method of Boolean modifier. There's still an issue but less noticable: Add a circle instead of a cylinder and use a Shrinkwrap modifier. You'll get a nice cut: Use add-ons like BoxCutter. As I know, it deals with N-gons nicely. But the add-on is expensive :(
common-pile/stackexchange_filtered
What is the use of the interrupt flag IRQF_TRIGGER_NONE? can anyone explain the flag, IRQF_TRIGGER_NONE declared linux in the file,/kernel/linux/include/interrupt.h. How can one use this flag? IRQF_TRIGGER_NONE is defined with a bit-mask of 0 indicating that it does NOT imply any kind of edge or level triggered interrupt behaviour. #define IRQF_TRIGGER_NONE 0x00000000 Hence registering an ISR using request_irq() with IRQF_TRIGGER_NONE does NOT modify the existing configuration of the IRQ. This is important in scenarios where we would simply like to register an ISR for an hardware in the mode it is currently configured [1]. Example usage of IRQF_TRIGGER_NONE in the Linux Kernel. If the flag is used to configure the ISR for its current mode, how to know the current configured mode,? @Mike The IRQF_TRIGGER_NONE flag is a quick way to simply continue using the interrupt simply like it has already been setup(in boot-loader, or earlier in kernel) and register an ISR for it. Identifying the currently configured mode is usually done by reading the appropriate registers on the device in question.
common-pile/stackexchange_filtered
What is a 50-ohm antenna? How would you make one? This is an intentionally very open ended question. What does it mean for an antenna to be a 50-ohm antenna at some frequency? How do you make a 50-ohm antenna for say 433.92MHz? What are the options? What are the consequences of it being different from 50-ohms? Trying to think what 433 is used for off the top of my head :) Is that the weak signals band? At any rate, most 2-way radios are made to match up to a 50ohm antenna and the matching is left up to you. You can get an antenna that is already tuned, or you can do impedence matching through a number of techniques (see the referenced article below). With a good match, you reduce standing waves. Standing waves build up when the radio sends out a nicely modulated signal but the antenna isn't resonating at that frequency and causes standing waves, which feed right back into the radio and can blow out the final stage. The higher the output power, the more this becomes important. At very low power, say <1watt, the worst you have to worry about is the antenna not resonating and your signal not going anywhere. At higher powers, say 50+ watts, you can damage your transmitter in less than 1 second. Modern radios have built-in SWR detectors that will cut the power if it detects a problem. Those aren't always guaranteed to work though. This page lays out a few key things verey nicely Unless this is a shared frequency band (such as ISM), I'm pretty sure this lies within a Ham band. In which case you have to take the test to transmit in the band. The test covers these questions. KC2QLW ;) 433.92Mhz is actually the center frequency of an ISM band, not part of the Ham spectrum, and is goverend by Part 18 of the FCC rules. It's part of the UK 70 cms amateur band allocation. People have been unable to get into their cars after parking them close to a 70 cms amateur radio transmitter. @vicatcu - (I appreciate this is an old thread, but your comment needs comment...) whilst 433.92Mhz is an ISM frequency, it is also a 70cm amateur frequency world wide. Use of the frequency for ISM is subject to not causing interference to hams, but you may suffer from hams using it! See also Leons comment! @Andrew sure, but you don't need a license to transmit on it (in most countries) was my main point. Thanks for the clarification though. @vicatcu - agreed, subject to very strict criteria (eg in the EU its a max 100mW on 433MHz) What does it mean for an antenna to be a 50-ohm antenna at some frequency? It means that if you apply 1 VRMS sine wave of that frequency at the end of the antenna, a 1/50 ARMS current will flow in the antenna at that point. V = IR Exactly. This can be generalized to the statement that the ratio of RMS voltage to current at any point on the antenna is 50, and the unit is, of course, ohms. So how do you build one for a target impedence? What's the design process? Also presumably imperfections come into play and you have to "tune" the circuit to the antenna (something like that), is there a clear approach to doing that? Radio amateurs use VSWR meters to check and tune antennas. The antenna's impedance should match the connector's impedance should match the line's impedance should match the transmitter's impedance. Then there's no reflections. If you don't use some kind of antenna tuner (L-C network, usually,) it is almost always required to do some cut-and-try trimming. There are all sorts of rule-of-thumb equations out there, but the best advice is to cut your (I'm assuming prototype) antenna a bit too long and test it with a meter that can measure forward and reflected power. Trim, then test again. You want to trim for minimum reflected power, which will mean that your power is being radiated instead of reflected back into the amplifier finals and heating them up. When referring to RF equipment you have to deal with 'characteristic impedance', which is a property of antennas, feed lines, and even transmitter output stages. The important thing is to make sure that impedances are matched up all the way from the equipment to the antenna. This is more important for transmitters, since more power is involved, but doesn't hurt for receivers either. One thing you don't want to do is just wire together two items with different impedances. There are RF transformers of various kinds can be used to match up sections that otherwise would be mismatched. Any abrupt change in impedance causes RF energy encountering the mismatch to partially reflect, sort of like what happens when light strikes a piece of glass. When one end of the system is a 100W transmitter, this can result in significant energy being reflected back to the tranmitter's output stage. Basically, it's just inefficient, since the reflected energy just becomes waste heat in the transmitter, and the output from the antenna is diminished. The measure of how much reflection is going on is referred to as the standing wave ratio, often abbreviated SWR. Not all RF systems are 50 ohms. There are kinds of coax (e.g. RG-59) that are 75 ohms, and 300 ohm twin lead that are not uncommon. A great tutorial: The Dropout’s Guide to PCB Trace Antenna Design It's also useful to understand why a 50-ohm antenna is so important. Let's say you have a source with an output impedance (resistance) of 50 ohms, like the ideal battery/resistor combination in the following diagram: If you want to extract maximum power from the above source, the load resistor you need has to be 50 ohms. Try it yourself - put in 40, 50, and 60 ohms, and calculate how much power goes to the load in each case. So, this is the reason why 50 ohm antennas are important: The sources that drive them typically have 50 ohms of impedance. Therefore, if you want to deliver the most RF power from your 50-ohm source to your antenna - voila, only a 50 ohm antenna will do that! Back to basics is good! I've never been able to think of a good explanation when the application is a receiver. Do you know of any explanations that start with a wave incident on an antenna, and still work? I've never seen it done. One reasonable speculation is that 50 Ohm impedance was a good compromise between power handling and low loss for air-dielectric coaxial feed line. Oh! microwaves101! I was looking for this site a while ago, and could not remember what it was called. I'd read some interesting things about skin depth at 60Hz a while ago while riding a bus, and later could not remember what or where. Excellent, thanks! A 1/4 wave antenna with four 1/4 wave radials at 45 degrees will give something close to 50 ohms impedance. This is very useful. I am not an electrical engineer, and therefore would am very interested in heuristics like this. Please add more if you know of any. It's not really a heuristic, it can be predicted from basic electromagnetic theory. Something similar is the impedance of a folded half-wave dipole - 300 ohms. Another example is the 30 ohms impedance of a 1/4 wave vertical over a ground plane. A microstrip line with standard FR4 PCB material will be about 0.1" wide. A dipole with bent/drop legs can easily be made to 50 ohms. This should be the selected answer as it is the only one that actually answers the OPs question. Antenna geometry is the key. Here's a good app note for making a Bluetooth PCB antenna (2.4Ghz) http://www.national.com/appinfo/cp3000/files/SBK/Bluetooth_Antenna_Design.pdf 50 Ohm is input impedance of feedline to the antenna. In general practice, we connect an antenna with 50 Ohm connector ( like SMA, Coax...) so feedline impedance should be also 50 Ohm. For Bluetooth antenna design at 2.4 GHz, you can also refer https://anilkrpandey.wordpress.com/2017/01/19/inverted-f-bluetooth-antenna-design-for-smart-phone/
common-pile/stackexchange_filtered
in twitter api I want to know the number of tweets that match specific query the problem is they limit the result they return to 1,500. but I only want to know how many results there are, not to get all of them There is no way to know this without using the Streaming API to track the keywords you want an maintaining your own count. The Search API only contains data for about the last 7-14 days depending on tweet volume so even if you did paginate through all available tweets you would only have a recent count. This answer still holds true 10 years later. You can use the Twitter Count API: http://urls.api.twitter.com/1/urls/count.json?url=www.apple.com&callback=twttr.receiveCount Response: twttr.receiveCount({"count":2596822,"url":"http://www.apple.com/"}) Note: this is not officially support by Twitter, so use at your own risk. There's a pretty easy tutorial on grabbing Tweet counts why you can do using JSON and the TweetMeme API. $.getJSON('http://api.tweetmeme.com/url_info.jsonc?url='+url+'&amp;callback=?', function(data) { $('#twitter').append(beforecounter + data.story.url_count + aftercounter); }); where the url variable corresponds to the url in the query you are matching.
common-pile/stackexchange_filtered
Casting to unsigned char in C I am facing a following problem: When trying to do cast to an unsigned char I get unexpected values. The code that I am using: unsigned char MyVal1 = ((0xF1E3 && 0xff00) >> 8); unsigned char MyVal2 = (unsigned char)((0xF1E3 && 0xff00) >> 8); unsigned char MyVal3 = (unsigned char)((0xF1E3 && 0xff)); I am storing all three variables in an array. The output I am getting (looking at the values in array; array is unsigned char array): 0x00 0x00 0x01 while I was expecting: 0xF1 0xF1 0xE3 Could someone be kind to help me out in what am I doing wrong? Operators && and & do not work the same on integers. Your operands are first converted to bool (zero/nonzero) and then anded together. Checkmate.... It has been a long day and I totally forgot that I was not using bitwise operator.... Much appreciated..... && is the boolean and operator; it gives 1 if both its operands are non-zero and 0 otherwise. You want the bitwise and operator, &, which gives 1 or 0 in each bit of its operands.
common-pile/stackexchange_filtered
custom object with button linking back to view controller I have view controller and a custom object that will return a view with buttons. I to set the button's target to a method on the view controller. I just want this object to create the view i want and then return it for me to addSubview:. CreateView.m //create button [button addTarget:(view controller) action:@selector(buttonMethod) forControlEvents:UIControlEventTouchUpInside]; How can i do this? Pass the view controller's self to the method? so CreateView is basically a factory responsible for creating views? then yes, pass the pointer to the viewController to the method. e.g. @interface CreateView : NSObject { } + (UIView*)createViewFor:(id)target; @end Yes, it would just be a factory. I don't see any clear advantage in the view class with delegates over doing it this way. Thank you. Please Try this. It may help you for solve this issue. [button addTarget:self action:@selector(buttonMethod:) forControlEvents:UIControlEventTouchUpInside]; -(void)buttonMethod:(id)sender { CreateView *c=[CreateView alloc]initWithNibName:@"CreateView" bundle:nil]; [self.view addSubview:c.view]; } he didn't ask how to get the action to the button and then add it to CreateView: CreateView isnt even a view, it is a factory producing views :)
common-pile/stackexchange_filtered
Remove an already-registered $state I was surprised to learn that ui-router shares state across modules. That's ok, but for our development environment I'd like to clear all the application states and start from scratch. It's not convenient to avoid defining them in the first case just for our test environment, because the state definition is mixed in with all the other application loading, and we'd like to be sure that the application dependencies are describe the same way in all environments. So can I clear, or remove one-by-one, the already defined states? .config( function($stateProvider) { // TODO: get rid of $state definitions from the app, we don't want them here } Found this. "on roadmap": https://github.com/angular-ui/ui-router/issues/1095 I think you can overwrite states. So you could replace the state with a URL that will never be matched. @ThinkingMedia the problem is there isn't a good way to remove it from the $urlRouterProvider. If there was I think this would already be a feature as it's been requested many times. possibly looking at this backwards... perhaps you want to look at conditional configurations depending on environment This is not possible. ui-router uses ng-router and ng-router does not expose the routes until after the provider is compiled. Meaning you wouldn't be able to remove states/routes until the app is configured. Which I don't think they will accept a PR. Edit: In response to the comment made. The routes objects used by the $routerProvider is available and you can remove routes. https://github.com/angular/angular.js/blob/master/src/ngRoute/route.js#L451 delete $route.routes['/']; But the states object used by the $stateProvider is not available. https://github.com/angular-ui/ui-router/blob/a7d25c6/src/state.js So ui-router would need to be modified to be able to remove states after config. OR ng-router would need to be modified to be able to remove routes during config. Can I remove them after the app is configured? You are able to remove routes but without a modified version of ui-router you cannot access the states object to remove that. That needs to be provided to the $state injectable. Yeah... It's the states from $state.get() I want to get rid of. Oh well, good to know it needs a fork to get done. Thanks Micah! With angular-ui-router starting from Version 1.0.0 (currently in rc1 version) it is now possible to properly remove states. Inject $stateRegistry (runtime) or $stateRegistryProvider (config) and call the deregister() method. Here the detailed API, implemented with this commit
common-pile/stackexchange_filtered
Use" INSERT ... ON DUPLICATE KEY UPDATE" to insert multiple records My Table structure table: marks My objective: i want to insert or update multiple records with the condition i am currently check by this query 1st step SELECT * FROM `marks` WHERE `student` =115 AND `param` =1 2nd step if records found by matching above criteria i just update record by my new values else insert new record into my table It gonna working fine . but i want to reduce code and optimize this into single query . its possible or not ? I found this on MySQL docs INSERT ... ON DUPLICATE KEY UPDATE . if this is a solution . how can i achieve by query ? Note: i am using the Yii framework . suggestion from Yii also welcome Edited: This query does't not update the rows . but escape from insert working correctly INSERT INTO marks(`student`,`param,mark`,`created`,`lastmodified`,`status`) VALUES (11,30,10,'00-00-00 00:00:00','00-00-00 00:00:00','U') ON DUPLICATE KEY UPDATE `mark`=VALUES(`mark`) First step: create a unique index on (student, param), then just try to insert like you would , ON DUPLICATE KEY UPDATE SET mark=VALUES(mark) @Wrikken how to set the two column combination as a unique . because different students have same param's . both student and param combination only unique . i not to familiar with indexing . plese need more info . thanks @Wrikken i edit my question . please review it . it does not update the existing record . but its skip the duplicate entry correctly. i add the unique index for the fields student and param . ALTER TABLE marks ADD UNIQUE (student, param);, and then INSERT INTO marks (student, param, mark, created) VALUES (11,20,10,NOW()) ON DUPLICATE KEY UPDATE SET mark=VALUES(mark); should work. @Wrikken this problem solved . thank for your comment. its useful to others Check this article Yii INSERT ... ON DUPLICATE UPDATE. They suggest you don't use this feature. But i want it to use, so I extended from CDbCommand my own component and add method for ON DUPLICATE KEY UPDATE: public function insertDuplicate($table, $columns, $duplicates) { $params=array(); $names=array(); $placeholders=array(); foreach($columns as $name=>$value) { $names[]=$this->getConnection()->quoteColumnName($name); if($value instanceof CDbExpression) { $placeholders[] = $value->expression; foreach($value->params as $n => $v) $params[$n] = $v; } else { $placeholders[] = ':' . $name; $params[':' . $name] = $value; } } $d = array(); foreach($duplicates as $duplicate) { $d[] = '`' . $duplicate . '` = VALUES(`'.$duplicate.'`)'; } $sql='INSERT INTO ' . $this->getConnection()->quoteTableName($table) . ' (' . implode(', ',$names) . ') VALUES (' . implode(', ', $placeholders) . ') ON DUPLICATE KEY UPDATE ' . implode(', ', $d); return $this->setText($sql)->execute($params); } Usage example: Yii::app()->db->createCommand()->insertDuplicate('user', [ 'id' => $this->id, 'token' => $token, 'updated' => date("Y-m-d H:i:s"), ], ['token', 'updated']); This command will create user with this parameters or update token and updated fields if record exists. can you please give the example parameter for this function . $table, $columns, $duplicates how to pass these values @RyanBabu sure, i added some example before this any fields indexing needed? please review my question on edited section . that query does not worked . Where i did mistake i can't understand my problem here . your code is useful i know . i just run that sql alone . its not update the existing value . Thanks for your example. nice to implement INSERT INTO marks(student,param,mark, created,lastmodified, status) there is a error: param,mark it must by 'param', 'mark' I tried again alex but not get updated only 0rows affected . i updated my question I find out my problem @alex thanks for your answer now i use your function . i am not update the other values .**param=values(param), student=values(student) ** This is no need here . both values are same . now its working Do not implement "INSERT ... ON DUPLICATE" in your programming as it is MySQL specific. When you migrate from MySQL to other Database your program cannot communicate with new Database as per the concept of Database Abstraction try like this function actionName() { $id=$_POST['marks']['id']; //Pick the ID from your form values $model = Marks::model()->findByPk($id); //Check the records in the Marks table if (!$model) //If not found create a new Model for insertion. If records are there it will update the model $model = new Marks(); $model->attributes = $_POST['marks']; //Assign the form values to attributes $model->save(); } did you read his question? he said that he want do that in one query thanks for your advice . my application does not need the DB change feature . i am also using this type of process. i want to change this into sql because of DB hit rate . The insertion rate is very high . This process look like slow for me .i need optimization.
common-pile/stackexchange_filtered
Rails minitest required library leading to uninitialized constant In running a test, the follwoing error is emerging: CartitemsControllerTest#test_update_q_on_last_item: ActionView::Template::Error: uninitialized constant Barby::DataMatrix In practice this error does not arise and the desired barcodes are being generated according to design. While this is running within the CartitemsController, the action calls up a partial that is part of class Cart. Moving the test to CartsControllerTest does not alter the error. It remains apparent though that the required libraries need to be loaded require 'barby/outputter/png_outputter' require 'barby/barcode/ean_13' require 'barby/barcode/data_matrix' How can Minitest be hooked up to the libraries required? Include the relevant require statements before class ActiveSupport::TestCase in test/test_helper.rb
common-pile/stackexchange_filtered
Deploying New Relic on Heroku Cedar (PHP) Has anyone succesfully deployed the New Relic addon to a PHP app running on Heroku Cedar stack? I'm running a fairly high traffic Facebook app on a few dynos and can't get it to work. The best info I can find details a Python deployment: http://newrelic.com/docs/python/python-agent-and-heroku Thanks! Contacted the relevant support channels yet? http://devcenter.heroku.com/categories/support and http://newrelic.com/support Yes, their response just pointed me to the New Relic PHP documentation, nothing specific to Heroku. I've succesfully used New Relic for traditional PHP applications but just can't find anything on Heroku. http://newrelic.com/docs/php/new-relic-for-php Heroku has just recently rolled out support for PHP with Cedar and we at New Relic don't know anything more than you do. We'll be talking with Heroku ASAP to get some docs developed which will certainly be on (New Relic's knowledge base), and I'll report back here as well. Edited to add: Sorry for the long delay in me checking back in. Unfortunately this is still not possible in a well-supported way, reason being that our php agent requires a standalone daemon to be running in addition to the dyno that is serving your content. While you can find terrible hacks to get you into the space where you could fire up the daemon temporarily, it's not sustainable and won't port to the next dyno that spins up. This means that we can't support you running the agent in this environment. Edited to add: As @aaron-heusser mentioned, support is finally official as of a month or so ago: https://github.com/heroku/heroku-buildpack-php Note: I work at New Relic. I'm very interested in this as well. +1. The Cedar stack is now very well supported and documented by Heroku. Looks like it might be possible with a "Custom Build Pack" http://blog.iphoting.com/blog/2012/05/24/running-php-on-heroku/ +1 I'd like to see this supported, ideally automatically through the Heroku Addon, and not needing a custom build pack. @fool - Is this still accurate, in Nov '13? I'd like to use the New Relic platform for monitoring PHP on Heroku if possible to do in a clean way. As of September 2014, New Relic PHP does support running on Heroku using the official Heroku PHP buildpack. See: New Relic documentation Heroku documentation
common-pile/stackexchange_filtered
Splash screen react-native Is there any repo or something that can be used to change the splash screen image automatically without doing a release? For example 1 week I want to display image X and after that I wanna do Y, but Y its also not on the phone so I have to download it from an api and so on. Possible duplicate of iOS Launch screen in React Native not a duplicate, i want to change it when its already installed on a phone, locally I know how to do that. Change your launch screen image to a uri with a fixed name, then you can replace the image when you need. EX: <Image style={{width: 50, height: 50}} source={{uri: 'url to your image'}} /> Remove launch screen from main UIViewController and in index.js get an Image component to render for some ms time(maybe setTimeout might help) and setState to render your app thereon. You can do that by yourself easily. Just write your api and once a week make your app check that endpoint while opening the app. Save the image to the disk of the device then serve your image on the splash screen from the memory of the device. If you do not want to write your own api, keep some state and persist it. Again once a week check the api you want if there are any new images, if yes download them to your device then serve them. This is a broad answer for a broad question, but you can achieve what you want with a little bit react(native) and js. The api and getting the images its not the problem, but how do you override the launch image? You can check react-native-fs in order to read/write from the file system where you can store your launch image. You can use existing npm packages to make splash screens. like react-native-splash-screen using setTimeout method componentDidMount() { setTimeout(function(){ // place your navigator code here }, 1000); // update your own time interval value } Hope this will help you :) Happy coding!
common-pile/stackexchange_filtered
Springboot 3 Factory method 'dataSource' threw exception with message: Failed to determine a suitable driver class I have a springboot 3 application, pretty standard, which has a Controller, a service that is called by the controller and a repository that the service uses to fetch and save data. I had configured my application to work with a postgresql DB, and it was actually working quite well. Then I decided to do some refactoring (originally, all logic was in the controller, I introduced the service mentioned above and moved it there). I didn't change anything to the Application launcher, the application.properties or anything else. Now when I try to start I get the following error: APPLICATION FAILED TO START Description: Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured. Reason: Failed to determine a suitable driver class Action: Consider the following: If you want an embedded database (H2, HSQL or Derby), please put it on the classpath. If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active). While the actual runtimeException where my debug point occurs says: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]: Unsatisfied dependency expressed through method 'dataSourceScriptDatabaseInitializer' parameter 0: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception with message: Failed to determine a suitable driver class I found some threads saying to (exclude = DataSourceAutoConfiguration.class) to my SpringBootApplication annotation, but this just results in another error saying UnsatisfiedDependencyException where my Repository is not available for injection into my controller. I've tried undoing all of my refactoring but still it's not working, and I'm quite stuck on this. Application: Application Repository: Repository Controller: Controller Service: Service Application.properties: Properties pom.xml: Pom Tried excluding DataSourceAutoConfiguration from the SpringBootApplication annotation, but this resulted in the TranslationRepository not being available in my TranslationService. Tried reverting my changes but that didn't help. Tried adding explicit postgres driver property to application.properties, also didn't help. As suggested by Mox: TranslationApplication: package com.projectbluegames.tbd; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class TranslationApplication { public static void main(String[] args) { SpringApplication.run(TranslationApplication.class, args); } } properties: spring.datasource.url=jdbc:postgresql://localhost:5432/TBD spring.datasource.username=postgres spring.datasource.password=password spring.jpa.hibernate.ddl-auto=update spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect spring.datasource.driver-class-name=org.postgresql.Driver Repository: package com.projectbluegames.tbd.repository; import org.springframework.data.repository.CrudRepository; import com.projectbluegames.tbd.entities.Translation; public interface TranslationRepository extends CrudRepository<Translation, Integer> {} Controller: @RestController public class TranslationController { private final ITranslationService translationService; public TranslationController(ITranslationService translationService) { this.translationService = translationService; } @PostMapping("/refresh") private ResponseEntity<String> refreshTranslationCache() { translationService.refreshTranslationCache(); return ResponseEntity.ok("Translation cache reloaded successfully"); } } IService: package com.projectbluegames.tbd.services; import java.util.List; import com.projectbluegames.tbd.dtos.TranslationDto; public interface ITranslationService { public void refreshTranslationCache(); } Service: package com.projectbluegames.tbd.services; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import com.projectbluegames.tbd.entities.Translation; import com.projectbluegames.tbd.repository.TranslationRepository; public class TranslationService implements ITranslationService { private final TranslationRepository translationRepository; private Map<String, Translation> translationCache = new HashMap<String, Translation>(); public TranslationService(TranslationRepository translationRepository) { this.translationRepository = translationRepository; refreshTranslationCache(); } @Override public void refreshTranslationCache() { translationCache.clear(); Iterable<Translation> translations = translationRepository.findAll(); translations.forEach(t -> translationCache.put(t.getLanguage() + "_" + t.getKey(), t)); } } Translation Entity: package com.projectbluegames.tbd.entities; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Table; @Entity @Table(name="translations") public class Translation { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; private String key; private String language; private String value; private Translation() { } public Translation(String key, String language, String value) { this.key = key; this.language = language; this.value = value; } public String getKey() { return key; } public String getLanguage() { return language; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } pom: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.1.4</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.pb</groupId> <artifactId>core</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>pom</packaging> <name>tbd</name> <description>Core</description> <properties> <java.version>17</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> You need to include database driver jar in your dependencies. If you have included share your dependencies included You're right, I should have done that. I've edited the post to include that. Instead of embedding links to screenshots, Please paste the code in the question. this will allow others to copy and paste your code to reproduce the issue. Hey Mox, I've done as you suggested Include the following property in your properties file spring.datasource.driver-class-name=org.postgresql.Driver This should mostly resolve. Unfortunately, the error remains the same As part of my refactoring, I had added to the pom.xml <packaging>pom</packaging> Which I had forgotten to remove. After removing this, it works.
common-pile/stackexchange_filtered
Transposed pattern search I have text file with format 1 5.287 15.026 0.623 1 U 1.805E+05 0.000E+00 e 0 666 761 769 2 4.601 15.023 0.623 4 U 6.220E+04 0.000E+00 e 0 0 0 0 3 2.883 15.059 0.623 3 U 3.303E+05 0.000E+00 e 0 680 761 769 4 0.623 56.340 5.287 3 U 9.990E+04 0.000E+00 e 0 769 590 666 .... I want to identify lines where column 11 matches to column 13 and column 13 matches to column 11 of any other line (e.g. Line 1 and Line 4). I wish to add a comment at the end of both lines and print the entire file. 1 5.287 15.026 0.623 1 U 1.805E+05 0.000E+00 e 0 666 761 769 #Line 4 2 4.601 15.023 0.623 4 U 6.220E+04 0.000E+00 e 0 0 0 0 3 2.883 15.059 0.623 3 U 3.303E+05 0.000E+00 e 0 680 761 769 4 0.623 56.340 5.287 3 U 9.990E+04 0.000E+00 e 0 769 590 666 #Line 1 This is NMR spectroscopy data. You help is highly appreciated. Thank you -mandar What have you tried so far? Show the code. SO is not a "write the code for me" site. @JimGarrison Sorry about that. I am from non-technical background. I was trying awk '{for (i=1; i<=NF; i++) if ($11==$13 && $13==$11); print $0 "#Line" $1 }' Something like this may work: use warnings; use strict; my %col11_13; # read file my @lines = map { chomp; [ split, $_] } <>; # prepare hash in the first pass for my $i (0..@lines - 1) { push (@{$col11_13{$lines[$i][10]."|".$lines[$i][12]}}, $i + 1); } # output in the second... for my $i (0..@lines - 1) { # get the list of matching records, but filter out a self match my @s = grep { $_ != $i + 1 } @{$col11_13{$lines[$i][12]."|".$lines[$i][10]}}; if (@s) { print $lines[$i][13], "# Line ", join(" ", @s) ,"\n"; } else { print $lines[$i][13], "\n"; } } How to modify your code to run only on non-zero values of column 11 and 13. (e.g. how to overlook line 2 of my original example?). Thank you. change the push like this: push (@{$col11_13{$lines[$i][10]."|".$lines[$i][12]}}, $i + 1) if ($lines[$i][10] && $lines[$i][12]); What's the grep in your answer doing? Looks like it's trying to prevent a line from matching itself, but it took me a moment to figure that out. A comment might be useful there. @IlmariKaronen, yes that's exactly what I did. Updated, thanks.
common-pile/stackexchange_filtered
Old Russian or Soviet-era cartoon movie about a servant, a prince and a princess I’d appreciate any help remembering the title of an old Russian or Soviet-era cartoon movie. The story is about a prince and his servant, who go on an adventure to rescue a princess from a dragon. The princess's name is Vasilisa the beautiful. During the adventure, it is the prince's servant who takes all the risks and completes all the missions. I remember that during one of the missions the servant was transformed into a dog, and in another he went inside the house of an old witch. Finally, he manages to defeat the dragon by cutting the dragon's heads with something like a magical water stream given to him during the adventure, and rescues the princess. As a reward, the princess marries him instead of the prince. This sounds interesting and a bit familiar to me. Was this a stop-motion animated film or a traditional type of cartoon? I assume you believe this is 1960s to 1980s and such by the way you mention “Soviet-era” correct? Was there moose and squirrel? Does it seem related to this 2006 Russian animated movie? https://en.m.wikipedia.org/wiki/Dobrynya_Nikitich_and_Zmey_Gorynych yes JakeGould I believe it was between 60s and 80s, it was a traditional cartoon, there was no moose nor squirrel, and it's not related to the mentioned 2006 movie. I remember more details now, the princess was called vasilisa the beautiful (I found stories with the same name but it was different from what I'm asking about), she was kidnapped by an old wizard who transforms to a dragon with many heads at the final battle and the servant was able to cut his heads by some thing like a magical water stream given to him during the adventure. thanks for your help guys What's the cryllic spelling of vasilisa? I have no idea, I tried to search with English pronunciation but I didn't get the answer I'm looking for I fffffound it, it's called Сказка сказывается, cde you inspired me, I searched google images for the Russian translation of Vasilisa the beautiful and I found a screenshot of the movie. thanks a lot for all of you. From the Cyrillic Сказка Сказывается literally translated as "The Fairy Tale", alternatively titled "Another's Tale to Tell" or "Tale to be Told" is a 1970 cartoon short by written by Boris Larin directed by Ivan Aksenchuk. It is based on the archetypical Slavic fairy tales of the Heroic Ivan Tsarevich or Ivan the Fool, The Maiden Vasilisa the Beautiful or Vasilisa the Wise/Frog Princess (not related to the germanic fairy tale of Frog Prince/Princess and the Frog), and the Villainous Immortal Koschei. [Koschei the Deathless] [Russian Literal: Bag of Bones] kidnapped Vasilisa the Beautiful, locking her away and torturing her so people will try to rescue her. There is a Prince who comes to save her but won't life a finger to do it. His faithful servant Ivan does it instead, dealing with a cannibalistic witch, a riddle loving living waterfall, and finally Koshcei turned into a 3 headed dragon. As mentioned, the servant does all the work, does get turned into a (very lion-y) dog, goes to retrieve a knife from the house of the famous old witch of fairy tale lore, Baba-Yaga, and in the end wins Vasilisa's hand in marriage. English and Spanish subtitles available by Chapaev & Eus and Don Medina respectfully (Use the youtube setting/gear button to change):
common-pile/stackexchange_filtered
Is it possible to configure after-deployment behavior for a WAR (or EAR)? When I'm deploying a WAR (or EAR) to an application server I have to be sure that the environment (everything around the AS) is ready for my application. Is it possible to instruct AS to execute certain Java classes right after deployment, and report a deployment problem if one of them reports a failure? Implement ServletContextListener and register it with <listener-class> inside your web.xml What if it's EAR without web.xml at all? I mean, is there any more generic approach? @Vincenzo: Note that the title of your question is misleading then :) What if it's EAR without web.xml at all? I mean, is there any more generic approach? I'll put my answer back then :) To my knowledge, there is nothing standardized in Java EE for that so the answer is "it depends on what your application server has to offer". For example, with WebLogic you can create ApplicationLifecycleListener classes. Depending on the complexity of the checks you want to perform, it might be simpler to create some kind of status page deployed as part of the application and check it after deployment (that you could poll later regularly to check the health of your app). For complex needs, using a real monitoring solution might be a better choice. This is the solution we're using for PHP projects: phpRack.com. It does exactly what you said, creating a dedicated monitoring page inside the application. So that you have to worry about tests only, not about how to run them and deliver results (to tester or to Maven/Ant/Phing). I was interested whether something similar exists for java.. Looks like it doesn't, right? (a good chance to create it :) @Vincenzo: Yes, something in the spirit of http://phpRack.com/. I'm not aware of something equivalent (it would be worth discussing what such a thing should check though). And as I said, for more complex needs, I'd consider real monitoring solutions like Nagios, ZenOSS, Hyperic, etc.
common-pile/stackexchange_filtered
Why "selected" not rendered here? I am trying to understand how React works with the new Hooks implementation. In this example, I want the browsers to render selected items as I click on the rendered options. But as you can see, it doesn't work. Here is the example: https://codesandbox.io/s/pjorxzyrx7 Do I have to use the useEffect in this case? Also, as I understand, useEffect couldn't render anything and only return functions. So, what am I missing here? Thank you! Please don't use external links to show your code. Instead, please [edit] your question to also include a [mcve] of your code in the question itself (using formatted text, no images please!) You're currently mutating the contents of the selected array instead of replacing it. React can't detect a state change when you do this. Try something like the following: const handleSelected = item => { console.log(item); console.log(selected); setSelected([...selected, item]); }; When updating arrays or objects as a part of a state, always make a new copy to assign so that React can properly know when to re-render. Also, include relevant parts of your code directly in the question in the future, instead of hiding it behind a link (although including a runnable example is great!)
common-pile/stackexchange_filtered
C# (.NET, Mono) Use array for transfer data between threads Today I accidentally stumbled upon a MemoryBarrier and realized that I do not fully understand the work of the CPU with RAM. The search did not give me an unambiguous answer to the question, so I decided to ask a new question. There are two arrays: int[] dataStates; //default items value is 0 MyStruct[] data; //MyStruct is a struct with several fields There are two threads (ThreadA, ThreadB) ThreadA performs the following code: data[index] = ... //new value //change to "1" after setting data Interlocked.Exchange(ref dataStates[index], 1); ThreadB code: //wait for "1" in array item and replace to "2" while(Interlocked.CompareExchange(ref dataStates[index], 2, 1) != 1) { Thread.Sleep(0); } //read actual data var value = data[index]; Is it possible that the Thread will read the data from the data[index] and they will be obsolete? By the word obsolete, I mean that the data received from the array will not match the data that was set before the Interlocked.Exchange call. In general, I try data transfer between threads in the most productive way. Do use this approach (without locks) is it appropriate or are there more acceptable approaches? Not familiar with Interlocked class. Normally do this with a Singleton. But your Thread.Sleep(0) is a problem since it does not force a context change. See: https://stackoverflow.com/a/3257751/2245849. I don't know if this is the solution but as far as I understood your sample you could do the following: var queue = new ConcurrentQueue<DateTime>(); var tcs = new CancellationTokenSource(); var token = tcs.Token; Task.Run(async () => { for (var i = 0; i < 2; i++) { queue.Enqueue(DateTime.Now); await Task.Delay(2000); } tcs.Cancel(); }, token); Task.Run(() => { while (!token.IsCancellationRequested) { if (queue.Any()) { DateTime result; queue.TryDequeue(out result); Console.WriteLine($"Received {result}..."); } } }, token).ContinueWith(t => { Console.WriteLine("Stop"); }); Console.ReadLine(); tcs.Cancel(); You will need some namespace-imports: using System.Threading; using System.Threading.Tasks using System.Collections.Concurrent; This is a complete different apporach avodiding manual sync between threads. I used DateTime instead of MyStruct. From what I read in the reference to the methods Exchange and CompareExchange they do not imply a memory barrier. Hence, writing the value to data[index] may be swapped with the interlocked setting of dataStates[index], which means that the second thread may actually read invalid data. I agree with sprinter252 that there is probably a better way to implement this. Isn't it a normal producer-consumer problem? This is solvable with semaphores or it can be rewritten to use a task queue as in sprinter's answer.
common-pile/stackexchange_filtered
Why are used conditional move assembly instructions? Why are still used conditional move instructions (CMOV) in assembly languages in certain cases? Why don't use S{cond} (skip instruction if compare with zero) ? Unlike CMOVs SKIPs don't have direct data dependencies (which is benefit for pipelining) and following instruction cen be arbitrary (not only condition move). Of course, it doesn't require flush pipelining, it just cancel write result of following instruction. The only bottleneck that I noticed can be seen on the following example: if(a > b) { a = b; } c = a % 2; With assembly equivalent: ; R0 = a, R1 = b, R2 = c SUB R2, R0, R1 ; R2 = R0 - R1 SLEG R2 ; if(R0 <= 0) PC++ | Skip If Less or Equal Zero CP R0, R1 ; R0 = R1 *AND R2, R0, =1 ; R2 = R0 & 0x01 * Critical execution. Processor must wait for result of CP instruction, because of R0 as operand in AND instruction. On the other side, this is common situation in modern CPU and is effectively solved, so I think degradation of performance wouldn't be so high as it is in the case of conditional move. Anyway, where is predictable conditional jump possible, use it. Sorry for my English. Can you please edit the architecture you are talking about into your question? I don't see a skip instruction for i386. @ColonelThirtyTwo I think that x86 doesn't use this instruction. Generally I know only about PICs. And my question is why this instructions aren't regularly used in modern CPUs? @NikNovák it's up to the instruction set designer which instructions they choose to include based upon what operations they choose should be easier to write. One could just as well ask why a PIC doesn't have the x86 rep instruction. Conditional moves, rep, and many other instructions are not essential (their capability can be implemented using other combinations of existing instructions). Note that a short forward branch can be interpreted as a request for predication. IBM implemented such dynamic hammock predication in POWER8 for single instruction conditional branch-overs for a significant subset of instructions. SLEG R2 is a conditional-branch forward by one instruction. It can be implemented with either a data dependency (effectively make the next instruction predicated) or branch prediction (treat the same as any other conditional branch). Note that the result of the comparison counts as "data", so cmov has 3 inputs: dest, src, and flags. Similarly, predicating an instruction with a skip adds the skip's control input to the data dependencies of the other instruction. You have to choose one or the other. I think the correct way to say what I think you're trying to say is that usually the data-dependency check doesn't find anything that it has to wait for. That's going to be true less often in a 4-wide out-of-order design like modern x86 chips, because the window for data dependencies to matter is much bigger. There are many more instructions in flight, and any independent dependency chains can run in parallel. A skip instruction is certainly more powerful than x86's clunky cmov. Since cmov can't take immediate operands, it often requires extra instructions to put a constant in another register as a source. Paul Clayton's comment is interesting: POWER8 special-cases conditional forward-by-1-insn branches to handle them as data dependencies instead of control dependencies. That sounds like it should be exactly the same as a PIC skip instruction. Thank you for your answer. So, you want to say me that conditional branch on POWER8 by 1 instruction (or branch distance depends on number of implemented pipeline levels?) is executed with only discard result writes that CPU jumps over? If I understand it right, at the end of pipeline (when results are writed into register/memory) must be some form of reorder buffer to get instruction back to their original order, isn't it so? Or POWER8 doesn't use out-of-order exectuion? @NikNovák: If I understand Paul's comment correctly, they yes, POWER8 treats forward branches by 1 insn as a predicate for the next insn. IDK if it still uses an execution unit for the instruction when the predicate turns out to be false, but that sounds likely. And yes, most OOO CPUs use a Re-Order Buffer (ROB) to track insns from the first OOO pipeline stage (issue) to the last (retirement). This allows in-order retirement to support precise exceptions.
common-pile/stackexchange_filtered
Stash a specific hunk, Git Using Git, I want to stash only one hunk in one specific file in order to commit the rest of the changes. Therefore, I could go back to my temporary change by pulling it from stash. However, the only way I could find is to stash the whole unstaged files. What about adding everything to the index except that hunk (using --patch), and then git stash save --keep-index? You can simply commit first, and then stash. @evolutionxbox I've tried this and what it does is stashing staged files (while keeping them staged too) and removing all the non staged modifications. This not the behaviour I was looking for That's why I recommended adding everything. It can all be unstaged after the stash. Could you please show how did you use --patch ? It’s interactive. I would add all but that one file to the stage and then use git add —patch on the last file to stage all hunks except the hunk I want to stash. Then stash keeping the index which will stash the hunk but leave the stage alone. In recent Git versions, the git stash push command accepts a pathspec to specify which file(s) to stash, and a -p option like git add: git stash push -p -- filename(s) or git stash -p -- filename(s) This will give you a prompt similar to git add -p to chose the hunk(s) you want to stash, and it will only stash the changes you selected for the files your specified. The solution above was tested with git 2.17.0. I also tested with an older version, git 2.4.10, and the pathspec was not supported. But the -p was still available for git stash save: git stash save -p or git stash -p It's not as nice as the option with more recent Git, though, because you have to interactively go through all the files, not just the one you want. PS: just tested on git 2.4, and filespec is not supported, but git stash save -p works, only it makes you go through all the files instead of only the specified one. Awesome ! This is the answer I was looking for. Thank you :) No problem. Now that I found it - thanks for asking the question! - I think I'll use it too. Simpler than my suggestion! Another approach is to stage the changes you want to stash first, then run git stash --staged. This allows you to select the hunks first, and compose the comment/message later, instead of having to do both in one step. @XiangmingHu That's a good suggestion, especially since it means you could stage files in multiple calls to git add or git add -p and only stash when you were happy with the results. Here is a workflow that accomplishes what you want using a branch, which is personally what I prefer to use instead of the stash. It's more typing and more commands, but it gives you full control of the results afterwards. git checkout -b dev.temp git add <file-to-stash> git commit -m'stash work alike' git checkout <base-branch> # commit what you need in <base-branch> From here you have your "stashed" file in a branch so there are many ways to continue. Option 1: go the the branch and keep working there, with a merge or rebase when you're done: git checkout dev.temp git rebase <base-branch> #work here, merge or rebase when you're done Option 2: check out the file into your main branch: git checkout dev.temp <file-to-stash> <file-to-stash> is now in the index; use git reset to revert it to a locally changed file and keep working where you were at. Option 3: cherry pick the commit so it's also committed in your working branch - this is the least like your workflow, however, since it leaves <file-to-stash> committed in `, but here it is for completeness: git cherry-pick dev.temp With all options, you can delete the branch with git branch -D dev.temp when you're done with it. -d will do if you actually merged it back in, but -D is needed if the branch is not actually merged but you have recovered the changes you wanted. I have a strong preference for using temporary dev branches over the stash because it gives you a lot more control over what you put in and how you take it back out afterwards, although I agree there are also effective (and certainly quicker) workflows with the stash itself: it's a trade-off between speed and control. I believe this could be a workaround to save temporary changes. But, I was looking for a quick usage of the stash itself on a specific hunk, without making temporary commits I agree, a quick stash command would be nicer, and I just found one. I'll write a second answer.
common-pile/stackexchange_filtered
Sort by divs content (click) I have a script that appends the content. There is only 1 change I need to do, but don't know how. I want a sort by content of the div every time I click.(ASC to desc or desc to ASC) What he does now is: I have 3 divs <div>Others</div> <div>Girls</div> <div>Boy</div> if I click it changes in <div>Boy Girls Other</div> <div>>Boy Girls Other</div> <div>>Boy Girls Other</div> My code: $("#button-sort").click(function(){ $(".sorteren div").sort(asc_sort).appendTo('.sorteren'); function asc_sort(a, b){ return ($(b).text()) < ($(a).text()) ? 1 : -1; } function dec_sort(a, b){ return ($(b).text()) > ($(a).text()) ? 1 : -1; } }); Code that I used before: var mylist = $('.sorteren'); var listitems = mylist.children('div').get(); listitems.sort(function(a, b) { return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase()); }); $.each(listitems, function(index, item) { mylist.append(item); }); My div structer is: <div id="drive-content"> <div class="folderbox"> <div class="sorteren"> <div class="items-titel"></div> </div> <div class="date"> </div> </div> <div class="folderbox"> <div class="sorteren"> <div class="items-titel"></div> </div> <div class="date"> </div> </div> <div class="folderbox"> <div class="sorteren"> <div class="items-titel"></div> </div> <div class="date"> </div> </div> </div> what error do you got? It's not the error I need to combine this with click event . If i do that it will only append (like the code does) but instead of append i need just to sort it on asc-desc and desc-asc Please create a [MCVE] rather than little snippets than don't quite have enough information You can add/remove one class to sort asc/desc, and just assign sorted html to one variable and change html of sorteren div as that variable. $("#button-sort").click(function() { var sort, el = $('.sorteren') sort = el.find('div').sort(el.hasClass('asc') ? dec_sort : asc_sort) el.toggleClass('asc') function asc_sort(a, b) { return ($(b).text()) < ($(a).text()) ? 1 : -1; } function dec_sort(a, b) { return ($(b).text()) > ($(a).text()) ? 1 : -1; } $(".sorteren").html(sort) }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="button-sort">sort</button> <div class="sorteren"> <div>Others</div> <div>Girls</div> <div>Boy</div> </div> In case you have multiple .sorteren divs and you want to sort each one you can change code to this. $("#button-sort").click(function() { function asc_sort(a, b) { return ($(b).text()) < ($(a).text()) ? 1 : -1; } function dec_sort(a, b) { return ($(b).text()) > ($(a).text()) ? 1 : -1; } $(".sorteren").each(function() { var sort, el = $(this) sort = el.find('div').sort(el.hasClass('asc') ? dec_sort : asc_sort) el.toggleClass('asc') el.html(sort) }) }) .sorteren { border: 1px solid black; margin: 20px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="button-sort">sort</button> <div class="sorteren"> <div>Others</div> <div>Girls</div> <div>Boy</div> </div> <div class="sorteren"> <div>c</div> <div>a</div> <div>b</div> </div> I have a script that makes the divs and the content. On 1 page i will have only 3 divs other page I will have 55 divs with same structure. Thats the reason i can't use this script. And my script will append all the content in 1 div Do you mean you have multiple .sorteren divs with divs inside and you want all of them sorted when you click on sort button? Yes everytime the script makes 1 folder box it contains a div named sorteren with the div named item-title its about the content of the div named item-title Nope it doesnt work and no errors i will update my div structure uno momento It somehow delete's the entire div with all divs in it It's my fault . I made a typo (don't know why he is deleting everything) but thnx to u its working !!! Thnx THNX THNX !!!!!!!!!!!!!!!!!!!!!!!!!!!!
common-pile/stackexchange_filtered
Android studio - Change string in textView I have some stings in the styles/string.xml as below: <string name="string1">something</string> <string name="string2">some other thisn</string> <string name="string3">asdfgh jkl</string> <string name="string4">qwerty uiop</string> . . . and I have a textView and a button in my current activity. When I click the button, the text in the textView has to change (to the next sting) according to what is currently shown. That is, if the current text in textView is string1, then it should change to string2. The code below doesn't work but will illustrate what I am looking for count = 0; public void onClick(View v) { count++; str="R.string.string" + count; textView.setText(str); } I have to somehow convert the string to the actual value of (say)R.string.string1. Is there a way to do that? Or is there any other method to achieve what I am looking for? You can bring your resource ids into an array and use counter to index them. You need to call a getString either from context or Resources.getSystem() with those ids to get the string you want. count can be made into a class field so that it persists between clicks. You can create a string array resource similar to this one below: <resources> <string-array name="my_string_array"> <item>stringa</item> <item>stringb</item> <item>another string</item> <item>yet another string</item> </string-array> </resources> // you can use a string array resource String[] strings = getResources().getStringArray(R.array.my_string_array) int count = 0; void onClick(View v) { if (count < strings.length) textView.setText(strings[count]) count++; } @possum, I updated the answer to include a sample xml string array resource Seems like I can't access the string array with (R.string.my_string_array). It only shows the strings, It's not showing string arrays. (edited) I have figured it out, It should be (R.array.my_string_array). Thanks for the answer Micah.
common-pile/stackexchange_filtered
Selenium Could Not Locate Element by XPath I am trying to locate element using Xpath with Selenium. The element in question is the channel name on the YouTube page: https://www.youtube.com/watch?v=FSyAehMdpyI&list=PL8dPuuaLjXtPHzzYuWy6fYEaX9mQQ8oGr My xpath is: /html/body/ytd-app/div[1]/ytd-page-manager/ytd-watch-flexy/div[3]/div[1]/div/div[7]/div[3]/ytd-video-secondary-info-renderer/div/div[2]/ytd-video-owner-renderer/div[1]/div/yt-formatted-string/a In the developer tool bar on the YouTube page, I was able to find the element by entering the Xpath. But when I try to find it in my Python script the operation times out. channel_name = self.wait.until(EC.presence_of_element_located((By.XPATH,"/html/body/ytd-app/div[1]/ytd-page-manager/ytd-watch-flexy/div[3]/div[1]/div/div[7]/div[3]/ytd-video-secondary-info-renderer/div/div[2]/ytd-video-owner-renderer/div[1]/div/yt-formatted-string/a"))).text Any ideas why? Try a simpler Xpath //ytd-video-owner-renderer/div/div/yt-formatted-string/a Try This one, Relative path - //yt-formatted-string[@id='owner-name']//a[contains(text(),'CrashCourse')] it Worked for me, Hope it Helps you! You can use a much simpler relative xpath to extract the channel name using visibility_of_element_located() method and you can use either of the following solutions: Using text: channel_name = self.wait.until(EC.visibility_of_element_located((By.XPATH,"//div[@id='owner-container']/yt-formatted-string[@id='owner-name']/a"))).text Using get_attribute(): channel_name = self.wait.until(EC.visibility_of_element_located((By.XPATH,"//div[@id='owner-container']/yt-formatted-string[@id='owner-name']/a"))).get_attribute("innerHTML")
common-pile/stackexchange_filtered
ResNet 34 training with custom dataset I am a beginner in Neural Networks and wanted to implement ResNet34 for a pet project at my workplace. Due to confidentiality issues, I do not want to use ImageNet trained weights. I have a dataset of around 10000 images which I can use to train my dataset. Can you suggest if that is possible without overfitting. I can use data augmentation for additional data. Any help is appreciated. Thanks. Not sure how confidentiality makes transfer learning an issue. That does not make sense to me and i would strongly consider it. Ideally, you'd want a bit more images in order to train your model effectively. I've managed to train a couple of ResNet-50 models on around 10000 MR Images from scratch, without much problem. However, what I was trying to solve was a relatively easy task. If you want to train your model on a more generic task, you might encounter a few issues. On the other hand, because of the strict format of MRIs, I couldn't augment my images to a large degree. I am trying to classify documents into around 10 categories. Do you think it would work ? And each document is represented as an image?
common-pile/stackexchange_filtered
"unityengine.component does not contain a definition for GetEnumerator" Error in Unity c# /* Ihitable in the foreach loop is taken from the IHitable interface so I'm not sure if i have implemented it correctly */ public interface IHitable { void Hit(); } /* Getting Error with second foreach loop as shown in the Title not sure how to fix the error */ void Attack2() { var hits = Physics.OverlapSphere(AttackPoint.position, 0.5f); foreach (var hit in hits) { var hitables = hit.GetComponent(typeof(IHitable)); if (hitables == null) return; foreach(IHitable hitable in hitables) hitable.Hit(); Debug.Log(hit.name); } } // Any help suggestions would be really appreciated hit.GetComponent(typeof(IHitable)) is returning only one object, and not a list/array, and does not implement IEnumerable, thus not implementing GetEnumerator as well. The GetComponent method is used to retrieve a unity component. A component is a class that derives from MonoBehaviour. So the type that you give to GetComponent must derive from MonoBehaviour. Maybe you should create a Hitable class that derives from MonoBehaviour, and add it to all of your hitable GameObjects.
common-pile/stackexchange_filtered
My javascript on another site, what domain is it checking cookies for? I am having some cookie issues and am trying to troubleshoot. So... I have a script that I put on other website domains <script type="text/javascript" src="http://siteA.com/script.php"></script> Lets say I put this script on siteB in http://siteA.com/script.php I have it check for a cookie with this code function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1); if (c.indexOf(name) != -1) return c.substring(name.length, c.length); } return ""; } function checkCookie() { var id = getCookie("mycookiename"); if (id == "1234") { redirect() } else { something() } } So my question is, is this javascript checking for the cookie on siteA or siteB? The PHP (server) at siteA will receive cookies for siteA. JavaScript will access the cookies of the page it runs in, which is siteB in your example (Client-side) JavaScript code (on a webpage) always executes in the context of the document it is loaded into, so it will have access to the cookies belonging to the document. You could generate the JavaScript using server side code (written in any language you like) and that server side code would have access to the cookies for the URI hosting the JS (and could inject the data into the JavaScript file). (This is usually not a good idea). Why "usually not a good idea"? IIRC that's the way authentication works for JSONP :-) @Bergi — Because usually you want scripts to be easily cacheable static resources. JSONP is a hack to use JS as a data serialisation format in browsers that don't support CORS. It will check on siteB's cookie (the page that is running the code). If it wouldn't it would lead to security issues. Also CDN libraries wouldn't work as they would check the cookie on the CDN's domain, not on the domain you really want to check.
common-pile/stackexchange_filtered
My app does not change orientation I am using XCode 4.6 and iOS 6.1. But my app does not change orientation. I have set my app to support orientation in pList and added orientation change method. But still the app does not change orientation. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); } I'm using TabBarController, and I'm adding it by using this code. self.window.rootViewController = self.tabController; In iOS 6 simulator all working fine but for iOS 5 it does not work. What is your view setup!? Do you use a rootViewController? Is it a single controller, or a tabbar, or a navbar? No one can answer this question without these informations. Appdelegate are u set the self.window.rootViewController = YourController; just comment that shouldAutorotateToInterfaceOrientation mehtod and run You are using tabBar so put this code in your AppDelegate at the bottom of @end. @implementation UITabBarController (Rotation) - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { if ([self.selectedViewController isKindOfClass:[UINavigationController class]]) { UIViewController *rootController = [((UINavigationController *)self.selectedViewController).viewControllers objectAtIndex:0]; return [rootController shouldAutorotateToInterfaceOrientation:interfaceOrientation]; } return [self.selectedViewController shouldAutorotateToInterfaceOrientation:interfaceOrientation]; } @end Hope this will help. Code for Checking Orientation Working or Not ? Code :: - (void)viewDidLoad { [super viewDidLoad]; [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged) name:@"UIDeviceOrientationDidChangeNotification" object:nil]; ...... } Check Method :: -(void)orientationChanged { NSLog(@"Orientation Changed..!!"); } Code for Orientation Changed Methods In PCH File, #define IOS_OLDER_THAN_6 ( [ [ [ UIDevice currentDevice ] systemVersion ] floatValue ] < 6.0 ) #define IOS_NEWER_OR_EQUAL_TO_6 ( [ [ [ UIDevice currentDevice ] systemVersion ] floatValue ] >= 6.0 ) In .m file, //For Less than IOS 6 #ifdef IOS_OLDER_THAN_6 - (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)toInterfaceOrientation { return toInterfaceOrientation; } #endif // For Newer than IOS 6. #ifdef IOS_NEWER_OR_EQUAL_TO_6 -(BOOL)shouldAutorotate { return YES; } - (NSUInteger)supportedInterfaceOrientations { return (UIInterfaceOrientationMaskAll); } #endif Hopefully, it'll be help to you. Thanks. Still Not changing orientation First applied for that code & check whether orientation is working or not by getting response in NSLog()? log value displaying fine but orientation not changing This mthods are never called. i had pu log in it and it does not showed In ios 6 simulator all working fine but for ios5 it does not work the method for detecting change of orientation is helpfull +1 You need to use these two new methods in order to control and configure the orientation changes for your viewControllers : - (BOOL)shouldAutorotate { return YES; } - (NSUInteger)supportedInterfaceOrientations { return (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown); } The method you are implementing is for iOS 5.x , but the methods mentioned in this answer are for iOS 6.x. If you want compatibility for both the OS versions, then you need to implement both the methods in your viewController. No still not changing orientation In your topmost navigation controller, define: -(BOOL)shouldAutorotate {return [self.visibleViewController shouldAutorotate];} and in your next viewController: -(BOOL)shouldAutorotate {return YES;} -(NSUInteger)supportedInterfaceOrientations { return (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown); }
common-pile/stackexchange_filtered
I have to run adb connect <IP_ADDRESS>:5555 in order for android emulator to show up in list When I start a Genymotion emulator (Android studio emulators crash android studio and dont start), I have to run adb connect <IP_ADDRESS>:5555 in order to connect adb to the emulator. Otherwise it doesn't show up when I use adb devices. I never had to do this before and I cannot figure out why. Does running adb usb to reset adb back to its default help? Give it a try. no that didn't work for me. Thanks Looks like it has something to do with recent update in android sdk platform tools. Downgraded mine from 28.0.2 to 28.0.1 and successfully got my genymotion emulator in adb devices back. 1): Try go to SDK MANAGER in folder EXTRAS and install GOOGLE USB DRIVER If this happens on a Linux machine you could try to Uncheck the "Use Host GPU" checkbox - in the emulator settings**
common-pile/stackexchange_filtered
$f^2+(1+f')^2\leq 1 \implies f=0$ Find all $f\in C^1(\mathbb R,\mathbb R)$ such that $f^2+(1+f')^2\leq 1$ It's quite likely the answer is $f=0$. Note that $|f|\leq 1$ and $-2\leq f'\leq 0$. Therefore $f$ is decreasing and bounded. What then ? I tried contradiction, without success. Have you thought about the limits as $x$ approaches $\pm \infty$? Remember that its values are decreasing and lie in a bounded region. well $-k\arctan(x)$ with $k$ small enough it seems for me satisfies your condition. Say $-1/\pi$. Then function is from $[-1/2,1/2]$ with negative derivative $>-2$. Something like that. @AlexanderVigodner with $k=0.01$ it fails at $x=13$. The equation is equivalent to $$ f^2+2f'+f'^2\le0\tag{1} $$ Since $f^2+2f'\le0$, where $f\ne0$, we have $$ (1/f)'\ge\color{#C00000}{1/2}\tag{2} $$ If $f(x_0)=a\gt0$, then $\dfrac1f(x_0)=\dfrac1a\gt0$ and $(2)$ says that $$ \frac1f\left(x_0-\frac3a\right)\le\frac1f(x_0)-\color{#C00000}{\frac12}\frac3a\lt0\tag{3} $$ as long as $\dfrac1f$ doesn't pass to $-\infty$ in $\left[x_0-\frac3a,x_0\right]$. In any case, on $\left[x_0-\frac3a,x_0\right]$, $\dfrac1f$ must pass through $0$, which is impossible because $f\in C^1(\mathbb{R})$. If $f(x_0)=a\lt0$, then $\dfrac1f(x_0)=\dfrac1a\lt0$ and $(2)$ says that $$ \frac1f\left(x_0-\frac3a\right)\ge\frac1f(x_0)-\color{#C00000}{\frac12}\frac3a\gt0\tag{4} $$ as long as $\dfrac1f$ doesn't pass to $\infty$ in $\left[x_0,x_0-\frac3a\right]$. In any case, on $\left[x_0,x_0-\frac3a\right]$, $\dfrac1f$ must pass through $0$, which is impossible because $f\in C^1(\mathbb{R})$. Therefore, $f(x)=0$ for all $x\in\mathbb{R}$. Can you elaborate a bit on your argument following $(2)$? @AlexSchiff: Any function with a slope at least $\color{#C00000}{1/2}$ (e.g. $1/f$) must pass through the $x$-axis at a finite point. What is $f=0$ how you can use (2) then ? @AlexanderVigodner: $f=0$ satisfies $(1)$. However, $(2)$ obviously holds wherever $f(x)\ne0$. Something must be adjusted since $\frac{1}{f}$ is continuous just outside the zeroes of $f$. What happens if a zero of $f$ belongs to the $(x_0-3/a,x_0)$-interval? Ok, it cannot happen. Since $f$ is decreasing and $f(x_0)>0$, any zeroes of $f$ is bigger than $x_0$. @JackD'Aurizio: All that matters is that there is a zero of $1/f$ in the interval. If $f$ has a zero, $1/f$ simply goes to $\infty$. The argument is simply that $1/f$ must pass through $0$ and therefore $f$ must go to $\infty$ in a finite interval, which cannot happen since $f\in C^1(\mathbb{R})$. @robjohn: to prove that $1/f$ must pass through zero, you need the continuity of $1/f$ over the whole interval; the argument do not work for continuous function (over their domain) like $\tan x$ in a neighbourhood of $\pi/2$, for example. @JackD'Aurizio: $1/f$ is $C^1$ except where it goes to $\infty$ ($f=0$). From any non-zero value of $1/f$, the differential inequality forces $1/f$ to zero in a finite time. @robjohn: I completely agree with you, I am simply pointing out that "$\frac{1}{f}$ changes its sign in the endpoints of this interval" does not automatically imply that $\frac{1}{f}$ is zero in an inner point, since $\frac{1}{f}$ can change its sign by passing through a discontinuity, i.e. a zero of $f$. @JackD'Aurizio: I have edited my answer to account for the case that $1/f$ may blow up inside an interval. Since $f(x)$ is bounded and decreasing both $\lim_{x \rightarrow \infty} f(x)$ and $\lim_{x \rightarrow -\infty} f(x) $ exist. If $f(x)$ were not identically zero, then at least one of these limits is nonzero. Say it is the first one, and call the limit $L$. By the mean value theorem, $f(n+1) - f(n) = f'(x_n)$ for some $x_n$ between $n$ and $n + 1$. The left-hand side of this equation converges to $L - L = 0$ as $n$ goes to infinity, so we have $$\lim_{n \rightarrow \infty} f'(x_n) = 0$$ But we also have $$\lim_{n \rightarrow \infty} f(x_n) = L$$ Plugging $x_n$ into $f(x)^2 + (1 + f'(x))^2 \leq 1$ and taking limits as $n$ goes to infinity gives $L^2 \leq 0$, a contradiction. A similar argument works if $\lim_{x \rightarrow -\infty} f(x) \neq 0$. This is intuitive, the simplest argument so far. And this doesn't use the continuity of the derivative. Nice. You don't have to reason by contradiction, because you end up with $L^2 \leq 0 \implies L = 0$ anyway. Hints: As you mentioned, $f$ is decreasing and bounded. Think about $\lim_{n \to \infty} f(n)$. Must this limit exist? What does this imply for the limit of the derivative $f'$? Full Solution. The function $f(x)$ is decreasing and bounded, so $\lim_{x \to \infty} f(x)=L$ for some $L \in [-1,1]$. For the sake of contradiction, we suppose $|L|>0$. To set up the contradiction, we relate $|f(x)|$ and $f'(x)$: Let $\epsilon\in (0,1]$, and suppose that we have $0 \geq f'(x) \geq -\epsilon$ for some $x \in \mathbb{R}$. Then \begin{align*} f^2(x) & \leq 1-(1+f'(x))^2\\ &\leq -2f'(x) - (f'(x))^2 \\ &\leq -2f'(x) \\ & \leq 2\epsilon. \end{align*} Thus $|f(x)| \leq \sqrt{2\epsilon}$. Therefore we know that if $|f(x)| > \sqrt{2\epsilon}$, then $f'(x) <-\epsilon$. For sufficiently large $x$, we must have $|f(x)| > |L|/2=\sqrt{2(|L|^2/8)}$, hence $f'(x) <-|L|^2/8$. This contradicts the fact that $f(x)$ is bounded below. An entirely analogous argument shows that $\lim_{x \to -\infty} f(x)=0$. Monotonicity implies $f=0$.QED Although it should be a cakewalk, I fail to prove that for a $C^1$ function with a limit at infinity, its derivative must have $0$ as limit at $\infty$... Have you first shown that the limit of the derivative exists? I don't think you can prove the existence of the limit for the derivative with usual theorems. The only information about it is boundedness. And now that I remember this, http://math.stackexchange.com/questions/788813/the-limit-of-the-derivative-of-an-increasing-and-bounded-function-is-always-0/788818#788818 this is definitely wrong. I was thinking that the constraint $f^2 +(1-f')^2 \leq 1$ would imply that the derivative's limit existed. Another thought would be to compare the limits as $x$ approaches positive and negative infinity. There are some easy restrictions there. I found a counterexample function, see my new answer. It seems for me your pved only that the fact that $f(x)\to 0$ on infinity. But it does not prove that $f(x)=0$ on $R$. Am I wrong? The sequence is decreasing, so that's all that needs to be shown. I think I have to completely rewrite the solution keeping the wrong one above untouched. As I said before I am sure we can build such function, and I think I did it using the ODE in the above solution in the end. I am building a counterexample function: Fistly, $f(x)= 0$ for $x\le 0$; Now I'd like to build a simple function satisfying condition $$ f^2+(1+f^\prime)^2\le 1 $$ on some interval $[0,x^*]$. I define $$ g(t)=-x^3/3-x^2/2\\ g^\prime(x)=-x^2-x $$ I is obvious that in some positive neighborhood $(0,\epsilon)$ $$ g^2+(1+g^\prime)^2 =O(\epsilon^4)+1-O(\epsilon) \le 1 $$ It is obvious also that staring from some $x^*$ $$ g^2+(1+g^\prime)^2\ge 1 $$ Besides we have this point $x^*$ is such that $$ g^2(x^*)+(1+g^\prime(x^*))^2= 1 $$ Let's check condition $g^\prime(x^*)>-1$. It is easy t estimate that $x^*$ is about $0.9$ and that then $g^\prime(x^*)< -1 Now again consider the differential equations $$ f^\prime=-1+\sqrt{1-f^2}\\ f^\prime=-1-\sqrt{1-f^2}\\ $$ and choose the second one in accordance with the sign $g^\prime(x^*)+1$. The solution of this equation with initial condition $f(x^*)=g(x^*)$ will extend our function on $R$. So the final function $f(x)$ is $$ f(x)=0 ~ if ~ x\le 0 \\ f(x)=g(x) ~ if~ 0<x\le x^* \\ solution~ of~ f^\prime=-1-\sqrt{1-f^2}, f(x^*)=g(x^*) ,~ x\ge x*\\ $$ Since I did not find any mistake in the proof that such function cannot exist I again probably made mistake somewhere. But I cannot find it. Any comments please. May be this ODE cannot have a solution on $R$? Lipschitz condition is not satisfied. FIX Well the solution of differential equation with non zero initial condition will satisfy your property $$ f'=-1-\sqrt{1-f^2} $$ Edit Notice that equation $$ f'=-1+\sqrt{1-f^2} $$ is also OK. Now let's change $\tau = -t$ and rewrite the second equation as function of $\tau$ $$ f_\tau^\prime =1-\sqrt{1-f^2} $$ Let's build now the function on $R^+$ as a solution of the first eqaution and on $R^-$ as a solution of the third equation. To guarantee differentiability in $t=0$ let's make equal derivatives at time $t=\tau=0$. $$ f^\prime_t=-1-\sqrt{1-f^2}=-f^\prime_\tau=-1+\sqrt{1-f^2} $$ So with initial condition $f=1$ we can propagate this function on $R$. I changed signs here. Now the initial derivative is Can you guarantee that it will exist on all of $\mathbb{R}$ if $f$ is not $\equiv 0$? I think we can play a bit with this equation to guarantee this. Let me think You can't have $f(x) = 1$ for any $x$. That would imply $f'(x) = -1$, and thus $f(y) > 1$ for $x-\varepsilon < y < x$. Who said this. I said it is 1 in the inital point. After this you extend it in both direction via equations. Extention is built on the different equation it is not symmetric. OK. I am wrong about negative direction. But something can be done, I am sure. I don't belieive f=0. I'm not sure either way. One could try if something like Gronwall's inequality forces $f\equiv 0$, though.
common-pile/stackexchange_filtered
In Dune are specifics given as to what the "Suk Imperial conditioning" of Dr Yueh actually is? I have read the first five Dune novels and after the first I do not recall any further mention of Imperial conditioning. In the novels written since Frank Herbert's death, were any further references or details given about what this process actually involved and why it was considered virtually impossible to remove? Synopsis Well, it's suggested that it's some form of Psychological Conditioning. I can't find any clear indication of how it's done, but that seems likely from the term, and none of the references I've found in the books I have seem to counter it. Also, given that it is broken via psychological means, that would pretty strongly suggest it's a mental conditioning. Now, since you asked about references, here's what some quick searching found: From Dune: “Hawat will have divined that we have an agent planted on him,” Piter said. “The obvious suspect is Dr. Yueh, who is indeed our agent. But Hawat has investigated and found that our doctor is a Suk School graduate with Imperial Conditioning—supposedly safe enough to minister even to the Emperor. Great store is set on Imperial Conditioning. It’s assumed that ultimate conditioning cannot be removed without killing the subject. However, as someone once observed, given the right lever you can move a planet. We found the lever that moved the doctor.” “How?” Feyd-Rautha asked. He found this a fascinating subject. Everyone knew you couldn’t subvert Imperial Conditioning! Then Jessica and Thufir talking about it: “Is there a traitor among us?” she asked. “I’ve studied our people with great care. Who could it be? Not Gurney. Certainly not Duncan. Their lieutenants are not strategically enough placed to consider. It’s not you, Thufir. It cannot be Paul. I know it’s not me. Dr. Yueh, then? Shall I call him in and put him to the test?” “You know that’s an empty gesture,” Hawat said. “He’s conditioned by the High College. That I know for certain.” Later, it being psychological is backed up by how they broke it: The Baron nodded. “Oh, yes. Now, I remember. So I did. That was my promise. That was how we bent the Imperial Conditioning. You couldn’t endure seeing your Bene Gesserit witch grovel in Piter’s pain amplifiers. Then, from the Appendix to Dune: IMPERIAL CONDITIONING: a development of the Suk Medical Schools: the highest conditioning against taking human life. Initiates are marked by a diamond tattoo on the forehead and are permitted to wear their hair long and bound by a silver Suk ring. PYRETIC CONSCIENCE: so-called “conscience of fire”; that inhibitory level touched by Imperial conditioning. (See Imperial conditioning.) Then, from Children of Dune: Suk doctors? Their conditioning supposedly guaranteed them against disloyalty to their owner-patients. Suk doctors came very expensive. Increased purchase of Suks would involve substantial exchanges of funds. Now, going to the newer books: From House Harkonnen “You, sir, are a Mentat, accustomed to selling your thoughts and intelligence to any patron.” Yueh drew his lips together and studied de Vries as if he were performing an autopsy . . . or wanted to. “I, on the other hand, am a member of the Suk Inner Circle, graduate of full Imperial Conditioning.” He tapped the diamond tattoo on his wrinkled forehead. “I cannot be bought, sold, or rented out. You have no hold over me. Now, please allow me to return to my important work.” In Sandworms of Dune: (I've omitted some irrelevant references, like him talking about drawing the tattoo back on his forehead.) In his first life, he had broken his Suk conditioning. He had failed his wife Wanna by allowing the Harkonnens to use her as a pawn and had betrayed Duke Leto, bringing about the Atreides downfall on Arrakis. ... Yueh touched his own smooth, unmarked forehead. "We're starting over, Jessica. Blank slates. Look at me. The first Yueh broke his Suk conditioning - but I was born without the diamond tattoo. Entirely unblemished. ... The evil Harkonnens had known that Wanna would be the key to breaking his Suk conditioning, and it had only worked - could only have worked - because Yueh loved her with all his heart. ... Unable to break his conditioning, Yueh shuddered and spasmed. He wanted nothing more than to do as the Baron demanded. "I... can't!" ... The memories were so clear to him that his entire body felt like a raw wound: Wanna in agony and the sharp, broken-crystal pain of how his Suk conditioning had been thwarted. ... In his restored memories, he saw with clarity when he had become an actual Suk doctor, when he passed through an entire Inner School regimen of Imperial Conditioning and took the formal oath. " 'A Suk shall not take human life.'" From Dune: House Atreides After years of training and conditioning, all Suk doctors seemed compelled to take themselves far too seriously. ... As heir to the Golden Lion Throne, Shaddam was familiar with Suk Imperial Conditioning, which guaranteed absolute loyalty to a patient. In centuries of medical history, no one had ever managed to subvert a graduate of the Inner School. There may be more, but that's all I could find in a quick search. Well that more than satisfies my curiosity. Thanks for a great answer. There was also a mention in Dune Messiah, where it's mentioned that the Bene Tleilax are very well aware that the conditioning can be broken. It is my understanding that this will eventually be explained in an upcoming book. Recently published, Sisterhood of Dune is the first in the "Great Schools of Dune" series and explains some of the back-story of the Bene Gesserit sisterhood. Frank Herbert left filing cabinets and boxes of notes devoted to the back-story of the Dune universe, and his son Brian is publishing much of the material. Thanks for your answer. I should really read the newer novels but I hear that they are poor in comparison to the work of his father. I used to read the Dune series every couple of years. I read the 'last' two book when they came out, and haven't had the heart to pick it up since. Not only is the story lack-luster, but the writing is like a primer on how NOT to write a novel. BH and KJA need to take creative writing 101. The second book of the series, Dune Messiah, contains the following passage. This is from the scene where Edric of the Spacing Guild presents Emperor Mua'dib with the Duncan Idaho ghola: The Tleilaxu displayed a disturbing lack of inhibitions in what they created. Unbridled curiosity might guide their actions. They boasted they could make anything from the proper human raw material -- devils or saints. They sold killer-mentats. They'd produced a killer medic, overcoming the Suk inhibitions against the taking of human life to do it. So, although the actual process remains a mystery, it's apparently a guard - either a biological one or psychological - against the taking of human life.
common-pile/stackexchange_filtered
SQLSTATE[HY000]: General error: 1005 Can't create table `test`.`members` (errno: 150 "Foreign key constraint is incorrectly formed") I'm using my migrations in Laravel to create the relationships between tables, and I have 4 tables: users, members, member_skills, and skills. I have the following code for the users table: public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); $table->boolean('admin'); }); } the members table: public function up() { Schema::create('members', function (Blueprint $table) { $table->id(); $table->timestamps(); $table->string('name'); $table->string('status'); $table->date('date')->nullable(); $table->text('project')->nullable(); $table->date('start')->nullable(); $table->foreign('name')->references('name')->on('users'); }); } the member_skills table: public function up() { Schema::create('member_skills', function (Blueprint $table) { $table->id(); $table->timestamps(); $table->string('name'); $table->string('skill'); $table->foreign('name')->references('name')->on('members'); }); } and the skills table: public function up() { Schema::create('skills', function (Blueprint $table) { $table->id(); $table->timestamps(); $table->string('skill'); $table->text('description'); $table->foreign('skill')->references('skill')->on('member_skills'); }); } However, running my migrations results to (errno: 150 "Foreign key constraint is incorrectly formed"). I have read that changing the migration order should fix the problem, so I have arranged the 4 tables to be migrated in the order of users, members, member_skills, and skills, but I am still receiving the same error. Is there anything else I'm doing wrong? I think you should not use name or skill as foreign key references as these entities are not unique. Here is the right way todo this public function up() { Schema::create('members', function (Blueprint $table) { ... $table->unsignedBigInteger('user_id'); $table->foreign('user_id')->references('id')->on('users'); }); } public function up() { Schema::create('member_skills', function (Blueprint $table) { ... $table->unsignedBigInteger('member_id'); $table->foreign('member_id')->references('id')->on('members'); }); } public function up() { Schema::create('skills', function (Blueprint $table) { ... $table->unsignedBigInteger('member_skill_id'); $table->foreign('member_skill_id')->references('id')->on('member_skills'); }); } more:https://laravel.com/docs/8.x/migrations#foreign-key-constraints You should try using the id of the member table as the foreign key rather than the name in the member_skills schema public function up() { Schema::create('member_skills', function (Blueprint $table) { $table->id(); $table->timestamps(); $table->string('member_id'); $table->string('skill'); $table->foreign('member_id')->references('id')->on('members'); }); } You are getting this error because you are trying to reference name in the member table which is already a foreign key to the users table. You can access the name of the member through the id foreign key in your blade.
common-pile/stackexchange_filtered
Two Maven basics / requirements and first project questions I want to use Maven for building my next Java Project. So I have some questions about Maven before starting right off. Does Maven need to be installed? Or can Maven binaries just be copied to a system (Windows) and be used in the same way. Setup a Maven project required? From a Maven tutorial i've seen that the first step in Maven is to setup a Maven project like this: mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false Why is that? Is writing a POM file not enough when I only want to compile some Java files and include some jars? Maven can be installed by simply unzipping the package and place the bin folder on the PATH. What the mvn archetype:generate does is creating a project structure along with the pom.xml. I usually create a maven project through the IDE new project and then maven project, which gives you the opportunity to select the generation as a step of the process. Question 1 (Installation): Well it mostly is simply copy, add to path, and run. However in real world there is a bit more than that. For example, - in a company, you may want to have a company central repository proxy. You will need to do extra set up in either HOME/.m2/settings.xml or MVN_DIR/conf/settings.xml (Wish I remember the path right :P ) You may want to put local repository in a different directory in some case, you will also need to change settings.xml. In order to have building of big project works, you may need to adjust M2_OPTS environment variable. etc... All these things are extra manual installation work you may need (Not difficult though) Question 2 (Archetype): You are actually right. You can simply write your own pom.xml and forget about archetype (That's what I was doing in the past too :) ). You can think Archetype as some template-project-generation feature, so that you may generate some pre-defined project types, and the essential project directory structure, required dependencies and settings in POM are all done for you. Of course you may even provide your own archetype, so new projects in your company can make use of them to conform with guideline or standard you want. Does Maven need to be installed? Or can Maven binaries just be copied to a system (windows) and be used in the same way. Maven comes bundled as a zip archive that you just need to unzip. You then need to add the bin directory to the PATH environment variable and you are good to go. Setup a Maven project required? From a Maven tutorial i've seen that the first step in Maven is to setup a Maven project like this: mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false There are multiple ways to create a Maven project. However, it is important to remember that a Maven project only comes down to having a single pom.xml file. This file will be located at the root of your project. So you are right when you say that "writing a POM file is enough". Now, since Maven is a tool that is built under the convention-over-configuration principle, several utilities have been created to help adhere with the basic conventions of Maven. One of those utilities is the maven-archetype-plugin, which is invoked by the call to mvn archetype:generate. This utility will create a basic pom.xml file along with the standard directory layout. If you are using an IDE, you could also create a Maven project by using the corresponding Maven plugin of this IDE (for example for Eclipse, this is the M2Eclipse plugin). Answer to 1st question: Maven is available in distributed binary format.You just have to download it and extract it in your local machine. And then, you have to create one user variable named M2_HOME(sometime M2_OPTS is also required) and add it to PATH variable. That's all you need to set up basic needs. If your system is inside some proxy network then you have to perform one additional settings. That is to copy secuirity xml, which is available inside the downloaded files, and modify the elements values inside it according to your network. Answer to 1st question: For the 1st time you need to use the command you specified. Once you get the file-structure, you may reuse it based on your need. But remember to follow predefined file-structure else you would be surely in a trouble. However,it's always advisable to create the projects using maven command as it would do many things for you which you might have to do manually if you opt for manual maven project creation.
common-pile/stackexchange_filtered
Paypal sandbox account approver url only showing one option? When redirecting to paypal approval url, I am only seeing one option i.e. return to merchant. I am using my sandbox account. The link "return to merchant" is redircting to my cancel_url instead of return_url. Please help. I am using paypal rest sdk . I have zero balance in my paypal account. can you paste the JSON request/response? I was able to make paypal working by using django-paypal. when redirecting to approval url , I get above page and url says expresscheckout generic error: https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-25T0801620213664S#/checkout/genericError?code=VU5TVVBQT1JURURfUEFZRUVfQ1VSUkVOQ1k%3D It's going to be hard to debug unless it's clear what request is being logged can that genericError code give you some hint what caused this ? usually every errorCode gives you exact error cause in api development.
common-pile/stackexchange_filtered
Example of a locally finite graph without a uniform degree bound We call an infinite graph locally finite if every vertex of it is of finite degree. A locally finite graph is said to have a uniform degree bound if the degree of every vertex of it is bounded by some fixed positive number, say $D$. Clearly the number of self-avoiding paths of length $n$ starting at any vertex of such a graph is at most $D^n$. Let us say that a locally finite graph satisfies the bounded connective constant property at a given vertex if for any $n$ the number of self-avoiding paths of length $n$ starting at the given vertex of a locally finite graph is at most $D^n$ for some $D>0$. I am looking for examples of infinite graphs which are locally finite but without a uniform degree bound, such that, if $N_{n,v}$ denotes the number of self-avoiding paths of length $n$ starting at vertex $v$, then for every $v$, $\limsup\limits_{n\to\infty}(N_{n,v})^\frac{1}{n}<\infty$. Loosely speaking, I am looking for examples of locally finite graphs which satisfy the bounded connective constant property at every vertex (in a slightly generalized way), but don't have a uniform degree bound. Any help will be highly appreciated. Also, I am specifically looking for graphs which are connected. Consider any infinite disjoint union of finite cliques of unbounded size. If you don't require the graph to be connected it's easy, take one star of each positive integer size (For every $v$ there are no self-avoiding paths of large lengths). If it must be connected just connect the centers of the start, each with the next. Explicitly the set of vertices is $(i,j)$ with $j\leq i$ and $i\in \mathbb Z^+$, and only take edges $(a,0) \sim (a,i)$ and $(a,0)\sim (a\pm 1,0)$. Note that in a self avoiding path all vertices except the first or the last one must be the centers of a star. It follows that the number of such paths is at most something like $2(i+n)^2$ where the initial vertex belongs to the $i'th$ star.
common-pile/stackexchange_filtered
Adding page break to tables in Pages 5.5 In Pages 5.5 on Yosemite how can I add a page break into a table? You can't add a page break within a table. You can provide feedback to Apple regarding this: https://www.apple.com/feedback/pages.html You can make another table by copying your table format and paste another table on to the next page. Then you can continue the information. You can still reference the other table for formulas. Just Figured it out!
common-pile/stackexchange_filtered
Image rotation transparency not persists I am rotating image (PNG) which is transparent using OPENNET CF DLL. But after rotation image 's transparency does not persists. How can I persist transparency or any one or other way I can do?
common-pile/stackexchange_filtered
Why does my mandarin tree (Citrus reticulata) have yellow leaves with speckled bottoms? I just bought a mandarin, variety 'nova'. I'm not sure if it's healthy or not, or if it's meant to be like this. It has plenty of new growth but all leaves including new growth are yellow, and the bottoms of the leaves have speckles on them. The tops have slight green in the middle that resembles some kind of deficiency. Other than this is seems to be fine, it's not dropping leaves or anything, so I'm not sure if it has a problem or not. I have a pomelo and it's green so wasn't sure if this mandarin is supposed to be like this or not. Click on pictures for full size. Well we have a happy ending, no idea what the place I bought it off did with it, as after a few weeks of fertilisation and re potting it in an air pruning pot it's sending out loooooads of new growth and the leaves look a more normal colour. The tree was rather tight in the pot, I won't say it was pot bound as it was in a type of air pot so the root ball is very very dense, but the root ball probably made up the vast majority of the pot so there was little soil left to absorb nutrients from. It's now looking a lot happier. ** ** My gut feeling would be spider mites, but I can't say for sure. In short, no, a citrus shouldn't look like this. The pale areas with darker veins are chlorosis, which can either be a sign of a mineral deficiency, trouble with the root system or drainage or even a reaction to a pesticide / herbicide. The latter could mean your supplier noticed an infestation of some sort and treated them. So for now, get your gardening gloves, secateurs and a magnifying lens and check your tree carefully: Insects, especially spider mites Are there tiny crawling insects? Possibly red, but white-is or brown is also frequent. Any small webbed areas, especially at the top and bottom of the leaf stems, along the middle vein or branch forks? Root system Lift the tree out of its pot and check the roots. Remove anything that looks mushy, moldy or otherwise damaged and ensure proper drainage. Did it look like this when you bought it? If yes, have you contacted your retailer? (I'd try to return it and probably think twice before shopping thete again.) Iv got a high powered microscope I use for microelectronics repairs so il pull a few leaves off tomorrow and take a look. The retailer said that mandarins tend to be lighter but to send them some photos so Iv done that and we'll see. Iv got a large air pruning pot that I was going to use for my mango so might just use it for the citrus if the roots look bad. It was the roots that I thought were rather odd. By the way u forgot to mention it came to me in a big box with straw in it, so I'm not sure if it has harvest mite damage. I may be onto something here, look at this https://www.google.co.uk/search?q=harvest+mite+damage&ie=UTF-8&oe=UTF-8&hl=en-gb&client=safari#imgrc=5D6nzDTDH0dpdM: As it came shipped in straw Iv just bought a greenhouse bug bomb that claims to kill spider mites, so il drop that in there and retreat to a safe distance and let them bake in there for a while, if there are any mites in there it should hopefully kill them. @IainSimpson No, not harvest mites (they would bite you or your pets, not your plants), but spider mites. Stephie has a nice answer, but I want to stress out that the yellow leaves is the primary problem. A weak plant will attract and suffer more from other diseases (in this case the spider mites). Try to fertilise the plant. Take into account the pH when choosing fertiliser and new soil. Extra care if you have calcareous water. Iv just had about 6 leaves from new shoots to old leaves under the microscope, and can't see any signs of life on any of the leaves, on the surface or under it. The blotches seem to be collections of dark cells under the surface, some swelling to the surface layer. No that looks more like burnt / fungus, the dark cells are under the surface but can't be seen from the top of the leaf, only the bottom. are they fussy about ph ?, as the water is rather Limey round here. Thanks, it's not in the ground it's in a pot, Iv only watered it once and had it about a week. Il re pot it next week into this air pruning pot I have with some ericaceous compost and perlite / sand mix and see how it goes, it may be pot bound as far as I know as not checked yet. It's exactly the same as it was on arrival, other than watering it once Iv not done anything.
common-pile/stackexchange_filtered
Center an element in middle on screen for an horizontal scroll list I'm attempting to have the element clicked being positioned automatically at the center of the screen. The list is having a horizontal scroll with some overflow-x : scroll which is hiding what's outside of the div(screen). I can't find out what coordinates to pass to scrollLeft(). $('#timepicker li').on('click',function(){ var maxScrollLeft= $("#timepicker").scrollLeft('#timepicker').prop('scrollWidth') - $("#timepicker").width(); $('#timepicker').animate({ scrollLeft: }); }); Please see my codepen: codepen thank you. try this $('#timepicker li').on('click',function(){ var pos=$(this).position().left; //get left position of li var currentscroll=$("#timepicker").scrollLeft(); // get current scroll position var divwidth=$("#timepicker").width(); //get div width pos=(pos+currentscroll)-(divwidth/2); // for center position if you want adjust then change this $('#timepicker').animate({ scrollLeft: pos }); }); Its a little tricky, but here's the solution. var left = $(this).offset().left var width = $("#timepicker").width(); var diff = left - width/2 $("#timepicker").scrollLeft($("#timepicker").scrollLeft()+diff) Basically what i've done is get the present left position of the clicked element and divide it with half of the width of the container. This gives the difference which the scroller has to move in order to take the elment to the middle. Hope you understood the logic. Here's the codepen attached http://codepen.io/prajnavantha/pen/eNwWgx You can copy paste this in the code pen click handler and see it working. thk it helps on the logic
common-pile/stackexchange_filtered
How to add a ripple effect to my custom view drawn element? I am trying to add click ripple effect to my custom view element. It is kind of a progress indicator with several circles. Circles are clickable. So I want to add ripple effect to the circle which user clicks. The ripple effect has to be bounded by circle radius. I cannot find any tutorial how can I do it. Whole widget drawn programmatically. It isn't a compound view. looks like those circles are small enough that your finger would cover them completely while pressing them, effectively preventing you from seeing the ripple I am interested in the opportunity to make such effect. @DanMan check my answer here https://stackoverflow.com/a/73571189/4288054 How to draw ripple effect on any custom view
common-pile/stackexchange_filtered
Problem on a Bilinear pairing This is a problem from hatcher's that I am trying to solve. Show that a nonsingular symmetric or skew-symmetric bilinear pairing over a field $F$, of the form $F^n\times F^n\rightarrow F$, cannot be identically zero when restricted to all pairs of vectors $v,w$ in a $k$-dimensional subspace $V\subset F^n$ if $k>n/2$. I am fairly rusty with linear algebra and don't know much about bilinear pairing barring the definitions. Could someone give me a hint on how to proceed. I would be most grateful. Hint: consider the case where the form is identically zero on $V$, then consider the implications for the rank of the matrix used to represent your (non-degenerate) form. @user8675309 Thanks a lot!! makes perfect sense. Just to be sure. We choose a basis for V. and extend the basis to a basis for $F^n$. We make the matrix of the form with respect to this basis. once we do that we check the rank turns out to be smaller than n which is impossible since it is nondegenerate. Is that correct? @user8675309 could you please explain how you got that inequality? Thanks. Let $\langle x, x'\rangle$ denote the symmetric or skew symmetric bilinear form for $x,x' \in \mathbb F^n$. which is your vector space. The form is stated to be non-singular (non-degenerate) so there is no non-zero vector that is orthogonal to all other vectors under your bilinear form. (I.e. the only null vector is the zero vector.) Let $W$ denote a subspace where the form is identically zero, i.e. $\langle w, w'\rangle= 0$ for all $w,w'\in W$. Suppose for contradiction that $\dim W = k \gt \frac{n}{2}$. Now build a bases for $W$ and extend to a basis for the vector space. I.e. we have $\mathbf B =\bigg[\begin{array}{c|c|c|c|c|c|c|c}w_1 & \cdots &w_k& b_{k+1}&\cdots &b_n \end{array}\bigg]=\bigg[\begin{array}{c|c|c|c|c|c|c|c}b_1 & \cdots &b_k& b_{k+1}&\cdots &b_n \end{array}\bigg]$ Define $A$ such that $a_{i,j}:=\langle b_i, b_j\rangle$. Note: if this were an inner product we would call $A$ a Gram Matrix. Then $A= \left[\begin{matrix}\mathbf 0_{k\times k} & *\\* & *\end{matrix}\right]=\left[\begin{matrix}\mathbf 0_{k\times k} & *\\\mathbf 0 & \mathbf 0\end{matrix}\right]+\left[\begin{matrix}\mathbf 0_{k\times k} & \mathbf 0\\* & *\end{matrix}\right]$ $\text{rank}\Big(A\Big)=\text{rank}\left(\left[\begin{matrix}\mathbf 0_{k\times k} & *\\\mathbf 0 & \mathbf 0\end{matrix}\right]+\left[\begin{matrix}\mathbf 0_{k\times k} & \mathbf 0\\* & *\end{matrix}\right]\right) $ $\leq \text{rank}\left(\left[\begin{matrix}\mathbf 0_{k\times k} & *\\\mathbf 0 & \mathbf 0\end{matrix}\right]\right)+ \text{rank}\left(\left[\begin{matrix}\mathbf 0_{k\times k} & \mathbf 0\\* & *\end{matrix}\right]\right) $ $\leq \big(n-k\big)+\big(n-k\big)$ $\lt \big(n-\frac{n}{2}\big)+\big(n-\frac{n}{2}\big)$ $=n$ justification: sub-additivity of rank and the fact that $\left[\begin{matrix}\mathbf 0_{k\times k} & *\\\mathbf 0 & \mathbf 0\end{matrix}\right]$ has at most $n-k$ non-zero columns and $\left[\begin{matrix}\mathbf 0_{k\times k} & \mathbf 0\\* & *\end{matrix}\right]$ has at most $n-k$ non-zero rows. $\text{rank}\Big(A\Big)\lt n \implies \dim \ker A \geq 1$ by rank-nullity. Thus there is some $\mathbf x \neq \mathbf 0$ such that $\mathbf 0 = A\mathbf x$ but looking at the $i$th component shows $0=\langle b_i, \sum_{j=1}^n x_j \cdot b_j\rangle$ and $\big(\sum_{j=1}^n x_j \cdot b_j\big) \neq 0$ by linear independence of basis elements, yet since this holds for all $i$, then $\big(\sum_{j=1}^n x_j \cdot b_j\big)$ is a null vector and we conclude the form is degenerate, a contradiction. alternative proof: the form $\langle , \rangle$ is totally isotropic on subspace $W$ where $\dim W=k$. Then $W\subseteq W^\perp$ (orthogonal complement) so $2\cdot k = 2\cdot\dim W \leq \dim W+\dim W^\perp = \dim \mathbb F^n=n\implies k\leq \frac{n}{2}$ (note: skew symmetry/symmetry isn't strictly needed here though without it we would need to run the argument separately for a right orthogonal complement and left orthogonal complement which is cumbersome) The key result that $ \dim W+\dim W^\perp = n$ holds for any subspace $W$ of an $n$ dimensional vector space equipped with a non-degenerate (skew) symmetric bilinear form. Proof: using $\mathbf B$ and $A$ as above, and $ P:=\left[\begin{matrix}I_{k} & \mathbf 0_{k\times n-k}\end{matrix}\right]$ (i.e first $k$ columns are the $k$ dimensional std basis vectors, followed by $n-k$ zero vectors) $n = \text{rank}\big(P\big) + \dim \ker\big(P\big) = k + \dim \ker\big(P A\big)=\dim W+\dim W^\perp$ which holds by rank-nullity and the invertibility of $A$ (since the form is non-degenerate) and the fact that building a basis for $\ker PA$ gives all possible elements in $\mathbb F^n$ that annihilate $W$. i.e. mimicking the ending of the above $\mathbf 0 = PA\mathbf x$ but looking at the $i$th component shows $0=\langle b_i, \sum_{j=1}^n x_j \cdot b_j\rangle$ since this holds for all $i\in \big\{1,\dots,k\big\}$ conclude that $\big(\sum_{j=1}^n x_j \cdot b_j\big)\in W^\perp$. Conversely any element $\in W^\perp$ may be written as $\big(\sum_{j=1}^n x_j \cdot b_j\big)\implies \mathbf x \in \ker PA$. Thanks a lot. The trick of breaking the matrix is really clever. So did we not require the bilinear form to be symmetric or skew-symmetric? for avoidance of doubt, the bilinear form does not need to be symmetric or skew-symmetric.
common-pile/stackexchange_filtered
SDL2 - show overlay on mouse motion and hide it some time after mouse stopped As the title says I'm trying to accomplish an overlay menu in my SDL2 application. I have a window where I want to show an overlay menu if the mouse starts moving and show it as long the mouse moves. If the mouse stops moving a timer should start with a specific timeout and should hide the menu after the timeout has passed. I tried using mouse events like SDL_MOUSEMOTION, but that doesn't work. I would rather need something like "mouse motion stopped" events, where I then would start the timer. I then thought I could combine SDL_MOUSEMOTION with SDL_GetRelativeMouseState() and compare the mouse position deltas and start the timer if the deltas are 0. But that kind of seems too complicated. Is the latter the way to go, or is there a simpler way? There are several ways you could approach this: SDL doesn't send 'mouse motion stopped' events but conceptually, a 'mouse motion stopped' event is a frame where you haven't received a mouse motion event. If you have a frame update loop, keep track of whether you've received a mouse motion event in the previous frame and update your menu timer accordingly. Simply reset your menu's timer every time you receive a SDL_MouseMotion event. It's not elegant but it should work. Run the menu timer as soon as you receive the first motion event and just reset the timer each time you receive a subsequent one until it expires and you hide the menu. Thanks! I like both ideas. I'll try out which is more handy to use and extend.
common-pile/stackexchange_filtered
Why is string.Empty more recommended than ""? Why is string.Empty more recommended than ""? Is it because when the compiler is parsing the code and a " comes, the compiler will get ready to read a string? but in string.Empty the compiler will not even get ready to read a string? Which language are we talking about? c#: http://blogs.msdn.com/b/brada/archive/2003/04/22/49997.aspx. "" creates an object while String.Empty references an existing object. what would happen if "" no longer defines an empty string!! And you can reference the Jon Skeet answer here: http://stackoverflow.com/questions/263191/in-c-should-i-use-string-empty-or-string-empty-or/263257#263257 @Joe, strings are immutable in C#. Once its an empty string, its always an empty string. Ya I know that :) it was more of like why in C do we use NULL instead of 0 or ((void*)0). The benefits of string.Empty are rather low but I do use it myself. I see what you're saying @benjynito: You link to an article from 2003 before the literal "" was interned. That is no longer the case: all uses of "" point to the same object, so there is no difference. Possible duplicate of What is the difference between String.Empty and "" (empty string)? Possible duplicate of In C#, should I use string.Empty or String.Empty or "" to intitialize a string? There's another reason. Constants, because of their nature, are a Statics are references to single instances shared by all threads in some application domain, while a literal would end up in producing N instances of an empty string. That's why the string.Empty constant read-only field is recommended over using the empty "" string literal, and obviously, as others have said, it increases readability. Anyway, string interning should be taken in account, because under some conditions it might happen that two or more literals containing the same string could end up in a single instance (see remarks section on String.IsInterned docs): The common language runtime automatically maintains a table, called the intern pool, which contains a single instance of each unique literal string constant declared in a program, as well as any unique instance of String you add programmatically by calling the Intern method. Since Console.WriteLine(ReferenceEquals("", string.Empty)); returns true, I would suggest your edit is highly significant, and indeed shows that this answer is incorrect. And furthermore, string.Empty is NOT a constant, whereas "" IS a constant - the opposite of what you are saying. Try doing const string x = string.Empty; and you'll get a compile error The expression being assigned to 'x' must be constant. If you do const string x = ""; then you won't get an error. @MatthewWatson Actually it's an answer from a long time ago. And you're right, it's not a constant but a read-only field... I'm going to fix this answer @MatthewWatson Now I'm at work, and I've tried to fix it quickly. BTW, do you find it better now? Well, it's better, but I disagree with the basic premise. The ONLY real reason to use string.Empty rather than "" is because you find it more readable (I find it less readable, FWIW). "" will ALWAYS end up with the same reference as string.Empty. @MatthewWatson It's the same issue with if(str?.trim() != "") or if(!string.IsNullOrEmpty(str)), isn't it? You're right that, at the end of the day, it's a matter of taste... There're a lot of examples of our debate. I'm just saying that your statement that a literal would end up in producing N instances of an empty string is not correct. No mater how many literal "" you have in an application, they will all reference the same string.Empty. @MatthewWatson I'm going to completely fix tonight, I can't use more work time for this! :( I wouldn't worry about it too much - it's a really old answer, as you pointed out. @MatthewWatson Meh but it's not about being old or new... StackOverflow is about quality. @MatthewWatson (and, in my case, I don't want to share incorrect info) if you are using "" it can be easily mistaken with " " so to increase readability String.Empty; can be used That's why I never write lower case "l" or UpperCase "I" in my code and always use StringHelper.LowerCaseL and StringHelper.LowerCasei No, it most certainly isn't the right answer. You don't mention a language, so let me guess some stuff here: String.Empty is a constant defined on class string. "" is a string literal for the empty string. Now, if you are doing equality comparisons, then you want to be sure you're talking about the same object, right? Does your language guarantee that "" and string.empty compare equal? This could also be a question of the runtime. I think the term you want to google is string interning. If you have that, then it doesn't really matter which one you use. If you don't, well, subtle errors will occur. EDIT: I see you are talking about c#. That does have string interning, so it doesn't really matter which one you use. This is just a matter of style. I believe low-level details aren't a good argument. I tend to take high-level facts, since I'm using a very high-level language such as C#. And in terms of code compilation, there's a great difference: string.Empty won't be compiling N times same "" string, although run-time low-level details such as string interning would optimize that. It's basically like a constant value for empty that's more human readable. Readability for most cases is highly subjective metric. E.g. - I prefer "". @Armis L. but coding standards are the definition of "code readability". We can argue string.Empty is better than "" or whatever, but if we need to follow coding standards, you'll be using string.Empty, fact that's going to increase your code readability because your code will be predictable. What do you think? :D
common-pile/stackexchange_filtered
How to troubleshoot a water cooling kit or system? I purchased and installed a "Thermaltake Pacific RL120 Water Cooling Kit" in my computer, and it worked perfectly fine for past 6 months. Just few days ago though, my computer overheated and turned itself off. I realized that there was air in the pipes that may have caused water to not pump properly and therefore the overheating the system. I filled more liquid to get rid of air, and in the process found out that one of the pipe was loose. I drained the water loop and redid the entire loop (this time everything is perfectly fit). Now, when I turn on the power the water won't pump back up to the CPU. I left it running on only for few minutes but the water won't move at all. Before I go around replacing parts, I wanted to know proper way to troubleshoot such problem. If you guys can give me some suggestions, that will be awesome! I haven't contacted Thermaltake, I believe either I am doing something wrong or the Thermeltake Pacific PR15, because as I understand that is the pump and if that doesn't work, water won't pump up. I have images available, but cannot attach them yet (due to my rep). does the pump actually run? Anything mechanical should have SOME vibrations. I can't tell. I don't think so. I have tried different ports on my motherboard to power it, but none of them seem to work.
common-pile/stackexchange_filtered
Error "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index" I tried the script by changing for (int ii = 0; ii < i_f.Length; ii++) into for (int ii = 0; ii < 100; ii++) but I still got the same error Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index float[][] b = Enumerable.Range(0, 1143600).Select(j => new float[100]).ToArray(); float[] i_f = new float[100]; List<float> storerandomvalues = new List<float>(100); public float Error(int itemid) { float error= 0f; float[] i_f = b[itemid]; for (int ii = 0; ii < i_f.Length; ii++) { error += storerandomvalues[ii] * i_f[ii]; //error line } error = 1-error; return error; } possible duplicate of "Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index" If you really want to use that indexer then just turn that list into an array.don't use list I posted by myself. That one is completely different @Alexander No, that is exatcly the same. storerandomvalues[ii] --> that is error, collection length is smaller than that iteration No @Selman22. During that one,I just create a list and fill it with random numbers.Now , I must to multiply that list with an array (like matrix multiplication) ans save the result in error.By the way, if I want to define public array for that one instead of list "var storerandomvalues = new int[100];" it shows an error about var (it can not define as public vaiable) It doesn't look like you added anything to the storerandomvalues list, you just initialized its capacity. The List(int) constructor does not add anything to the list, it just makes the backing storage large enough to hold 100 items. If you want to initialize something to a fixed number of items, you really should be using an array, not a list: float[] storerandomvalues = new float[100]; Alternatively, you should adjust your loop condition so that it checks the length of both storerandomvalues and i_f so that the index can't wander out of range of either of them.
common-pile/stackexchange_filtered
How to determine when a item in a WebView is clicked? Is there anyway to determine when a item inside of a WebView is clicked? Such as another link in a WebView. I want to listen for these clicks and repsond to them. is there anyway to go about doing this? Call javascript onClick function and from there you can call java object which you passed using addJavaScriptInterface. This link might help. Copied it from the link: <input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" /> <script type="text/javascript"> function showAndroidToast(toast) { Android.showToast(toast); } </script> and Android is an object passed by writing following lines WebView webView = (WebView) findViewById(R.id.webview); webView.addJavascriptInterface(new JavaScriptInterface(this), "Android"); Hope this help!!! Check out the WebViews addJavascriptInterface(mHandler, "testhandler"); mHandler is a plain class that you can define to handle calls from the javascript. Check out this link for more info.
common-pile/stackexchange_filtered
jquery datepicker validation returns allocation size overload error i am making a Birth Date input with a jquery datepicker plugin. the plugin works but i wanted to validate that only people with 18 years old birthdate will be allowed. i have tried restricting the year but i am having an error allocation size overload and its referring to the year. here is my code: $(function() { var dateNow = ($.now() - 18); $( "#birthdate" ).datepicker({ yearRange: "1920:" + dateNow, changeMonth: true, changeYear: true, dateFormat: 'yy-mm-dd' }); }); If you have to check this after user enters the date, use the following snippet. Demo Fiddle. $(function() { $('#birthdate').datepicker({ changeMonth: true, maxDate: '0',changeYear: true, yearRange: '1900:2014', dateFormat: 'dd-mm-yy', onClose: function(){ var today = new Date(), birthday = $('#birthdate').datepicker("getDate"), age = ( (today.getMonth() > birthday.getMonth()) || (today.getMonth() == birthday.getMonth() && today.getDate() >= birthday.getDate()) ) ? today.getFullYear() - birthday.getFullYear() : today.getFullYear() - birthday.getFullYear()-1; if(age>=18){ alert('18+'); }else{ alert('not 18'); } } }); }); If you wish to restrict the users below 18, change yearRange attribute of .datepicker() Demo For this. this code is well and good but i wanted to restrict the user's option of the drop downs of the date so that they wont be able to pick less than the age permitted. Try something like: $(function() { var now = new Date(); now.setFullYear(now.getFullYear() - 18); $( "#birthdate" ).datepicker({ yearRange: "1920:" + now.getFullYear(), changeMonth: true, changeYear: true, dateFormat: 'yy-mm-dd' }); }); That was just an idea to work with. Try the variation to fit the whole. try this. it should sort you out.
common-pile/stackexchange_filtered
Sum multiple values from multiple tables I'd like to do an SQL query to get a sum number, but i don't know how to construct this query. select count(*) from table1 where commom_fk in (1234); select count(*) from table2 where commom_fk in (1234); select count(*) from table3 where commom_fk in (1234); select count(*) from table4 where commom_fk in (1234); select count(*) from table5 where commom_fk in (1234); I wanna to sum these results in just one query, is that a way to do this? Thank you all. -----* This was answered. But if i wanna to do this with more than one common_fk? SELECT ( SELECT ...) + ( SELECT ...) + ( SELECT ...) + ( SELECT ...) + ( SELECT ...) AS sumAll or to have all 5 results: SELECT ( SELECT ...) AS sum1 , ( SELECT ...) AS sum2 , ( SELECT ...) AS sum3 , ( SELECT ...) AS sum4 , ( SELECT ...) AS sum5
common-pile/stackexchange_filtered
Connection string for multiple deployments I am building a .NET 4.0 C# application which connects to a web service, pulls some data, then inserts it into a database. This application is being designed to require no user input as it will be scheduled to run daily. When I deploy this application to our customers, I run into a problem. Some of them are using SQL Server for their back-end and some are using MS Access. The only solution that I can come up with is to pass the connection string as a command line parameter, but I don't prefer that method. Since I have to deploy this to over 70 different customers, I would rather not compile a copy of the program for each customer. Any thoughts and ideas are appreciated. Put it in the app.config file. Is it a windows service? Put the connection string in the app.config file I thought I had read that using app.config was an outdated way of doing things. You can have the connection string in the App.config file. During the application deployment you can check the user machine whether SQL Server is installed by querying registery. based on the this result update app config with database specific connection string. App.config <?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <add key="DbConnectionString" value="Will be updated during deployment" /> </appSettings> </configuration> Updating connection string in app.config: Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); configuration.AppSettings.Settings["DbConnectionString"].Value = "DB Specific Connection string"; //Save only the modified section of the config configuration.Save(ConfigurationSaveMode.Modified); //Refresh the appSettings section to reflect updated configurations ConfigurationManager.RefreshSection(Constants.AppSettingsNode); Won't I have to hard-code the connection string into my application then? Where would I be getting the connection string from? @DoubleJ92 you dont have to hardcode it. Read it from App config file. See the edited answer. I must be missing something then. The initial value of DbConnectionString is "Will be updated during deployment" When the program runs, that value gets updated to the actual connection string. Where does that come from? @DoubleJ92 Yes, It will be empty in when you deploy. During the deployment based on the DB type you should update the connection string. thereafter your application will read the DB specific connection string. @DoubleJ92 Yes, DB specific connection string should be kept as constant or in resource file. I'm doing the same for my project and it works fine.
common-pile/stackexchange_filtered
How to use Bcrypt in Postman pre-request script? CryptoJS doesn't support Bcrypt, what can I do to use Bcrypt in Postman pre-request script? An alternate way is to create separate api uses Bcrypt and call it from pre-request script. Thank you for the suggestion, I was thinking on doing that with a local service, but figured out that there should be another way because I plan on share this with a team, so it will be troublesome for them to setup servers just for bcypt usage
common-pile/stackexchange_filtered
Pandas: How to pad value for every row that missing years I have a table contains keyword and its occurrence on each year, but if it doesn't occur in some years, those years are missing. But I need to pad those years with zero now, how can I do it with Pandas dataframe? My data is like the table below, each keyword should be padded zero up to 13 years from 2003 to 2015. +---------+------+-------+ | keyword | year | count | +---------+------+-------+ | a | 2003 | 1 | | a | 2004 | 2 | | b | 2003 | 1 | | b | 2005 | 2 | +---------+------+-------+ Desired result: +---------+------+-------+ | keyword | year | count | +---------+------+-------+ | a | 2003 | 1 | | a | 2004 | 2 | | a | 2005 | 0 | | a | 2006 | 0 | | a | 2007 | 0 | | a | 2008 | 0 | | a | 2009 | 0 | | a | 2010 | 0 | | a | 2011 | 0 | | a | 2012 | 0 | | a | 2013 | 0 | | a | 2014 | 0 | | a | 2015 | 0 | | b | 2003 | 1 | | b | 2004 | 0 | | b | 2005 | 2 | | b | 2006 | 0 | | ... | ... | ... | +---------+------+-------+ How can I do this? I have searched StackOverflow and only find the answers on non-repeating date, but here my years are repeating. Have you checked this post ? You can create new MultiIndex by MultiIndex.from_product, then convert columns to MultiIndex by DataFrame.set_index and DataFrame.reindex: mux = pd.MultiIndex.from_product([df['keyword'].unique(), np.arange(2003, 2016)], names=['keyword','year']) df = df.set_index(['keyword','year']).reindex(mux, fill_value=0).reset_index() print (df) keyword year count 0 a 2003 1 1 a 2004 2 2 a 2005 0 3 a 2006 0 4 a 2007 0 5 a 2008 0 6 a 2009 0 7 a 2010 0 8 a 2011 0 9 a 2012 0 10 a 2013 0 11 a 2014 0 12 a 2015 0 13 b 2003 1 14 b 2004 0 15 b 2005 2 16 b 2006 0 17 b 2007 0 18 b 2008 0 19 b 2009 0 20 b 2010 0 21 b 2011 0 22 b 2012 0 23 b 2013 0 24 b 2014 0 25 b 2015 0 Another solution is create new DataFrame by itertools.product and DataFrame.merge with left join, last repalce missing values by DataFrame.fillna: from itertools import product df1 = pd.DataFrame(list(product(df['keyword'].unique(), np.arange(2003, 2016))), columns=['keyword','year']) df = df1.merge(df, how='left').fillna({'count':0}, downcast='int') @yatu - Thank you.
common-pile/stackexchange_filtered
Create a nested objects from for-comprehension in Scala I have a case class being instantiated based on some DB operations: case class FullFight(fight: FightsRow, firstBoxer: BoxersRow, secondBoxer: BoxersRow, bookiesOdds: Seq[BookiesOddsRow]) val tupledJoin = for { f <- Fights b1 <- Boxers if f.firstBoxerId === b1.id b2 <- Boxers if f.secondBoxerId === b2.id } yield (f, b1, b2) db.run(tupledJoin.result).map(_.map(FullFight.tupled)) The problem is that I would not like to specify any bookiesOdds in this query (they are filled in some other query). Instead I would like to create a tuple tupledJoin containing an empty sequence of Seq[BookiesOddsRow] to create my case class' object. Is there any way of mixing that in a for-comprehension loop? I suppose I need something like that: val seq: Seq[BookiesOddsRow] = Nil val tupledJoin = for { f <- Fights b1 <- Boxers if f.firstBoxerId === b1.id b2 <- Boxers if f.secondBoxerId === b2.id } yield (f, b1, b2, seq) Is this possible? How to implement it correctly? Best Regards Your last snippet seems to be doing exactly what you describer. What's the problem? I got the error not enough arguments for method map: (implicit shape: slick.lifted.Shape[_ <: slick.lifted.FlatShapeLevel, (models.Tables.Fights, models.Tables.Boxers, models.Tables.Boxers, Seq[models.Tables.BookiesOddsRow]), T, G])slick.lifted.Query[G,T,Seq]. Unspecified value parameter shape. I don't see anything to do with slick in your snippet. Your question must have to do with some specifics of slick, but you haven't posted nearly enough details to identify that problem. I can tell you that there is absolutely nothing wrong with the for-comprehension snippet you posted. Strange thing is that when I use yield (f, b1, b2, 5L) with the last static value - it works. I think you can only use DB actions in the for comprehension. You could try this (not tested): val tupledJoin = for { f <- Fights b1 <- Boxers if f.firstBoxerId === b1.id b2 <- Boxers if f.secondBoxerId === b2.id bookiesOdds <- DBIOAction.successful(Seq()) } yield (f, b1, b2, bookiesOdds) You are right! I needed to convert my Query to Action and then make any map changes with it.
common-pile/stackexchange_filtered
What is ** in C? the * is used for pointers, but what is ** used for? I found this question in a video I was watching on implementing a hash table passed into main as char **argv. Pointer to pointer. Pointers point to stuff. Sometimes that stuff is other pointers. Pointer to pointer. Like array of string in case of argv (no hashtable) or array of arrays and so on. Use optional book about C for more details. A pointer to a pointer. The most common case is int main(int argc, char** argv) Since pointers can point to an array, pointers to pointers are commonly used to arrays of arrays. Also used as function arguments when setting the value of a pointer.
common-pile/stackexchange_filtered
Can i hide the App Icon from the Action Bar in Honeycomb? I am currently planning the honeycomb update for my app and i am wondering how to use the Action Bar correctly. My first question is if it is possible to hide the App-Icon and Title from the Action Bar. And is there any kind of Design guidline for the Honeycomb-UI yet? Yes, you can hide the app icon and title. You can also replace the app icon with a wider logo image for your activity. The app icon/logo at the left is collectively treated as a "home" affordance. You can optionally ask the system to display it as "up." When tapped, this should take the user either to a home/landing page for your app or one level up in the app's navigation hierarchy, respectively. This complements the system back button by providing a consistent way for the user to move around your app when the history associated with the back button might be complex. (For example, the user might have been deep-linked into your app through a notification or an intent from another application.) By using this pattern your app won't need to hijack the normal behavior of the back button in special cases for convenience. The action bar does double duty in the form of action modes. The two APIs are orthogonal but the resulting UI occupies the same screen real estate. An action mode presents a set of contextually relevant options to the user as a customized action bar. For example, a user might select several items from a list at a time. The app might present an action mode to let the user take a bulk action on the set of all selected items such as delete or share. Action modes are a great way to present contextual actions that doesn't stop the user from interacting with the rest of the UI the way that popup menus do. Design guidelines will hopefully be published "soon." :) Waiting for the design guidelines :) yay for impending design guidelines Any chance you could go into greater detail about action modes? Maybe in a blog post or something? Sure, I'll see what I can do. :)
common-pile/stackexchange_filtered
PHP Global Exception handling across all classes In PHP,is there any way to handle exceptions globally using one method? If there is, how could I do that? I want to use the method which handles exception across all classes. The reason that I want to achieve this is I do not want to repeat same code all the time. Here is the example of the exception handling. try { ***SOME CODE TO EXCUTE*** } catch ( Exception $e ) { /* custom function to handle exception */ $msg = exceptionHandler($e); $this->error(0,500, $e->getMessage()); } http://php.net/manual/en/function.set-exception-handler.php Slightly off topic, but if you're using Composer with your project, you could use a library to provide nicer error handling capabilities - such as Whoops
common-pile/stackexchange_filtered
std::vector<> No default constructor exists after using constructor from base class and overloading the derived class I am creating a template class and inheriting std::vector. Along with all the constructors of std::vector, I want to overload the constructor of the derived class with a custom class. However when I do this, I get the compilation error for the default constructor call. Code below: template<typename T, unsigned int N> class _std_vector : public std::vector<T> { public: using std::vector<T>::vector; _std_vector(const MyCustomClass& that) { //Do Something } } And I call as follows: MyCustomClass my; _std_vector<int, 8> sv{ my}; The above works fine the moment I overload the constructor. However the default non parametrized constructor gives compilation error. Error C2512 '_std_vector< int,8>': no appropriate default constructor available _std_vector <int, 8> svv; //This works fine until I add _std_vector(const MyCustomClass& that) However please note, all the other parametrized constructor of std::vector seem to compile fine. Am I missing something here? Just don't inherit from stl::vector or any other standard container. There is never a good reason to do that. Don't inherit from standard containers. Just create a free function std::vector<T> toVector(const MyCustomClass& that) and avoid much trouble However, this question would be valid if it would not be std::vector you are inheriting from. If you are interested in that, you can ask another question or edit this one. I'm voting to close this question as off-topic because OP should not inherit from STL's vector, and there is nothing to debate. @SergeyA That's a poor reason. It doesn't violate any site guide lines and the practice isn't strictly speaking disallowed. And questions shouldn't start a debate, those that do should be closed for being opinion based. @FrançoisAndrieux probably the better closure would be a one of a thousands duplicates which explain why one shouldn't do this. Since I already cast my vote, you can cast a duplicate one. @SergeyA I again disagree. This question isn't asking whether or not inheriting from std::vector is a good idea. The question is asking why the default constructor stops working in this case. It doesn't have anything to do with inheriting standard containers and it's just unfortunate that it's the example that was used to illustrate the question. Links to questions explaining why this inheritance is a bad idea have already been posted and that should be sufficient. Your sample code doesn't fail for the appropriate reason: https://godbolt.org/g/ofDBbV . Shouldn't using std::vector<T>; be using std::vector<T>::vector; If I assume you made a typo and meant using std::vector<T>::vector;, I can't reproduce the compilation error (it compiles fine for me): https://godbolt.org/g/JebZwg @Justin A More complete example: https://godbolt.org/g/hXhGMt (still compiles) @AjayNair Your sample compiles here. Can you post a reproducible [mcve] that fails to compile? @NathanOliver Ah. The code was in multiple places, so I missed that. Yes, this doesn't compile on msvc: https://godbolt.org/g/D8Ns3n Intresting. Clang and GCC are fine. ICC and MSVS both fail. Must be something to do with how they implement vector. Your class name is illegal, see details here https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier FWIW: here is a "better" MCVE: https://godbolt.org/g/EzqHJN
common-pile/stackexchange_filtered
Named Event in Python In python, is there a cross platform way of creating something similar to Windows named Event in one process, and set it from another process to signal something to the first one? My specific problem is that I need to create a process that on startup will check if any other instances of itself are running, and if so, signal them to quit. With Windows API I would use CreateEvent with the lpName parameter, and SetEvent. I've spent about a day now searching for a good answer to this and here is what I am coming up with at this moment: It is possible to use signals to indicate to the process that some change needs to take place, however in a more complex legacy codebase I am dealing with it causes the process to crash. Signaling interrupts various I/O processes and alike based on python signal docs. You can implement signal handler with signal.SIGUSR1 import signal def signal_handler(signum, stack): print('Signal %d received'%signum) signal.signal(signal.SIGUSR1, signal_handler) This code can be triggered in Linux et al. through: $ kill -s SIGUSR1 $pid I am presently leaning towards kazoo Python Zookeeper library. It requires to stand up Zookeeper as infrastructure. I do have an additional need for toggling configuration values in my case. However Zookeeper supports a number of interprocessor communication tools that will serve your needs. UPDATE: I finally settled on a named pipe (FIFO), calling it inside a thread with readline. if not os.path.exists(fifo_name): os.mkfifo(fifo_name) while True: with open(fifo_name, 'r') as config_fifo: line = config_fifo.readline()[:-1] print(line) I used tempfile.gettempdir() to find a good location to place the FIFO in the file system. It requires quite a bit of refinement however, since I did not care to parse passed content while you might. Also if you are planing on having more then one consumer of the event you are going to have it propagated to only one consumer as it is a queue. Another similar solution is to use socket networking in the same way. This can also be cross platform. It seems to me that this is not so much a question as to whether this is possible in Python, but whether such a cross-platform approach exists: if one does, then even if no directly written Python exists, one can always make system calls using subprocess.call() and the like. As for whether it's a possibility, I can't profess to be much of an expert, but a bit of a search has thrown up these discussions which might prove helpful to you. Thanks, but it doesn't really matter to me if the answer will give exact behavior as Windows Events. I only need to be able to signal something to another process which is not a child process (and without tricks like using files, etc.). I guess other OS have features for this.
common-pile/stackexchange_filtered
How to calculate the moment of inertia for 4 welded c beams? I'm trying to figure out if an existing bus shelter can support additional weight on its roof. To do that, I need to figure out the bending moment of it's supporting beams, but I'm stuck on the unusual beam structure it uses. Basically it's 4 welded C beams. I have the engineering drawings for the structure, so I've attached the relevant detail I think. Any help would be appreciated. The quickest way would be to design this in autocad and use the MASSPROP Command, or similar functionality in other drafting software (e.g. Solidworks inventor etc). For the 4 channels assembly, due to symmetry, the neutral axes fall on the centroidal axes x & y. $I_x = \sum (I_i + Ai*d_i^2)$ $I_i$ = moment of inertia of the individual channel with respect to its centroid. You can get it from a steel table. $A_i$ = crossectional area of the individual channel. $d_i$ = distance measured from the centroid of the individual channel to the "x-axis" If needed, do the same for $I_y$. Note: In calculating $I_x$, the $A*d^2$ term for C10 is zero, because the center of the channel is coincident with the neutral (x) axis (d = 0). Suggestion: For a quick feel, you may start with the assumption that only the two C10s contribute to the strength of the beam. Then add C6s only if necessary. For information: The welds are offset on top through unknown members! And 1/4" weld is not enough to develop full tension or compression in channels. @kamran OP is checking on the strength of an "existing" structure that was already been "designed and built". He is only asking how to calculate the member property, not the design.
common-pile/stackexchange_filtered
Session and casting error [Telerik and C#] I don't how to cast this properly and I don't know if I pass it readable by telerik radgrid. Kindly check. I have the following codes: When I try to pass my session to another list type variable, it encountered error. I'm trying to pass session because I Pass it on another aspx. public class Employee { int empID; string employeename; int age; string adress; } List<Employee> Profile = new List<Employee>(); Session["Emp"] = Profile; List<Employee> xdata = new List<Employee>(); xdata = (List<Employee>) Session["Emp"]; Radgrid1.Datasource = xdata; Could you please try with the below code snippet? It might be possible that you have given inbuilt keyword name to variable so it was giving casting error. public class Employee { int empID; string employeename; int age; string adress; } List<Employee> empList = new List<Employee>(); Session["Emp"] = empList; List<Employee> xdata = (List<Employee>) Session["Emp"]; Radgrid1.Datasource = xdata;
common-pile/stackexchange_filtered
Vaadin ServerRPC Exceptionhandling I implemented a custom widget and it does calls via a ServerRPC implementation. This works all good. I wanted to know how I should implement errorhandling, because I need the sent messages to be redelivered in case of an error. I pretty much followed this chapter in the book. Any help is appreciated. What do you mean exactly with the error handling? Like in pure gwt rpc for instance with AsyncCallback, where a onFailure method exists. For instance if the message is not delivered due to network problems.
common-pile/stackexchange_filtered
Anyway to mark my answers as "mis-interpreted question"? Recently, I misinterpreted a question and provided an incorrect solution to a problem. Can, I mark it in any way just like we have "duplicate" questions? I would love to contribute to the community. But, I don't want to contribute poorly. I've misinterpreted a user's question. And, by now he must be irritated of the constant pinging by my edits. I can suggest two ways to handle the case where you misinterpreted the question: Delete your answer. Enough said, no further action needed. Delete your answer. Post a new question, that asks the question you thought you were answering, and post your answer there. How to choose between those two? It might depend, for instance, on whether you expect the alternate question to be useful to others in the future. You might also consider whether it makes sense to edit the question to make it clearer, to help other readers avoid misinterpreting it in the same way you did. You might not be the only one to come away with the wrong impression of what is being asked. So, I don't think we need a way to mark answers as "I misinterpreted the question", and I don't think it would be beneficial. Sometimes, there's a learning opportunity if the same misinterpretation is likely to happen to other readers, and the answer works toward clearing it up in an interesting way. But yes, deleting is the besser way most of the time. @Raphael, I can understand that. Personally, my sense is that in most cases, that kind of information is better as a comment or an edit to the question to clarify what is being asked and innoculate other readers against that misunderstanding, but I can see how it might depend on the situation and how interesting the information is.
common-pile/stackexchange_filtered
Load data from bucket google cloud Here is a function to load data from google cloud bucket. action_dataset_folder_path = 'action-data-set' zip_path = 'actions.zip' url='http://console.cloud.google.com/storage/browser/actions' class LoadProgress(tqdm): last_block = 0 def hook(self, block_num=1, block_size=1, total_size=None): self.total = total_size self.update((block_num - self.last_block) * block_size) self.last_block = block_num if not isfile(zip_path): with LoadProgress(unit='B', unit_scale=True, miniters=1, desc='actions-Dataset') as pbar: urlretrieve( url, zip_path, pbar.hook) if not isdir(action_dataset_folder_path): with tarfile.open(zip_path) as tar: tar.extractall() tar.close() print('All done ...!') The file is downloaded as empty file with 73.7KB! I did not understand! It seems everything is good. Here is the code from google cloud site:python-code from gcloud import storage def download_blob(bucket_name, source_blob_name, destination_file_name): """Downloads a blob from the bucket.""" storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(source_blob_name) blob.download_to_filename(destination_file_name) print('Blob {} downloaded to {}.'.format( source_blob_name, destination_file_name)) download_blob("datset","actions", "dataset") You can retrieve data from Google Cloud Storage by using a GET request. In Python you could do this with the Requests library. First you need to retrieve an auth code (you can test this using OAuth 2.0 Playground) Then you could use something like this to retrieve the data (object): import requests authCode = YOUR_AUTH_CODE auth = "Bearer " + authCode myHeaders = {"Authorization": auth} r = requests.get('https://www.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME', headers=myHeaders) print r.text print r.status_code
common-pile/stackexchange_filtered
Residue fields of gaussian primes I just started with algebraic number theory and need some help: In the ring of Gaussian integers a prime $p$ with $p=1\bmod 4$ splits into a product of two irreducible elements $(a+bi)(a-bi)$, with $a^2+b^2=p$, if $p=3\bmod 4$ then $p$ stays prime in $\mathbb{Z}[i]$ and if $p=2$ then $p$ ramifies as $(1+i)^2$. I wonder how I can see that the different residue fields that you get from the prime ideals generated by the irreducible elements just described have $p$, $p^2$ and $2$ elements respectively. I.e. the norm of the generator gives the size of the field. Why? If $p = 1 \bmod 4$ and $a^2 + b^2 = p$, then $a+bi$ is a factor of $p$, so the ring homomorphism ${\mathbf Z} \rightarrow {\mathbf Z}[i]/(a+bi)$ kills $p$ and thus induces a ring homomorphism $f \colon {\mathbf Z}/(p) \rightarrow {\mathbf Z}[i]/(a+bi)$. It's injective since any ring homomorphism out of a field is injective. The meaty part is showing this is surjective, and for that it's enough to see that $i \equiv c \bmod a+bi$ for an integer $c$. Well, $i \bmod a+bi$ is a square root of $-1$, and $-1$ is a square in ${\mathbf Z}/(p)$ because $p \equiv 1 \bmod 4$. Therefore the image [...] of $f$ includes two square roots of $-1$ inside ${\mathbf Z}[i]/(a+bi)$. Those are the only ones possible because ${\mathbf Z}[i]/(a+bi)$ is a field (the number $a+bi$ is prime in the PID ${\mathbf Z}[i]$, so working mod $a+bi$ is a field). Therefore $i \bmod a+bi$ has to be in the image of $f$, so $f$ is surjective and thus an isomorphism. (Wait, an easier soln: it's easy to solve for $i$ in $a+bi \equiv 0 \bmod a+bi$ because $b$ has an inverse mod $p$.) Thus ${\mathbf Z}[i]/(a+bi)$ has order $p$. The other cases of primes in ${\mathbf Z}[i]$ are simpler. Another way: think about the tower of ideals $(p) \subset (a+bi) \subset {\mathbf Z}[i]$. I hope you can see that $(p)$ has index $p^2$ in ${\mathbf Z}[i]$ (think about what a congruence mod $p{\mathbf Z}[i]$ really means on the real and imaginary parts). Therefore $(a+bi)$ has index 1, $p$, or $p^2$ in ${\mathbf Z}[i]$. Since $a$ and $b$ are not 0, $(a+bi) \not= (p)$. Since $a+bi$ is not a unit (it has norm $p$), $(a+bi) \not= {\mathbf Z}[i]$. So the only choice is for $(a+bi)$ to have index $p$ in ${\mathbf Z}[i]$. @Kcd why is this a comment, and not an answer? @KCd , you should really gather together your comments into one answer...a pity this question will go unanswered when you've done all that writing. Besides the wonderful answer of KCD, we can also avail of the theorem of Dedekind. Also see IV.XXXI. Now we take $f(x)=x^2+1$. If $p\equiv 1\pmod4$, then there is an integer $a$ such that $a^2\equiv -1\pmod p$. So, according to the theorem, $(p)=(p,i-a)(p,i+a)$. Now $\mathbb Z[i]/(p,i-a)\cong (\mathbb Z[i]/(i-a))/(p)\cong \mathbb Z/(p)$, so the residue field in question has $p$ elements. If $p\equiv -1\pmod 4$, then $x^2+1$ is irreducible over $Z/(p)$, so $(p)\mathbb Z[i]=(p,i^2+1)=(p)$, and hence the residue field $\mathbb Z[i]/(p)\cong \mathbb Z[x]/(p,x^2+1)\cong (\mathbb Z/p\mathbb Z)[x]/(x^2+1)$ is an extension of $\mathbb Z/p\mathbb Z$ of degree $2$, namely, it has $p^2$ elements. If $p=2$, then $x^2+1\equiv (x-1)^2\pmod p$, so $(2)=(2,i-1)^2$, and the residue field $\mathbb Z[i]/(2,i-1)\cong \mathbb Z/(2)$ has $2$ elements. Inform me, if the notations are too ambiguous, or if some errors take place here. Thanks for any attention.
common-pile/stackexchange_filtered
Inserting strings into a two-dimensional char array, then printing them with a pointer in C I am a little new to using multi-dimensional arrays, but I think after extensive research, I was starting to feel super confident I could work with them correctly. Apparently, I guess I don't quite know them completely lol. In this case, I am trying to read in all the test files from directory ("path" in this case), insert each "d_name" into its own row of a 2-dimensional char array. I am able to print each string element (filename, in this case) successfully when I use the "[]" array-type notation. However, after I pass a pointer for this 2-dimensional char array into a "readFiles" function, I am able to successfully print out the 1st string of this array, but when I attempt to move the pointer in order to point at the next row (the 2nd string, or filename), I receive unexpected garbage results, eventually ending in a seg fault. So something is wrong with the way I am iterating through an array with multiple rows like this. I REALLY do not wish to print character by character here, I just want to print out 1 string (filename) at a time by simply moving the pointer down 1 row after a string element is printed. Could somebody please help if you can ? I really really appreciate your time on the weekend like this! my program (just a giant function for now)... #include <stdio.h> #include <dirent.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include<unistd.h> #include <stdbool.h> #include <errno.h> #include <sys/types.h> void alphabetcountmulthreads( char *path ) { void readFiles( char **allfiles, int total_rows ) { printf( "The pointer passed into the function is at %p and its first element is...\n", (void *)*allfiles ); for ( int k = 0; k < total_rows; ++k ) { printf( "%s\n", *( allfiles + k ) ); printf( "...which was found at...%p\n", (void *)*(allfiles + k) ); printf( "...because the pointer was added by %d (string should be in row %d )\n", k, k ); } } DIR *dir; struct dirent *in_file; char fileList[100][30]; char *filename_reader = &fileList[0][0]; int filled_rows = 0; int file_count = 0; dir = opendir( path ); // open the data directory if( dir == NULL ) { printf( "Unable to read directory!" ); exit( 1 ); } while( ( in_file = readdir( dir ) ) != NULL ) { FILE *entry_file; char *check_filename; // for checking if file ends EXACTLY with ".txt" int c; check_filename = strrchr( (in_file->d_name), '.' ); // move to last "." if ( !strcmp ( in_file->d_name, "." ) || !strcmp ( in_file->d_name, ".." ) ) { continue; } if ( check_filename ) { if ( strcmp( ( check_filename ) , ".txt" ) ) // does it end in ".txt" ? { continue; } file_count++; int filename_length = strlen( (in_file->d_name) ); // path = "../data" printf( "%s...%d c's long\n", in_file->d_name, filename_length ); strcpy( fileList[filled_rows], (in_file->d_name) ); printf( "The string, %s\n", fileList[filled_rows] ); printf( "had its first character stored at...%p\n", &fileList[filled_rows][0] ); filled_rows++; } } closedir( dir ); fileList[ (filled_rows - 1 + 1) ][0] = '\0'; filename_reader = &fileList[0][0]; char **function_insert1 = &filename_reader; printf( "The actual address of the 2D array is %p\n", (void*)&fileList[0][0] ); printf( "Its pointer's location is at %p\n", filename_reader ); readFiles( function_insert1, filled_rows ); } and here is my output........ test11.txt...10 c's long The string, test11.txt had its first character stored at...0x7fffd2b86180 test10.txt...10 c's long The string, test10.txt had its first character stored at...0x7fffd2b8619e test2.txt...9 c's long The string, test2.txt had its first character stored at...0x7fffd2b861bc test1.txt...9 c's long The string, test1.txt had its first character stored at...0x7fffd2b861da test3.txt...9 c's long The string, test3.txt had its first character stored at...0x7fffd2b861f8 test12.txt...10 c's long The string, test12.txt had its first character stored at...0x7fffd2b86216 test13.txt...10 c's long The string, test13.txt had its first character stored at...0x7fffd2b86234 The actual address of the 2D array is 0x7fffd2b86180 Its pointer's location is at 0x7fffd2b86180 The pointer passed into the function is at 0x7fffd2b86180 and its first element is... test11.txt ...which was found at...0x7fffd2b86180 ...because the pointer was added by 0 (string should be in row 0 ) ...which was found at...0x7fffd2b860e0 ...because the pointer was added by 1 (string should be in row 1 ) ...which was found at...0xa5b420 ...because the pointer was added by 2 (string should be in row 2 ) Segmentation faultSegmentation fault char fileList[100][30]; char (*filename_reader)[30] = fileList; and fileList[ (filled_rows - 1 + 1) ][0] = '\0'; is just fileList[filled_rows][0] = 0; You may want to read Difference between char pp and (char) p? and Pointer to pointer of structs indexing out of bounds(?)... Also, always compile with warnings enabled, and do not accept code until it compiles without warning. To enable warnings add -Wall -Wextra -pedantic to your gcc/clang compile string (also consider adding -Wshadow to warn on shadowed variables). For VS (cl.exe on windows), use /W3. All other compilers will have similar options. Read and understand each warning -- then go fix it. That would have identified your pointer mismatch. They will identify any problems, and the exact line on which they occur. You can learn a lot by listening to what your compiler is telling you. Additional 2D array pointer help How to pass a 2D array to a function using single pointer Finally found the exact one I was looking for 2D array seg fault in C Let me know if you have further questions. (your question is more or less a duplicate of this one from the 2D array handling standpoint) Hey David, I really appreciate the time you've taken to respond here. I did not notice elsewhere that sort of notation you mentioned ("char (*filename_reader)[30] = fileList"), but unfortunately, when I try to adapt the program for this, the same problem persists. I just want to be able to move down a whole row at a time...is this not possible? You have other issues, but fileList is a 2D array (an array of 1D arrays). On access, fileList is converted to a pointer to its first element (the first 1D array). So char (*filename_reader)[30] = fileList; declares a pointer-to-array of char[30]. So *filename_reader provides access to the first string, then filename_reader++ will advance the pointer by 30-characters (to your next 1D array) and *filename_reader now provides the 2nd string. Note, since you use an empty-string as a sentinel, you would iterate while(**filename_reader) puts (*filename_reader++); Here is a very minimal example of what you are doing. I uses the 2D array of strings (named strings) and a pointer to the first 1D array in strings (pstring) to iterate over each sting in the 2D array Pointer-to-Array. Note, C doesn't allow nested functions, so I don't know how you are compiling with the declaration for void readFiles() nested in void alphabetcountmulthreads() If you are still stuck, edit and provide A Minimal, Complete, and Verifiable Example (MCVE) and I'm happy to help get you going. David, thank you so much! Within the first main function, the printing of each element with the char (*filename_reader)[30] using the incrementing pointer is working. BUT, I was really hoping you could give me a suggestion as to how I can pass this same pointer to the readFiles function? Preferably it be a double pointer so that this function can manipulate the value of this pointer? Again thank you so much Pointer type controls pointer-arithmetic. You do not have a pointer to another pointer, you have a pointer to array of char[30]. So you will require void readFiles( char (*allfiles)[30], int total_rows ) just as you declared char (*filename_reader)[30] = fileList; in main(). If you pass char** (pointer to pointer), then p++ advances 8-bytes (or 4-bytes on x86) to the next pointer. By passing char (*)[30], then p++ advances 30-bytes to the beginning of the next string (1D array). See 2d to function Let us continue this discussion in chat. Awesome David your code in opensuse helped me a lot! You clearly know all of the ins and outs of C and I can only dream of getting to your level of expertise. My function works now. Hope you have a wonderful rest of your day x) Learning C is more a journey than a race. There is a lot to learn, but you are on the right track. Best advise is to slow down, enjoy the journey and approach it the same way you approach eating a whale -- one byte at a time....
common-pile/stackexchange_filtered
Height in 2D game I'm working on a 2D top-down game (like the picture below) and am wondering what can I do for "jumping" So far, I've done these: adding two events in jumping animation (one for when the enemy is in the air and one for when it's coming back to the ground) the events turn enemy's colliders off and on And it worked well, the enemy dodged the attacks and all but upon more testing, I found out some serious issues: the enemy can pass objects like trees but it shouldn't explosions should affect enemies even if they are on air but without any colliders, it is not possible So what I want to know is how I can add "jumping" to my game? Is there any "standard" way to do this in top-down games? I don't want a piece of code or something like that, just an explanation of how I can achieve this is enough. Thanks in advance! https://docs.unity3d.com/Manual/LayerBasedCollision.html You could make a jump layer that is still affected by things like explosions but turns immun to collision with enemies (since you dont collide with them) and still get stuck against hard objects like trees/ buildings Oh man, that's perfect! I already have my enemies on an enemies layer and have used layer collision matrix but didn't think about adding an enemies_onair layer. thanks for the link! So, the way jumping works in Zelda is kind of unintuitive at first, but if you think about it, it makes a lot of sense. In modern games, sprites and models ARE the game objects, so we've become used to manipulating the thing as a whole whenever we need to do something. But in older games, sprites are only a visual representation of what is going on in the background. Whenever you jump in Zelda, a flag (bool) gets set to indicate that the player is in the air, but the collider isn't affected. Whenever that "in air" flag is set, the player collider simply ignores the effects of other colliders like pits or enemies, but the collider still moves along the ground like normal. While that's happening in the background, the sprite is just being moved up and down in a way that looks like jumping, while still following the position of the collider underneath, but it has no actual impact on what is happening in the background. So, what I'm saying is that you should separate the collider from the sprite, then add your jumping animation to the sprite, and an "in air" bool to your collider interactions. Though depending on how you've set up your code it might be easier to switch the object to a different layer. This is an excellent answer -- multiple colliders is definitely the best solution, IMO too. Actually, I'm doing something similiar to that, the enemies just visualy go up but not the collider. though, I don't think in the Zelda case it's just a simple flag. As I recently re-played it, I found out that it's a bit hard to get flying objects ()like hearts) and needs a presice jump so I guess they used a variable to hold height and gave the objects a height too @ArianKeshvari You could also add another collider that does follow the sprite. For prototyping purposes, you could always use a coroutine. It will get things moving, but I would try to structure your code so physics are in a fixed update, eventually. A coroutine is basically a process that runs on the side. It gives you enough flexibility to get the jump working while you fix your enemies. Be careful with coroutines though, I have seen some get way out of hand. You don't want too many, or too much going on in one. Memory leaks can happen here. This is not how I would handle a jump, but it works. I would consider utilizing a state pattern for your character (even a small pseudo pattern could work.) This is not a terrible approach to a jump, though. I am not in a place where I can test this, so this is just an example off the top of my head to show you what the syntax would look like. void Update(){ HandleInput(this); } private void HandleInput(IControllable controller){ ... if(controller.jump) StartCoroutine(HandleJump()); } // jumpHeightVector is a vector 3 with y being your jump height applied, the rest 0 private Vector3 jumpHeightVector = (0, jumpHeight, 0); // every 10th of a second increments current time by 1 private float jumpInterval = 0.1f; // this would be responsible for a choppy movement [SerializeField] jumpTime; //serialize this to show in inspector private IEnumerator HandleJump(){ // Important: let update know that this method is off limits controller.jump = false; anim.SetBool("jump", true); curJumpTime = 0; while(curJumpTime < jumpTime) { // may need better validation for landing in the right spot if(curJumpTime * 2 < jumpTime) Transform.Translate(jumpHeightVector); // up else Transform.Translate(-jumpHeightVector); // down // this always creates a new wait for seconds, consider assigning one of these in Start() yield return new WaitForSeconds(jumpInterval); curJumpTime++; } anim.SetBool("jump", false); } We have a coroutine that loops through a while loop while current jump time curJumpTime is less than our allowed jump time jumpTime . if we are less than half of the way through our jump, move up. If we are less than half, move down. When our elapsed jump time is equal to our allowed jumptime, we break the while loop. We also set our animation bool (you could even just use anim.Play("jump"). Thanks for the answer and good explanation! But what others mentioned (changing layer) is way easier and, probably, more efficient While it may be easier, I disagree with the latter. Good luck :) Remember that WaitForSeconds resumes on the first frame after that many seconds has elapsed, which could be anywhere from 0 ms to 33 ms later at 30 fps. This will make the jump inconsistent, sometimes running longer or shorter, or looking jerky if different steps in the jump get different delays based on how they mismatch against the frame timings. You'll likely want to use yield return null instead to resume every frame, and use Time.deltaTime to adjust the jump update to match how much time has actually passed, to smoothly match whatever the framerate conditions happen to be.
common-pile/stackexchange_filtered