text
stringlengths
175
47.7k
meta
dict
Q: Eclipse RCP Fragment How to Build library.jar I have a plug-in fragment which contributes a jar file to the host plug-in, following these instructions. It works by creating a file library.jar which is specified in build.properties and associated with a directory which contains the source to be built. It all works as expected, except I can't figure out how to cause library.jar to be created in Eclipse. When I run a Maven build that points to my fragment project and includes it as a module, the file library.jar shows up in the project directory. But building or cleaning the project in eclipse does not create the file. I want other developers to be able to generate library.jar in their Eclipse workspace without running the Maven build. I'm really surprised that the Maven build creates libary.jar in the plug-in project itself, and not just in the product created in the build target. There should be a way to get Eclipse to do this without running the Maven build. EDIT: build.properties: bin.includes = META-INF/,\ library.jar source.library.jar = src/ MANIFEST.MF: Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: Custom Bundle-SymbolicName: org.python.pydev.custom Bundle-Version: 1.0.0.qualifier Fragment-Host: org.python.pydev;bundle-version="5.1.2" Bundle-RequiredExecutionEnvironment: JavaSE-1.8 Eclipse-PatchFragment: true Bundle-ClassPath: library.jar, . Require-Bundle: org.python.pydev.debug;bundle-version="5.5.0", org.eclipse.cdt.debug.core;bundle-version="8.0.0", org.apache.log4j A: Eclipse will build the library.jar rather than putting the class files in the normal place when the build.properties file looks like: bin.includes = META-INF/,\ library.jar source.library.jar = src/ The library.jar entry in the bin.includes replaces the normal . entry. The source.library.jar entry says that the Java files in the src directly should be put in the library.jar. The Bundle-Classpath entry in your MANIFEST.MF should be: Bundle-ClassPath: library.jar (so no '.' entry)
{ "pile_set_name": "StackExchange" }
Q: Linux server compatibility questions I'm replacing an ancient server I have at home. The old machine is currently running Windows 2000 Server edition. It's an Active Directory domain controller, functions as a basic file server, hosts an ASP.Net 2.0 web site (dasBlog), and I occasionally need to remote in to it when visiting places that won't have a vnc client installed other than the windows terminal services rdp client. I'd like to put an operating system on new box that's not almost 10 years old, and so I'm wondering what a linux distro has to offer in the following departments: Can I run dasBlog on mono? Where can I find help setting that up? Is it possible to migrate my Active Directory domain to a linux clone of some kind, such that my wife's laptop doesn't even notice (she won't be happy if I have to mess with it again)? Where should I look for help with that? Can I set up a terminal services/rdp-compatible remote desktop solution? How? How do I set up file shares to replace the existing shares that will work with the defined NT security groups? These shares are currently also available via the web if you know where to go and can log into a domain account with the proper security. How can I replicate that? A: dasBlog on mono - dont think so (third party libraries?) migrate active directory - ive never been able to do this,, but the last time i tried this was about 2 years ago No, RDP is microsofts proprietary protocol. X Server & VNC is all you got. File sharing - Samba will take care of it should be doable, but i think u need to adress #1-4 above first./
{ "pile_set_name": "StackExchange" }
Q: Access instance members through local static instance I have a communication manager who is an instanced by de-serialization. Now I want to create some static methods to access instance data. On other posts i see people be advice not to access static fields of instance objects. But now I create the following code and this work like expected, i can de-serialize and use the static method without a new instance of the CommManager. Great! The question: Is this is approach safe? I want to apply Threading, GetChannel is a core of my application and will be used by many application parts on multiple threads. I find it important that i do not create a performance penalty or into other consequences. Please advice. I ask this cause i find it strange that i cannot find any similar example of this approach, The way i see it now, i can easily make every method static without disadvantages. public class CommManager { public ObservableCollection<ChannelConfig> channelConfigs; private List<iChannel> channels; private static CommManager StaticMe; public CommManager() { channelConfigs.CollectionChanged += ChannelCollectionChanged; StaticMe = this; } private void ChannelCollectionChanged(object sender, NotifyCollectionChangedEventArgs args) { if (channels == null) channels = new List<iChannel>(); switch (args.Action) { case NotifyCollectionChangedAction.Add: foreach (ChannelConfig newItem in args.NewItems) channels.Add(CreateChannel(newItem)); break; case Notif.. /// etc. etc. } } /// <summary> /// I can access this method without instance and i get normal de-serialized values /// </summary> public static iChannel GetChannel(CommChannel channelnr) { return StaticMe.Channels[(int)channelnr]; } } A: A problem might arise the moment you create a second instance of your class. A static field can only exist once. The moment you overwrite a static field, it will change the reference to the new object. Any old reference set to the old object that might still be used elsewhere will not update - or worse, if it holds any data, it might change unexpectedly. CommManager manager = new CommManager(); manager.GetChannel(); // refers to the static field StaticMe.channels which is manager.channels. CommManager manager2 = new CommManager(); manager2.GetChannel(); // refers to the static field StaticMe.channels which is manager2.channels. manager.GetChannel(); // still exists, now refers to manager2.channels because of StaticMe now being manager2 // It is not retaining any of the original channels because of the changed reference. Because of that, static fields or properties should better be immutable and not rely on anything stored within the static property other than default or fixed values. If you really have to store mutable values globally, don't assign them in a constructor or in any instance method but on the definition. If your channels should be available globally, then make the List globally available by making that one static readonly (as the List reference will stay the same, only the contents may change). // for brevity, removed all unchanged parts... public class CommManager { private static readonly List<IChannel> channels = new List<IChannel>(); private void ChannelCollectionChanged(object sender, NotifyCollectionChangedEventArgs args) { switch (args.Action) { case NotifyCollectionChangedAction.Add: foreach (ChannelConfig newItem in args.NewItems) CommManager.channels.Add(CreateChannel(newItem)); break; case Notif.. /// etc. etc. } } public static IChannel GetChannel(CommChannel channelNr) { return CommManager.channels[(int)channelNr]; } } Also if you are going to a multi threading approach, you might need a ConcurrentBag<T> that is thread safe instead of a normal List<T> which is not.
{ "pile_set_name": "StackExchange" }
Q: PayPal Express not giving option for Check out as Guest, even if it is active (PayPal Paying Guest option to YES) I had some problems with paypal settings in Magento 1.7.0.2. The problem is this: I am using using paypal express (I have my account created and verified Paypal Company). It has active PayPal Paying Guest option set to YES, but when a user in my shop will complete your purchase and pay with Paypal will be the option PayPal API perfect, but does not show me the option to pay without paypal account. I have VERIFIED ALL settings in Magento Admin Panel and everything "seems to be fine". I have also tried making a new store to rule out any configuration already had my store "old", that might not let me do my Enable PayPal Guest Checkout, but still have the same problem. I look forward to your help to solve the problem, since I have no idea what else to do on my page. thanks A: One thing to do is to make sure that your call to paypal includes SOLUTIONTYPE=Sole as this should be the flag to inform paypal to allow guest checkouts. If this flag is not set then you can investigate the Magento side to see why this is not being set of request, If this is set but set to Mark then your config value is set to not allow guest checkout from the Magento admin config, If this value is set then I would suggest there is a problem on the paypal side of things and would recommend getting in contact with them directly, I hope this helps you find your issue.
{ "pile_set_name": "StackExchange" }
Q: I'm looking for the sql term to remove duplicate rows from a report The adhoc report tool is a Shazam product and I have a sql filter that has these value options: Is Equal To Is Between Is Greater Than Is Greater or Equal Is Less Than Is Less or Equal To Is Like Is Not Equal To Is Not Between Is Not Like The report runs, but I have a couple duplicates of the same Incident Number. How can I tell it to remove any duplicates? A: I think you are looking for the DISTINCT clause: The SQL DISTINCT command used along with the SELECT keyword retrieves only unique data entries depending on the column list you have specified after it.
{ "pile_set_name": "StackExchange" }
Q: How to access a compiled element's template after it's been compiled? Say I have an element like this: <elemental></elemental> I can pull the scope by running: angular.element($('elemental')).scope() Is it possible to get an element's source template after it's been compiled in a similar fashion from the DOM? A: It is possible although I would think the use case for this should be pretty rare (i.e. your code is running outside the Angular "world"). I've given the directive an ID with the same name so I could locate it via the DOM, but this could be done using any DOM element that is part of the app: var appElement = angular.element(document.getElementById('elemental')); var injector = appElement.injector(); var myTemplate = injector.get('elementalDirective')[0].template; console.log(myTemplate); // the template First, get the app's injector. Then locate the provider for the custom directive, which will always be the name of the directive plus the string 'Directive' (in this case elementalDirective). Then access the template property. Demo: Here is a fiddle See also: Call Angular JS from legacy code Edit: My previous answer assumed the element was not compiled yet.
{ "pile_set_name": "StackExchange" }
Q: How to create this `through`` association? Organization and Link are associated through Node. Organization: has_many :nodes has_many :links, through: :nodes, source: :where_first_links Node: belongs_to :organization has_many :where_first_links, class_name: "Link", foreign_key: "first_node_id" has_many :where_second_links, class_name: "Link", foreign_key: "second_node_id" Link: belongs_to :first_node, class_name: "Node" belongs_to :second_node, class_name: "Node" Question:: How can I associate Link back to Organization? I tried the line below but that does not seem to work (ArgumentError: Unknown key: :through.): belongs_to :organization, through: :first_node, source: :where_first_links, inverse_of: :links A: belongs_to association not support through key you should use has_one association has_one :first_node_organization, through: :first_node, class_name: 'Organization', source: :organization
{ "pile_set_name": "StackExchange" }
Q: How can I remove characters around words? I need to remove all characters that are not alphabetical from the beginning and end of each word. For example: --Hello& World-@ 1234... Should look like: Hello World 1234 I tried replaceAll, but I have no idea how many different characters I need to remove or what those characters are. I tried the following, but it didn't work. word = resultString.replaceAll("[^a-zA-Z_0-9|$a-zA-Z_0-9]|^-|$-|^--|$--|^---|$---|\\$", ""); There were still words that showed up with dashes. Is there another way to do this without using replaceAll? A: To be strict, all the answers don't solve exactly what the author asked. The problem is that they all will delete special characters even inside words, and not only "from the beginning and end of each word". Here is the code which fixes it: String str = "--Hello& World-@ 1234... my email is me@example.com"; // Analyzing every word String[] words = str.split("\\s+"); String regex = "^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$"; String result = ""; for (String word : words) { result += word.replaceAll(regex, "") + " "; } System.out.println(result); // gives "Hello World 1234 my email is me@example.com " Regex "^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$" explanation: ^[^a-zA-Z0-9]+ matches one or more special characters at the beginning of the word | OR [^a-zA-Z0-9]+$ one or more special characters at the end of the word. You can modify the regex in order NOT TO DELETE the ,.!?:; or other meaningful characters at the end of a word.
{ "pile_set_name": "StackExchange" }
Q: matlab - what is the equivalent of null / None / nil / NULL etc.? In most OO languages, where variables may point to objects, they may also have a null value, which is highly convenient. In Matlab, I have a function which parses a command, and then returns a cell array, or false (which is equal to zero — which is another common pattern) if it fails: function re = parse(s) ... if (invalid) re = false; return; end end The problem is that when I check the result, it gives an error: re = parse(s); if (false == re) Undefined function 'eq' for input arguments of type 'cell'. I've written a function to check it without an error: strcmp('logical', class(re)) && false == re, but that seems to be really slow for use in hot areas of the code, and also inconvenient if I have to add this function to every M file I'm writing. Using NaN is even worse, because besides throwing that error, it also isn't equal to itself. What's a better alternative for use with this pattern? A: A good alternative is to use the empty array: [] and isempty(re) to check. This doesn't throw the error. Reference: http://www.mathworks.com.au/matlabcentral/newsreader/view_thread/148764 A: You can use the isequal function to compare any two items without causing that error. For example: if isequal (re, false) %code here end
{ "pile_set_name": "StackExchange" }
Q: finish activity from an other one I have an activity for my menu events: public class GlobalMenu extends Activity{ private MenuItem item; public boolean event(MenuItem item){ this.item = item; // Handle item selection switch (this.item.getItemId()) { case R.id.menu_stop: finish(); return true; } return true; } } And I use it like this GlobalMenu gm = new GlobalMenu(); @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { return gm.event(item); } But the finish didn't work, I think I need to link it with an application but I don't know how to do Thanks A: First of All, You can't make a Object or Instance of Android Activity. like this GlobalMenu gm = new GlobalMenu(); You have to pass a Context of GlobalMenu Activity to other Activity or Class and then call finish on this. Like, ((GlobalMenu)mContext).finish(); Here mContext is a reference of GlobalMenu Activity.
{ "pile_set_name": "StackExchange" }
Q: Tunneling TCP ports through ssh without blocking I'm trying setup a ssh tunnel via pexpect with following code: #!/bin/env python2.4 import pexpect, sys child = pexpect.spawn('ssh -CfNL 0.0.0.0:3306:127.0.0.1:3306 user@server.com') child.logfile = sys.stdout while True: code = child.expect([ 'Are you sure you want to continue connecting \(yes/no\)\?', 'password:', pexpect.EOF, pexpect.TIMEOUT ]) if code == 0: child.sendline('yes') elif code == 1: child.sendline('passwordhere') elif code == 2: print ".. EOF" break elif code == 3: print ".. Timeout" break What I expect is after password was sent and ssh tunnel established, the while loop exits so that I can continue processing with other business logic. But the code above block util timeout (about 30 seconds) if ssh tunnel established. Could anyone please give me some advice on how to avoid the block? A: I think the simplest solution is to use ssh host-key authentication, combined with backgrounding ssh with &... this is a very basic implementation, but you could enhance it to kill the process after you're done... also, note that I added -n to your ssh args, since we're backgrounding the process. import subprocess USER = 'user' HOST = 'server.com' cmd = r"""ssh -CfNnL 0.0.0.0:3306:127.0.0.1:3306 %s@%s &""" % (USER, HOST) subcmd = cmd.split(' ') retval = subprocess.Popen(subcmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stat = retval.poll() while stat == None: stat = retval.poll() print "ssh in background" Finally, if you don't already have ServerAliveInterval in your ssh_config, consider calling ssh as ssh -o ServerAliveInterval=30 <other_options_and_args> to make sure you detect loss of the tunnel as soon as possible, and to keep it from aging out of any NAT implementations in the path (during inactivity).
{ "pile_set_name": "StackExchange" }
Q: PHP echo to remain on the same line after HTML (<?php _e( 'Up to', 'test' ); ?> &pound; <?php $current_price = get_field( 'price_details_price_b', 'option' ); $exchange_rate = get_field( 'price_details_exchange_rate', 'option' ); $uk_price = ($current_price * $exchange_rate); echo $uk_price; ?>) This code outputs the echo on a new line. I don't want this to occur and I don't want the PHP to start after the pound symbol, therefore what is the solution? I know I can do this by adding HTML comment <!-- --> after the pound symbol and before the PHP tag but wondered if there was a better solution? A: Why couldn't you just do (<?php _e( 'Up to', 'test' ); ?> &pound <?php $current_price = get_field( 'price_details_price_b', 'option' ); ? Or not drop out of PHP mode in the first place? (<?php _e( 'Up to', 'test' ); echo '&pound;'; $current_price = get_field( 'price_details_price_b', 'option' );
{ "pile_set_name": "StackExchange" }
Q: rounded parent border dosen't apply to child when i make the first layout with rounded border using this xml layout <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#00ffffff"/> <stroke android:width="3dp" android:color="#ffffff" /> <padding android:left="1dp" android:top="1dp" android:right="1dp" android:bottom="1dp" /> <corners android:bottomRightRadius="15dp" android:bottomLeftRadius="15dp" android:topLeftRadius="15dp" android:topRightRadius="15dp"/> </shape> its make my layout border rounded but the child its be over the rounded border see the image the parent border was rounded but the child its come over rounded border how can i solve this ? another image A: Actually you didnt make it round you just set a rounded background to your view and the layout still is a rectangle . You can set the same background to child view or use clipping as mentioned in this post.
{ "pile_set_name": "StackExchange" }
Q: Pycharm - Configure PYTHONPATH in Remote Interpreter I have PyCharm 2.7.3 installed on Windows, and I am trying to remotely develop an application on a Linux machine. So far I can run simple programs, however I'm trying to set my PYTHONPATH and it seems that PyCharm specifically ignores this configuration. Under my run configuration, I've tried setting PYTHONPATH=/path/to/my/libs, however if I print this environment variable from Python through os.environ, it is ignored. If I set another environment variable, for example ASDF=42, the value is printed as expected - so it's something special with PYTHONPATH. Under interpreters, I tried adding it under the Paths tab, but this tab only supports Windows paths, so it seems to be local only. import os if __name__ == '__main__': print os.environ['PYTHONPATH'] print os.environ The output of the first line of this program changes based on check boxes in the run config, all with PYTHONPATH=/path/to/my/libs With Add content roots to PYTHONPATH and Add source roots to PYTHONPATH checked, and PYTHONPATH=/path/to/my/libs, the first line of output is the remote root of my project - but still not my lib directory. If I uncheck the source roots box, the path remains empty (but the variable is set, to the empty string). What am I doing wrong? A: I believe this is a bug in PyCharm, but in the meantime, I've found a workaround. The heart of the issue is that with a remote interpreter, the Path configure dialog is for the local machine, not the remote machine. So the solution is to set up deployment to the remote machine, and map local folders to path folders on the remote machine. In the paths tab, add empty windows folders to your project, representing each of the lib directories, then in Tools -> Deployment -> Configuration, map those directories to your lib directories. ie. if you have a lib in /my/fancy/python/lib, create a folder C:\IdeaProjects\MyProject\my_fancy_python_lib, and then create a mapping to /my/fancy/python/lib in the deployment configuration. Hacks, but it works. Someone filed a bug report for it here (I posted my answer there too): http://youtrack.jetbrains.com/issue/PY-10739
{ "pile_set_name": "StackExchange" }
Q: MonoTouch: CurrentCulture when "Language" set On an iPhone, when the user sets their Language to French and their Region Format to United States, the CurrentCulture represents en-US. Only when the user sets their Region Format to France do I get fr-FR; How can I determine the language if the user has set their Langauge, but not their Region Format? A: You want to look at NSLocale, e.g. NSLocale.CurrentLocale.Identifier to get a string like en-US. That will give you the exact values that iOS is using. Both .NET and iOS have similar, but subtly different, API to get those values. It's difficult to be fully compatible with .NET by using only iOS data (it's not a perfect fit). In some case, e.g. RegionInfo, we have been able to bootstrap the .NET classes using iOS provided data. As more features becomes available we might be able to do the same for other types in the future.
{ "pile_set_name": "StackExchange" }
Q: Oracle Trigger creation with compilation errors I am trying to create a simple trigger with following code - CREATE OR REPLACE TRIGGER trg_menu_id BEFORE INSERT ON "menu" FOR EACH ROW BEGIN SELECT menu_id_seq.NEXTVAL INTO : NEW.MENU_ID FROM dual ; END ; But I am getting - [Err] ORA-24344: success with compilation error I don't understand what I am doing wrong. A: At last my problem is solved. Field name was in small letter so I have to use NEW."menu_id" instead of NEW.MENU_ID and now it works fine!!! My new code is- CREATE OR REPLACE TRIGGER trg_menu_id BEFORE INSERT ON "menu" FOR EACH ROW BEGIN SELECT menu_id_seq.NEXTVAL INTO :NEW."menu_id" FROM dual ; END ;
{ "pile_set_name": "StackExchange" }
Q: SelectionIndexChanged firing twice I am wondering why my selection index changed is firing twice when I click on an item on my list. This is the code I use in the selectionindexchanged private void listBoxFolders_SelectionChanged(object sender, SelectionChangedEventArgs e) { // Taking the name of the folder to pass in the parameters if ((Folder)listBoxFolders.SelectedItem != null) { folderTmp = (Folder)listBoxFolders.SelectedItem; } // Connexion to the webservice to get the subfolders and also the files WebClient wc = new WebClient(); wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted2); wc.DownloadStringAsync(new Uri("http://clients.uicentric.net/IISHostedCalcService/FilesService.svc/GetFoldersAndFiles?selectedFolder=" + folderTmp.Name)); } and this is the method wich is firing twice inside it : public void wc_DownloadStringCompleted2(object sender, DownloadStringCompletedEventArgs e) { if (e.Error == null) { XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None); XNamespace aNamespace = XNamespace.Get("http://schemas.datacontract.org/2004/07/System.IO"); try { // Retrieving the subfolders var folders = from query in xdoc.Descendants(aNamespace.GetName("DirectoryInfo")) select new Folder { Name = (string)query.Element("OriginalPath"), }; _lFolders = new ObservableCollection<Folder>(); foreach (Folder f in folders) { LFolders.Add(f); } listBoxFolders.ItemsSource = LFolders; listBoxFolders.DisplayMemberPath = "Name"; // Retrieving the files var files = from query in xdoc.Descendants(aNamespace.GetName("FileInfo")) select new File { Name = (string)query.Element("OriginalPath"), }; _lFiles = new ObservableCollection<File>(); foreach (File f in files) { LFiles.Add(f); } listBoxFiles.ItemsSource = LFiles; listBoxFiles.DisplayMemberPath = "Name"; listBoxFiles.SelectionChanged += new SelectionChangedEventHandler(listBoxFiles_SelectionChanged); } catch { } } } A: You are reloading the item source of listbox upon the selection changed event. Becoause of the reload action, the index gets changed to its default value, ie, -1 . This probably must be your issue. Instead of using selection changed event go for Tap event.
{ "pile_set_name": "StackExchange" }
Q: Processing form after modal submit in JSP I am displaying a modal after a button click . The code of button for opening a modal is as follows : <button type="button" name="btnEditIP" data-toggle="modal" data-target="#myModal" class="sultan_btn">Edit IP</button>\ The code of modal is as follows : <div id="myModal" class="modal fade"> <div class="modal-dialog"> <div class="modal-content"> <form id="ipForm" class="form-horizontal" role="form" method="post" action="info_edit.jsp"> <div class="modal-header modal-header-warning"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title ">Please Enter IP Address</h4> </div> <div class="modal-body"> <div class="form-group"> <label for="inputName">IP Address</label> <input type="text" class="form-control" name="ip"/> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button> <button type="button" name="btnSave" id="btnSave" class="btn btn-primary" data-dismiss="modal">Save</button> </div> </form> </div> </div> In edit_info.jsp page, I am trying to determine whether the btnSave button is pressed by the following code : if ((request.getParameter("btnSave") == null) ? false : true) { out.println("Form submitted"); } else{ out.println("Form not submitted"); } Although , I am pressing the Save button in modal , I am always getting this message , "Form not submitted!" .That means , either the form is not submitted or there is an error in pressing button . I am not sure where is the error . I have tried a lot but could not identified where is the error . Please help me to solve this error . A: Please change request.getAttribute("btnSave") to request.getParameter("btnSave"). Because getParameter() returns http request parameters. EDIT I am not sure if one would see btnSave server side since the button name would not be sent ? We can use type="submit" to send the pressed button's name to the server. <input type="submit" name="btnSave" value="SAVE"/> Also Check: Difference between getAttribute() and getParameter() Difference between type='button' and type='submit' How do I call a specific Java method on click/submit event of specific button in JSP?
{ "pile_set_name": "StackExchange" }
Q: controlling the height change speed I have the below javascript for a height change of a div. However, I don't know how to adjust the speed when the div reveals. i know 500 is the speed when the height of the div changes to 30px, but i don't know how to control the speed when it changes back to 100%. can anyone help? $(document).ready(function(){ $("#mydiv").click(function(){ var $this = $('#mydiv_2'); $this.animate({height: $this.height() == 30 ? '100%' : 30}, 500); }); }); A: $this.animate({height: $this.height() == 30 ? '100%' : 30}, 500); The second property is your speed in milliseconds.
{ "pile_set_name": "StackExchange" }
Q: How would I create a custom prompt for a response in AngularJS I basically have the UI all set up as well as all the scope variables. Let's say I have two buttons, left and right, and I only want the function to continue when one of them is clicked. That being $scope.isLeft of $scope.isRight is true. This would be similar to the way a normal javascript prompt would wait until there is a response. This is my infinite loop way of trying to get this accomplished (though this obviously doesn't work, it just shows what I am trying to do) self.getLeftOrRight = function () { $scope.promptLeftOrRight = true; //this method is being called from the directive, so a call to $apply() here is necessary if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') { $scope.$apply(); } while(!$scope.isLeft && !$scope.isRight) { //waste time for now } if (isLeft) return "left"; else if (isRight) return "right"; }; A: If you happen to be using the Angular Bootstrap module, try looking at the modal directive here. Looking at it may also give you a better understanding of what to do. Otherwise I would do what @tymeJV mentioned if you are wanting to do your own thing. Have some function/directive show the prompt(also block the background with a transparent div or something) then have each button call a function to set the left or right variables.
{ "pile_set_name": "StackExchange" }
Q: Having a separable extension of degree $n$ implies having a Galois extension of degree $n$? I would like an explanation for the fact stated in the title. To repeat: Question: How does one prove that if a field has a separable extension of degree $n$, then it has a Galois extension of degree $n$? Note that the statement might as well be false (though I would not bet on that). [EDIT: I thought I had a proof that the statement was true for $n=3$, but as Emil Jeřábek points out in his comments, this is false as well!] This might be completely trivial, but I have no idea on how to address this question, and since it kinds of naturally arose in my research, I thought it would be appropriate to ask here. A: I am posting my comment as an answer (I had no intention of causing any dispute). That is not true. Let $K$ be the maximal solvable extension of $\mathbb{Q}$ (or $\mathbb{C}(t)$, etc.). There are irreducible quintic polynomials over $K$ (otherwise every quintic over $\mathbb{Q}$ would have a solvable Galois group). Thus, there are separable, degree 5 extensions of $K$. However, every Galois extension of degree 5 would have cyclic Galois group. Since $K$ is already the maximal solvable extension of $\mathbb{Q}$, there is no nontrivial, finite cyclic extension of $K$.
{ "pile_set_name": "StackExchange" }
Q: Kernel 4.18.0-14-generic Borks Display Yesterday's apt update included the 4.18.0-14-generic kernel. On a couple of my Ubuntu 18.10 MATE laptops (older DELL and Samsung models . . . I can't recall the models; they're at a different location), when they rebooted, I was greeted with a blank screen. Evidently something went awry with the video driver compatibility. Anyone else experience a problem similar to this on older machines? I had no problem with my newer laptop (DELL Latitude E6530 running Ubuntu 18.10 MATE). Was able to work on both older laptops using the old Shift-key boot trick to get to the Grub menu's Advanced options and switching back to the machine's 4.18.0-13-generic state. Never had this happen before. Guessing I'll have to wait until the next iteration of the kernel for a fix? Or is there something I can do in the meantime to "patch" those two older laptops? TIA. [In response to the request for information about the graphics driver...] $ inxi -G -M Machine: Type: Laptop System: SAMSUNG product: R530/R730/R540 Mobo: SAMSUNG model: R530/R730/R540 BIOS: Phoenix v: 08JV.M029.20100621.hkk date: 06/21/2010 Graphics: Device-1: Intel Core Processor Integrated Graphics driver: i915 v: kernel Display: x11 server: X.Org 1.20.1 driver: modesetting unloaded: fbdev,vesa resolution: 1366x768~60Hz OpenGL: renderer: Mesa DRI Intel Ironlake Mobile v: 2.1 Mesa 18.2.2 $ inxi -G -M Machine: Type: Portable System: Dell product: Latitude E5400 Mobo: Dell model: 0D695C date: 04/29/2009 Graphics: Device-1: Intel Mobile 4 Series Integrated Graphics driver: i915 v: kernel Display: x11 server: X.Org 1.20.1 driver: modesetting unloaded: fbdev,vesa resolution: 1280x800~60Hz OpenGL: renderer: Mesa DRI Mobile Intel GM45 Express v: 2.1 Mesa 18.2.2 That's all I can provide. I don't know any other command magic to display graphics info. A: Yes, I was also greeted with a blank screen on my veteran PC. I also switched to 4.18.0-13-generic state. I'm looking for a way to fix this. This bug has been confirmed: Ubuntu boot failure. 4.18.0-14 boot stalls. (does not boot) For now, I just deleted the latest kernel: sudo apt-get remove "linux-headers-4.18.0-14-generic" sudo apt-get remove "linux-image-4.18.0-14-generic" sudo apt-get remove "linux-image-unsigned-4.18.0-14-generic" sudo apt autoremove P.S. Kernel 4.18.0-15.16 has fixed the problem. It is available in -proposed.
{ "pile_set_name": "StackExchange" }
Q: How do I get the structural images BKChem produces to satisfy these conditions on Wikipedia? I'd like to know how to get BKChem to create structural images that satisfy these conditions. A: The instructions on the page seem fairly simple (make a couple of files that hold the contents as specified). But if you want to reduce that to a few commands you can just fire off without thinking, this is what they're after: mkdir ~/.bkchem cat << EOF > ~/.bkchem/standard.cdml <?xml version="1.0" ?><cdml version="0.15" xmlns="http://www.freesoftware.fsf.org/bkchem/cdml"> <info> <author_program version="0.12.2">BKchem</author_program> </info> <standard area_color="" font_family="Arial" font_size="24" line_color="#000" line_width="0.06cm" paper_crop_margin="5" paper_crop_svg="1" paper_orientation="portrait" paper_type="Legal"> <bond double-ratio="0.85" length="1.4cm" wedge-width="0.18cm" width="0.21cm"/> <arrow length="1.6cm"/> </standard> </cdml> EOF cat << EOF > ~/.bkchem/prefs.xml <?xml version="1.0" ?> <bkchem-prefs> <lang type="StringType">en</lang> <geometry type="StringType">1016x522+4+27</geometry> <recent-file1 type="StringType"></recent-file1> <recent-file2 type="StringType"></recent-file2> <use_real_minus type="IntType">0</use_real_minus> <default-dir type="StringType">~</default-dir> </bkchem-prefs> EOF
{ "pile_set_name": "StackExchange" }
Q: Ubuntu One app installation "waiting" on iPad I would like to install the Ubuntu One app on my iPad. When I choose "install" in the app store, the Ubuntu One icon appears on my screen with a progress bar and the message "waiting." And it stays like that. I've tried removing it and restarting the installation and I get the same problem. A: I've sometimes encountered this problem when installing any apps from on iOS devices. Try the following: First, try turning the network devices off and on. Do this with all of them (Wifi, 3G, LTE). Even try putting it into and out of airplane mode. If that didn't work, try rebooting the iPad. Hope one of these helps.
{ "pile_set_name": "StackExchange" }
Q: Want to change my master to an older commit, how can I do this? I want to rollback to a previous commit, and then publish that code, then go back to the latest commit. i.e. so my master is pointing to an older commit version just so I can pulish that version, then I want to go back to the latest commit I was one initially. How can I do this? A: If you want to do this and revert the master to the previous commit: git checkout master~1 # Checkout previous commit on master git checkout -b new_master # Create branch for new master git branch -D master # Delete old master git branch -mv new_master master # Make new_master master Alternatively: git reset --hard master~1 # Reset current branch to one commit ago on master A: Your question is unclear. I think what you are asking for is this: git push -f origin $old_commit_id:master What will this do? It will push the $old_commit_id commit to origin as the new head of origin’s master branch. If that is what you wanted, you do not need to touch your local master branch at all. A: use git reset --hard <old commit number> it will reset the HEAD to this old commit. additionally, you need to use git push -f origin to alter the remote repo too.
{ "pile_set_name": "StackExchange" }
Q: c++ failed to specialize function template 'iterator_traits' im trying to compile a school assignment but im getting an error, and since there is no qualified teacher available at uni at this hour, i've come here for help. im getting a error stating: "Error C2893 Failed to specialize function template 'iterator_traits<_Iter>::difference_type std::distance(_InIt,_InIt)'" line 22 i have no clue as to why this error occurs. code: #pragma once // ttt.h #ifndef TTT_H #define TTT_H #include <tuple> #include <array> #include <vector> #include <ctime> #include <random> #include <iterator> #include <iostream> enum class Player { X, O, None }; using Move = int; using State = std::array<Player, 9>; // used to get a random element from a container template<typename Iter, typename RandomGenerator> Iter select_randomly(Iter start, Iter end, RandomGenerator& g) { std::uniform_int_distribution<> dis(0, std::distance(start, end) - 1); std::advance(start, dis(g)); return start; } template<typename Iter> Iter select_randomly(Iter start, Iter end) { static std::random_device rd; static std::mt19937 gen(rd()); return select_randomly(start, end, gen); } std::ostream &operator<<(std::ostream &os, const State &state); std::ostream &operator<<(std::ostream &os, const Player &player); Player getCurrentPlayer(const State &state); State doMove(const State &state, const Move &m); Player getWinner(const State &state); std::vector<Move> getMoves(const State &state); #endif // TTT_H function call": State mcTrial(const State &board) { State currentBoard = board; std::vector<Move> possibleMoves = getMoves(currentBoard); while (possibleMoves.size() > 0) { int move = select_randomly(0, (int)possibleMoves.size() -1); Move m = possibleMoves[move]; currentBoard = doMove(currentBoard, m); possibleMoves = getMoves(currentBoard); } return currentBoard; } A: You should pass iterators to select_randomly, not indexes. Here is the proper function call: std::vector<Move>::iterator it = select_randomly(possibleMoves.begin(), possibleMoves.end()); To learn more about iterators visit http://www.cprogramming.com/tutorial/stl/iterators.html
{ "pile_set_name": "StackExchange" }
Q: Which Ruby on Rails version should I upgrade to? I am using Ruby on Rails 3.2.9 and on the official blog it has been posted the following article: "[SEC] [ANN] Rails 3.2.13, 3.1.12, and 2.3.18 have been released!". My question is: Which Ruby on Rails version should I upgrade to? Note: I ask this because in the linked blog post (and in related linked pages) there is a bit of confusion. I would be grateful if someone would tell me a little more about the upgrades. A: I suggest to upgrade to the latest release of the branch you are currently using, i.e. from 3.2.9 to 3.2.13.
{ "pile_set_name": "StackExchange" }
Q: ¿Como escapar caracteres en javascript? Tengo un script que agrega el contenido de una variable a una tabla y crea dinamicamente unos botones que deberian pasarle a una funcion un arreglo. pero este arreglo al tener caracteres especiales o espacios me genera conflicto. A continuacion el script que genera la tabla con los botones. (Lo importante es la variable array y el llamado a la funcion editarSucursal en el Onclick del boton). <script type="text/javascript"> $(document).ready(function(){ $.ajax({ type: 'POST', url: "showStores.php", data:{ 'id':'helow' }, success: function (mensaje) { var data2= JSON.parse(mensaje); // tablamodificar var contenido=" <table class='table ' data-filtering='false' data-sorting='true' id='table2' style='text-align:center; vertical-align: text-top; border: solid; border-width: 1px; border-radius: 0;border-color: black;'>"; contenido+="<thead style='background: #064380; color: white;'>"; contenido+="<tr>"; contenido+="<th data-breakpoints='' style='color: white;'>Nombre</th>"; contenido+="<th data-breakpoints='' style='color: white;'>Nombre Completo</th>"; contenido+="<th data-breakpoints='' style='color: white;'>Tipo de Documento</th>"; contenido+="<th data-breakpoints='' style='color: white;'>Numero de Documento</th>"; contenido+="<th data-breakpoints='' style='color: white;'>Email</th>"; contenido+="<th data-breakpoints='' style='color: white;'>Dirección</th>"; contenido+="<th data-breakpoints='' style='color: white;'>Altura</th>"; contenido+="<th data-breakpoints='' style='color: white;'>Piso</th>"; contenido+="<th data-breakpoints='' style='color: white;'>N° de telefono</th>"; contenido+="<th data-breakpoints='' style='color: white;'>Codigo postal</th>"; contenido+="<th data-breakpoints='' style='color: white;'>Ciudad </th>"; contenido+="<th data-breakpoints='' style='color: white;'>Provincia</th>"; contenido+="<th data-breakpoints='' style='color: white;'>Acción</th>"; contenido+="</tr>"; contenido+="</thead>"; contenido+="<tbody>"; for (let index = 0; index < data2.length; index++) { contenido+="<tr>"; contenido+="<td>"+data2[index].short_name+"</td>"; contenido+="<td>"+data2[index].name+"</td>"; contenido+="<td>"+data2[index].doc_type+"</td>"; contenido+="<td>"+data2[index].doc_number+"</td>"; contenido+="<td>"+data2[index].email+"</td>"; contenido+="<td>"+data2[index].address+"</td>"; contenido+="<td>"+data2[index].stree_number+"</td>"; contenido+="<td>"+data2[index].floor+"</td>"; contenido+="<td>"+data2[index].phone+"</td>"; contenido+="<td>"+data2[index].zip_code+"</td>"; contenido+="<td>"+data2[index].city+"</td>"; contenido+="<td>"+data2[index].state+"</td>"; var array = new Array(data2[index].short_name,data2[index].name,data2[index].doc_type,data2[index].doc_number,(data2[index].email),data2[index].address,data2[index].floor,data2[index].phone,data2[index].zip_code,data2[index].city,data2[index].state); // console.log(array); contenido+="<td> <button type='button' onclick='editarSucursal("+array+");' class='btn btn-sm btn-primary' style='color:#CBA92A ;' href='#' ><i class='fas fa-pencil-alt'></i></button> <button type='button' class='btn btn-sm btn-primary' style='color:red;' href='#' ><i class='fa fa-times'></i></button> </td>"; contenido+="</tr>"; } contenido+="</tbody>"; contenido+="</table>"; $('#tablaStores').html(contenido); } }); }); Aca el script de la funcion que por ahora no hace nada pero deberia recibir el array function editarSucursal(data){ //por ahora no hace nada} Y por ultimo el error que recibo en el navegador A: Estás creando mal el array. var array = new Array(data2[index].short_name,data2[index].name,data2[index].doc_type,data2[index].doc_number,(data2[index].email),data2[index].address,data2[index].floor,data2[index].phone,data2[index].zip_code,data2[index].city,data2[index].state); Tienes que escapar el código al html y recién allí colocarle el onclick='editarSucursal Prueba este ejemplo y dime como te fue ejemplo:. $(document).ready(function(){ $.ajax({ type: 'POST', url: "showStores.php", data:{ 'id':'helow' }, success: function (mensaje) { var data2= JSON.parse(mensaje); // tablamodificar var contenido=" <table class='table ' data-filtering='false' data-sorting='true' id='table2' style='text-align:center; vertical-align: text-top; border: solid; border-width: 1px; border-radius: 0;border-color: black;'>"; contenido+="<thead style='background: #064380; color: white;'>"; contenido+="<tr>"; contenido+="<th data-breakpoints='' style='color: white;'>Nombre</th>"; contenido+="<th data-breakpoints='' style='color: white;'>Nombre Completo</th>"; contenido+="<th data-breakpoints='' style='color: white;'>Tipo de Documento</th>"; contenido+="<th data-breakpoints='' style='color: white;'>Numero de Documento</th>"; contenido+="<th data-breakpoints='' style='color: white;'>Email</th>"; contenido+="<th data-breakpoints='' style='color: white;'>Dirección</th>"; contenido+="<th data-breakpoints='' style='color: white;'>Altura</th>"; contenido+="<th data-breakpoints='' style='color: white;'>Piso</th>"; contenido+="<th data-breakpoints='' style='color: white;'>N° de telefono</th>"; contenido+="<th data-breakpoints='' style='color: white;'>Codigo postal</th>"; contenido+="<th data-breakpoints='' style='color: white;'>Ciudad </th>"; contenido+="<th data-breakpoints='' style='color: white;'>Provincia</th>"; contenido+="<th data-breakpoints='' style='color: white;'>Acción</th>"; contenido+="</tr>"; contenido+="</thead>"; contenido+="<tbody>"; for (let index = 0; index < data2.length; index++) { contenido+="<tr id=\"tr_"+index+"\">"; contenido+="<td>"+data2[index].short_name+"</td>"; contenido+="<td>"+data2[index].name+"</td>"; contenido+="<td>"+data2[index].doc_type+"</td>"; contenido+="<td>"+data2[index].doc_number+"</td>"; contenido+="<td>"+data2[index].email+"</td>"; contenido+="<td>"+data2[index].address+"</td>"; contenido+="<td>"+data2[index].stree_number+"</td>"; contenido+="<td>"+data2[index].floor+"</td>"; contenido+="<td>"+data2[index].phone+"</td>"; contenido+="<td>"+data2[index].zip_code+"</td>"; contenido+="<td>"+data2[index].city+"</td>"; contenido+="<td>"+data2[index].state+"</td>"; // console.log(array); contenido+="<td > <button id=\"editarSucursal_"+index+"\" type='button' class='btn btn-sm btn-primary' style='color:#CBA92A ;' href='#' ><i class='fas fa-pencil-alt'></i></button> <button type='button' class='btn btn-sm btn-primary' style='color:red;' href='#' ><i class='fa fa-times'></i></button> </td>"; contenido+="</tr>"; } contenido+="</tbody>"; contenido+="</table>"; $('#tablaStores').html(contenido); for (let index = 0; index < data2.length; index++) { var array = new Array(data2[index].short_name,data2[index].name,data2[index].doc_type,data2[index].doc_number,(data2[index].email),data2[index].address,data2[index].floor,data2[index].phone,data2[index].zip_code,data2[index].city,data2[index].state); $("#editarSucursal_"+index).attr('onclick','editarSucursal('+array+')'); } } }); });
{ "pile_set_name": "StackExchange" }
Q: ディスカッションの発生を避けるための注記 phpでmysqlにデータを保存しているデータをid毎に静的フアィルhtmlに生成して書き出したいです この質問は、コメントと回答を駆使してディスカッションが行われた結果、第三者には全く話が追えない(=Q&Aリソースとしては無価値な)状態となっています。 これは極端な例としても、コメントや回答でディスカッションが行われる例は多数あります。 現状でも、コメントの入力欄に「コメントを使って情報の追加を求めたり改善方法を提案したりします。コメントを使って回答しないでください」と説明がありますが、 指摘に対しては質問や回答を編集することで応えるようにしコメントで返信すべきではないことは伝わらない 字が薄い上1文字でも入力した瞬間消えてしまうのでそもそも気がつかれていない と、あまり注意書きとしては機能していないようですので、はっきりとした注記を追加した方がいいように思います。 これを読んで「ディスカッションは一律に許されないのだ」と誤解される方がいるかも知れないので追記。 ディスカッションがまずいのは、「質問」と「回答」だけを見ても話が通じずコメントのやりとりをすべて追わないと質問の真意や正確な回答がわからない、という事態が引き起こされることです。「質問」と「回答」だけを取り出してもQ&Aとして成立する、という状態が理想ではないでしょうか。 従って、「質問への追加情報の依頼」→「依頼への疑義」→「依頼の訂正」とか、「回答への疑義」→「疑義への疑問の呈示」→「当初の疑義への補足」みたいなやりとりがコメント欄で行われるのは問題では無いと思います。「依頼への疑義」とか「疑義への疑問の呈示」のような内容を質問や回答に追記してもかえってわかりにくくなるだけでしょう。長くなるようならチャットにした方がよいですが。 回答欄は回答欄なのですからそこに質問を書くべきでないのは言うまでもないでしょう 上記追記部分については、この投稿を理由にして「ディスカッション(ユーザー同士のやりとり)は絶対に駄目だ」とされないよう、ヘルプセンターの記述や過去のメタの議論からおそらくこうであろうというSOのポリシーを書いたもので、この点について討議を求めているわけではありません。この点について討議が必要とお考えの場合は、新たに質問として投稿されれば良いと思います。 A: 案です。テキストボックスの上に表示されることを想定しています。 質問のコメント欄 コメントで求められた追加情報の要求や改善の提案にはコメントで返信せず質問の編集で行ってください コメントで質問に回答しないでください 回答の入力欄 追加の質問や「ありがとう」を回答として投稿しないでください 質問に対する追加情報の要求や改善の提案は質問のコメントを使って投稿してください 回答のコメント欄 回答内容の疑問点の確認はよいですが、追加の質問の場合は、元の質問を編集して行うか新たに別の質問として投稿してください 回答の訂正や追加情報はコメントではなく回答を編集して行ってください
{ "pile_set_name": "StackExchange" }
Q: Detecting mouseReleaseEvent in pyqtgraph. Problem with inheritance Pyqtgraph does unfortunately not provide a mouseRelease signal. Therefore, I would like to modify the mouseReleaseEvent method in pyqtgraphs GraphicsScene class to emit a custom signal. But in my example below, the mouseReleaseEvent function overrides the equivalent method in the QWidget parent and not in pyqtgraph as desired. How can I address and change this method or is there an easier way for detecting a mouse button release? import sys, pyqtgraph from PyQt5 import QtGui, QtWidgets class Window(QtWidgets.QDialog): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self) layout = QtGui.QGridLayout(self) view = pyqtgraph.GraphicsLayoutWidget() layout.addWidget(view,0,0) view.scene().sigMouseClicked.connect(self.OnClick) def OnClick(self): print("click") # This works inside the GraphicsLayoutWidget. def mouseReleaseEvent(self,ev): # This does only work outside the pyqtgraph widget. It overrides the method in QWidget and not in pyqtgraph.GraphicsScene() print("released ",ev) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) form = Window() form.show() sys.exit(app.exec_()) A: So, I don't know if this is particularly clever, but I came up with a solution using a separate timer that keeps track of the existence of clickEvents. I hope this is helpful for people having a similar issue. import sys, pyqtgraph from PyQt5 import QtGui, QtWidgets, QtCore class Window(QtWidgets.QDialog): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self) layout = QtGui.QGridLayout(self) self.view = pyqtgraph.GraphicsLayoutWidget() self.timer = QtCore.QTimer() layout.addWidget(self.view,0,0) self.proxy = pyqtgraph.SignalProxy(self.view.scene().sigMouseMoved, rateLimit=30, slot=self.OnMouseMove) self.view.scene().sigMouseClicked.connect(self.release) self.timer.timeout.connect(self.release) def release(self): if not self.view.scene().clickEvents: print("release after drag") self.timer.stop() elif not self.timer.isActive(): print("release after click") def OnMouseMove(self): if not self.timer.isActive() and self.view.scene().clickEvents: self.timer.start(10) # After a drag release, this is the "wait" time before self.release is called. def mouseReleaseEvent(self,ev): # This does only work outside the pyqtgraph widget. It overrides the method in QWidget and not in pyqtgraph.GraphicsScene() print("released ",ev) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) form = Window() form.show() sys.exit(app.exec_())
{ "pile_set_name": "StackExchange" }
Q: Equivalents to Comptes Rendus The Comptes Rendus is (are) a French Academy of Sciences publication, essentially a 'rapid communication' format. It comes in many flavours, and maths is one of them. Proofs are non-existent (at least in older articles I've read), or perhaps only sketched. I don't know what the reach of CR is outside the francophone world (note that CR is bilingual French/English) One preliminary question is this: Are there any equivalents to CR? Some context: say I have a new result, which I know will be true, and just the grinding calculations need to be done. If I don't want to wait to unveil it to the world, what benefit do I get from publishing in rapid communication journals like CR? I could put the same thing on the arXiv, and while one might point out that a journal is refereed, but how can a proofless/proof-lite article be refereed? Should I submit to a 'rapid communication' style journal while I finish the work, and then submit the full article elsewhere (+post on arXiv), or can I get away with a short arXiv note and then post and submit the full version when it is done? A: I hope you will allow me to relate a cautionary tale. Once upon a time, my co-author and I managed to find a counter-example to a conjecture, and we wrote up a corresponding two page paper. We decided to submit our paper to Comptes Rendus (the paper contained all the details, btw, given the existence of the ArXiv, publishing research announcements just seems like resume padding). I was in charge of handling the submission, and so I naturally enough searched online for where to submit the paper. My reaction upon finding the website was "oh, that's funny, Comptes Rendus is a Canadian journal, I always thought it was a French journal". Not thinking much beyond that, I submitted the file. Time went by, and, although I noticed that the journal seemed to be taking a long time to referee a two page paper, I did not think so much about it. Six months later (to the day), the paper was accepted. I then noticed on the journal's website a note that said "On acceptance of a paper, to help defray the costs of publication, a charge of 100 dollars will be requested." Somewhat nonplussed, I emailed the editor in chief whether this was true, and he confirmed indeed that it was, with the helpful remark that, and I quote, "we assume that the researcher usually has a grant to cover such costs". It was only at this point that my co-author realized my blunder. I was then in the awkard position of having to withdraw my paper from the Canadian journal "Comptes Rendus Mathematiques" and submit it to the (French) journal "Comptes Rendus Mathematique". This resulted in not only having to write one embarassing email but two: after asking to withdraw the paper the editor wrote me back and offered to waive the 100 dollar charge, thinking that this was the reason for my withdrawl. In the end, it did get submitted to the correct journal, where it was accepted in two days. A: In the pre-Internet era, the role of CRAS was clear: publishing quickly announcements of results that would be published in full, later and elsewhere. To speed up publication, academicians or corresponding members had the power of accepting a note without having it refereed, with all the inherent risks (I remember the late Raoul Bott quipping, around 1983: "On the stock exchange, CRAS would be rated B"). Nowadays, in view of the role taken by ArXiV in quick dissemination of results, my feeling is that CRAS is more and more evolving to a journal publishing short papers with complete proofs, duly refereed, with the advantage of a quick decision process. In the committees where I've been recently, CRAS is rated as an ordinary journal. The only thing that would prevent me to submit to them, is Elsevier's pricing policy: see http://www.elsevier.com/wps/find/journaldescription.cws_home/621366/bibliographic A: Electronic Research Announcements of the AMS is perhaps one such journal. But why not publish in Comptes Rendus? It is well known the world over and has many gems (with complete proofs). For example, Gabber's proof of a deep finiteness result in etale cohomology is in O. Gabber , Sur la torsion dans la cohomologie l-adique d'une variété. C. R. Acad. Sci. Paris 297 (1983), pp. 179–182.
{ "pile_set_name": "StackExchange" }
Q: Problema de Replace no sqlserver Tenho um campo na pagina que recebe somente numero, mais quando vou compara na função este valor da página com o que esta no banco, não retorna a pesquisar. Estou tentando usar o Replace para tira o formatação do valor do banco para compara com o valor vindo da pagina. este e o código que estou usando IF @charLinhaDigitavel IS NOT NULL BEGIN SET @SQL = @SQL + @CONDICAO + 'TIT.LinhaDigitavel LIKE ''%''+'+ '''' +replace( @charLinhaDigitavel,''.'',''''),replace( @charLinhaDigitavel,'' '','''' + '''' +'+''%'' ' SET @CONDICAO = ' AND ' END A: A princípio está faltando um ) no último replace, seria algo como replace( @charLinhaDigitavel,'' '','''') + '''' +'+''%'' ' Da maneira que está ai você acaba repetindo a linha digitável, já que você esta concatenando o resultado de um replace com o resultado de ouro replace (separados), aplicados na mesma variável. Tente utilizar um replace dentro do outro. Por exemplo: replace(replace(@charLinhaDigitavel,'' '','''' + ''''),''.'','''') Dessa forma você irá aplicar sempre pegar o resultado do replace mais "interno" e aplicar o replace mais "externo".
{ "pile_set_name": "StackExchange" }
Q: Doing a Line Integral Problem Here is my attempt: $$W=\int_C\vec{F}\cdot d\vec{r}\\=\int_C\frac{\alpha x}{(x^2+y^2)^{3/2}}dx+\frac{\alpha y}{(x^2+y^2)^{3/2}}dy\\Using\quad x=2t+1\quad and \quad y=-2t\quad for\quad 0\le t\le 1\\=\alpha\int_0^1\frac{8t+2}{[(2t+1)^2+4t^2]^{3/2}}dt$$ At this point, I am stuck. A: Hints: $$\begin{align*}\bullet&\;\;(2t+1)^2+4t^2=8t^2+4t+1\\{}\\ \bullet&\;\;8t+2=\frac12\left(8t^2+4t+1\right)'\\{}\\ \bullet&\;\;\forall\,\text{differentiable positive function}\;f(x)\;,\;\;\int\frac{f'(x)\,dx}{f(x)^{3/2}}=-\frac 2{\sqrt{f(x)}}+C\end{align*}$$
{ "pile_set_name": "StackExchange" }
Q: ScrollTop animate does not work if html, body is overflow-x: hidden I have come upon an interesting problem. I am using jquery to animate scrolltop property of html and body tags to perform smooth scroll. It works nicely, but in MS Edge appears horizontal scrollbar (Mac, no problem, nothing is overflowing to sides :/ ). So to prevent this behavior, I have set overflow-x: hidden to body and html tags. The horizontal scrollbar disappeared. HOWEVER my smooth scroll isn't working how it should. Whenever you click the button to scroll down while you are not right at the top of page, the view jumps to the top and moreover it didn't scroll to requested place. Here is website where you can see it. Click on PRO MUŽE or PRO ŽENY (at center of top section). http://mountiny.com/lab/colourMe/ Do you know why the horizontal scrollbar shows in some windows browsers and in on it doesn't? Thanks for explanation of animation behavior and also for help with scrollbar. That's my Javascript (jQuery) <script type="text/javascript"> var colors = ["red", "purple", "pink"]; var number = Math.floor(Math.random() * 3); var logo = $(".logo img"); var parfem = $(".parfem img"); var descBg = $(".desc"); var introSection = $(".intro"); var text = $(".introText"); var contentText = $(".content-text"); var lomitko = $("#svgLomitko"); if (number == 0) { logo.attr("src", "images/colourme_logo_cervena.png"); parfem.attr("src", "images/colourme_cervena.png"); introSection.css("backgroundColor", "#D2232A"); contentText.css("backgroundColor", "#D2232A"); descBg.css("backgroundColor", "rgba(210, 35, 42, 0.7)"); text.css("color", "#981A26"); lomitko.css("stroke", "#981A26"); // alert("red"); }else if(number == 1) { logo.attr("src", "images/colourme_logo_fialova.png"); parfem.attr("src", "images/colourme_fialova.png"); introSection.css("backgroundColor", "#8568A2"); contentText.css("backgroundColor", "#8568A2"); descBg.css("backgroundColor", "rgba(159, 133, 181, 0.7)"); text.css("color", "#3F325D"); lomitko.css("stroke", "#3F325D"); // alert("purple"); } else { logo.attr("src", "images/colourme_logo_ruzova.png"); parfem.attr("src", "images/colourme_ruzova.png"); introSection.css("backgroundColor", "#F37FB2"); contentText.css("backgroundColor", "#F37FB2"); descBg.css("backgroundColor", "rgba(244, 152, 193, 0.7)"); text.css("color", "#C5568F"); lomitko.css("stroke", "#C5568F"); // alert("pink"); } $("#scrollTop").on("click", function(e){ e.preventDefault(); smoothScroll($("html")); }) function smoothScroll(target) { $('body,html').animate( {'scrollTop':target.offset().top}, 600 ); } $(document).ready(function(){ // if ($(".mobile-info").css("display") != "none") { $(".vyber").on("click", function(){ smoothScroll($(".offer")); }) // } $("#open-info").click(function(e){ e.preventDefault(); $(".cross").css("display", "block"); // $(".content-text").css("display", "block"); $(".content-text").toggleClass("display-block"); $(".content-text").animate(function(){ opacity: 1 }, 300, function(){ $(".content-text").css("opacity", "1"); }) }); $(".cross").click(function(){ $(".content-text").animate(function(){ opacity: 0 }, 300, function(){ $(".content-text").css("opacity", "0"); }); setTimeout(function(){ $(".content-text").toggleClass("display-block"); $(".content-text").css("opacity", "1"); $(".cross").css("display", "none"); }, 300); }); $(".par").click(function(){ // alert("asd"); if ($(".desc").hasClass("selected")) { if ($(this).find(".desc").hasClass("selected")) { $(this).find(".desc").removeClass("selected"); return; }; $(".selected").removeClass("selected"); }; $(this).find(".desc").addClass("selected"); }) $("div.vyber a").click(function(e){ e.preventDefault(); if ($("div.vyber a").hasClass("selected")) { // alert("asd"); if ($(this).hasClass("selected")) { $("div.vyber a.selected").removeClass("selected"); // return; } else { $("div.vyber a.selected").removeClass("selected"); $(this).addClass("selected"); } } else { // alert("asd"); $(this).addClass("selected"); } if ($(".zeny a").hasClass("selected")) { $(".proZeny").removeClass("active"); $(".proMuze").addClass("active"); } else if($(".muzi a").hasClass("selected")) { $(".proMuze").removeClass("active"); $(".proZeny").addClass("active"); } else { $(".proMuze").removeClass("active"); $(".proZeny").removeClass("active"); }; }) // $(".offer:not(.desc)").click(function(){ // alert("as"); // if ($(".desc").hasClass("selected")) { // $(".selected").removeClass("selected"); // }; // }) }) </script> A: Your code works good. The problem, must be in your CSS file. I suspect that you set html and body height to 100% if yes, remove it or use min-height instead. If you set the html and body height to 100%, the browser consider 100% the visible space, so you can't scroll anywhere because the space that you can see is the already 100% because you forced this in your css. Your document is contained in the body, if you set the body height to 100% what do you expect to see if your document height is greater than the visible space?
{ "pile_set_name": "StackExchange" }
Q: Applying css on ActionLink in mvc? I am working in mvc5. I made a simple action link in a view using this syntax @Html.ActionLink("Manage List", "Index", new { @class = "ManageLink" }); But css was not working untill i added controller name like this: @Html.ActionLink("Manage List", "Index",new { controller = "ControllerName" }, new { @class = "ManageLink" }); I want to know why we need to define controller name here while it is quite obvious that every view is related to some action method of a controller ? I am very new to mvc so need to know these kind of things. Thanks for the help. A: You could also have fixed this by simply specifying the name of the optional parameter you wanted to set: @Html.ActionLink("Manage List", "Index", htmlAttributes: new { @class = "ManageLink" }); Otherwise, the Razor engine has to try to figure out which overload of the ActionLink method you're trying to call; sounds like in your case it thought the third argument was for the routeValues parameter. This would also work: @Html.ActionLink("Manage List", "Index", "ControllerNameHere", new { @class = "ManageLink" });
{ "pile_set_name": "StackExchange" }
Q: Is it possible to upload to Amazon S3 with part less then 5 MB? Is it possible to upload to Amazon s3 with part less then 5 MB? I'm now using Android client but I think it doesn't matter. I'm trying to upload file to Amazon S3 with Android by parts. And I want these parts be less the 5MB (1MB for example) but I can't. EDIT: // Step 1: Initialize. InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(existingBucketName, keyName); InitiateMultipartUploadResult initResponse = s3.initiateMultipartUpload(initRequest); File file = new File(filePath); long contentLength = file.length(); long partSize = 15 * 1024 * 1024; // Set part size to ~ 1 MB. try { // Step 2: Upload parts. long filePosition = 0; for (int i = 1; filePosition < contentLength; i++) { // Last part can be less than 5 MB. Adjust part size. partSize = Math.min(partSize, (contentLength - filePosition)); // Create request to upload a part. UploadPartRequest uploadRequest = new UploadPartRequest() .withBucketName(existingBucketName).withKey(keyName) .withUploadId(initResponse.getUploadId()).withPartNumber(i) .withFileOffset(filePosition) .withFile(file) .withPartSize(partSize); A: Accordingly to AWS documentation "each part must be at least 5 MB in size, except the last part"
{ "pile_set_name": "StackExchange" }
Q: Mathematica shows complex roots while asked for reals? I ran the following code in Mathematica ToRadicals[Reduce[-14848 c^4 + 38016 c^3 x - 30888 c^2 x^2 + 6480 c x^3 + 1215 x^4 == 0 && c < 0,x,Reals]] This should give the real roots of the polynomial. However, the output displays two complex roots? How is this possible? Thanks in advance!e A: I am getting this ToRadicals@ Reduce[-14848 c^4 + 38016 c^3 x - 30888 c^2 x^2 + 6480 c x^3 + 1215 x^4 == 0 && c < 0, x, Reals] addendum Interesting, without ToRadicals one get only real roots. f = -14848 c^4 + 38016 c^3 x - 30888 c^2 x^2 + 6480 c x^3 + 1215 x^4; sol = Reduce[f == 0 && c < 0, x, Reals] sol[[2]] /. c -> -1 // N (* x == -1.12557 || x == 8.69121 *) Manipulate[ Plot[-14848 c^4 + 38016 c^3 x - 30888 c^2 x^2 + 6480 c x^3 + 1215 x^4, {x, -10, 10}], {c, -10, -0.1}]
{ "pile_set_name": "StackExchange" }
Q: How to get a margin around the page without content being pushed out I want to have a somewhat fluid site where the min-width would be 1000px and the maximum width would be 1200px. Can someone either show me how to do this or point me to a tutorial? The issue that I was having was that if I gave a 10px margin on the body, whatever was on the page was being pushed off the right side of the page by 10px. How do I correct this? A: Here is one good website that should help you to see the CSS for creating a fluid and fixed layout website- http://csslayoutgenerator.com/ Regarding your 10px margin issue, here is a Test fiddle- (CLICK here), that I have made. What is the issue in it? css- body { margin:10px; min-width:400px; max-width:450px; } #test { background-color:yellow; }
{ "pile_set_name": "StackExchange" }
Q: CMake claims finding OpenGL but can't find EGL and OpenGL::GL CMake is giving me confusing results when trying to find OpenGL on Ubuntu. The context is I need to do headless rendering on the server / docker without X display. I have installed OpenGL via apt-get install libgl1-mesa-dev and apt-get install libegl1-mesa-dev. Here is the relevant part in my CMakeLists.txt: cmake_minimum_required (VERSION 3.5.1) project (sandbox LANGUAGES CXX) # add OpenGL find_package(OpenGL REQUIRED COMPONENTS OpenGL EGL GLX) include_directories(${OPENGL_INCLUDE_DIRS}) if(OPENGL_FOUND) message("Found OpenGL in the current environment!") else() message("Error: No OpenGL found.") endif() message("OpenGL include dirs" ) message("${OPENGL_INCLUDE_DIR}") message("EGL include dirs" ) message("${OPENGL_EGL_INCLUDE_DIRS}") if (OpenGL_EGL_FOUND) message("EGL Found!") else() message("EGL Not Found!") endif() add_executable (sandbox "hello_egl.cpp" "shader.cpp") target_link_libraries(sandbox PRIVATE OpenGL::OpenGL OpenGL::EGL OpenGL::GLX) #target_include_directories(sandbox PRIVATE "/usr/include/EGL") #target_link_libraries(sandbox "/usr/local/lib/x86_64-linux-gnu/libEGL.so") #target_link_libraries(sandbox "/usr/local/lib/libEGL.so") set_target_properties(sandbox PROPERTIES CXX_STANDARD 11) Here is the error I got from running cmake .. : Found OpenGL in the current environment! OpenGL include dirs /usr/local/include EGL include dirs EGL Not Found! -- Configuring done CMake Error at CMakeLists.txt:44 (add_executable): Target "sandbox" links to target "OpenGL::OpenGL" but the target was not found. Perhaps a find_package() call is missing for an IMPORTED target, or an ALIAS target is missing? CMake Error at CMakeLists.txt:44 (add_executable): Target "sandbox" links to target "OpenGL::EGL" but the target was not found. Perhaps a find_package() call is missing for an IMPORTED target, or an ALIAS target is missing? CMake Error at CMakeLists.txt:44 (add_executable): Target "sandbox" links to target "OpenGL::GLX" but the target was not found. Perhaps a find_package() call is missing for an IMPORTED target, or an ALIAS target is missing? What's confusing is that CMake sets OPENGL_FOUND to true, but can't link to the target OpenGL::OpenGL ? Also, I have EGL in /usr/local/lib/x86_64-linux-gnu/ but why can't CMake find it? root@6442439c7090:/app/sandbox/build# ls /usr/local/lib/x86_64-linux-gnu/ libEGL.so libGL.so.1 libGLESv1_CM.so.1.2.0 libGLX.so libGLdispatch.so.0 libOpenGL.so.0.0.0 libEGL.so.1 libGL.so.1.7.0 libGLESv2.so libGLX.so.0 libGLdispatch.so.0.0.0 pkgconfig libEGL.so.1.1.0 libGLESv1_CM.so libGLESv2.so.2 libGLX.so.0.0.0 libOpenGL.so libGL.so libGLESv1_CM.so.1 libGLESv2.so.2.1.0 libGLdispatch.so libOpenGL.so.0 The reason I insist to use find_package is that previously I manually link to libEGL.so but the application can't get display during runtime. So I suspect I link to the wrong library. terminate called after throwing an instance of 'std::runtime_error' what(): EGL error 0x300c at eglGetDisplay Aborted (core dumped) A: As per the helpful comment of @Tsyvarev, this output is due to the wrong version of CMake. I forgot to link it but the documentation of FindOpenGL I look at is for version 3.18.1 while I required the min CMake version to be 3.5.1. In 3.5.1, there's no COMPONENTS part. Also OPENGL_FOUND does not check for EGL.
{ "pile_set_name": "StackExchange" }
Q: Recover formatted virtual drive with filesystem changed Here's an interesting problem and predicament that I'm currently in. I have a 239 GB large VHDX, originally formatted as NTFS. It contains a lot of important files, including proprietary code, game development assets and a ton of artwork. I was trying to create an Ubuntu Desktop 18.04 installer on my flash drive, and I used Rufus to try and put it in. I was in class, so I wasn't that concentrated on my laptop. Funnily enough, Rufus sorted that mounted VHD as the first, and without double-checking, I started the operation. In less than 7 seconds, the entire disk was formatted into FAT32, and Windows instantly recognized the drive, along with the available space and all. Luckily enough, I was able to cancel the operation before it started writing to the drive. Immediately after this, I set the drive as read-only, and until now I have not unmounted the drive, in fear that it might implode (even though this isn't that possible.) Now, here's the fun part: I am certain that the files are still there. The VHD size is still 239 GB, and Recuva is still able to determine a few files in the drive. I have tried deep-scanning the drive, and there are still a few files that it can muster up. The problem is, with the changed filesystem, and the circumstances that the drive was formatted in, will I still be able to recover the files (possibly with free recovery tools) or not? I've tried to use Recuva, but given that a Deep Scan is worth 9 hours and I might come up empty-handed, I just wanted to ask here first. I'm also seeing TestDisk as an option, although I don't know how it works. The VHD itself, as seen in Windows Explorer. A screenshot of the drive details, as provided by Windows. (note the incorrect partition name) As hopeless as this seems, at least I kept a month-old backup of the drive. This was the main reason why I frequently use virtual hard drives. Although this drive contains a lot of the nostalgic stuff, I'm more interested in the newer files, since these contain projects and it's going to be a major setback to start from a previous time. A: First advice : Make a backup copy of the VHDX (if not already done). The product TestDisk can use the MFT mirror to restore a disk, although its being formatted as FAT32 may throw it off: In the Advanced menu, select the NTFS partition, choose Boot, then Repair MFT. You will find a list of recovery products in the article Best Free Data Recovery and File Un-delete Utility. Personally, some time ago I had an important disk to salvage, so I tried every recovery tool in that list. The only utility that recovered almost all the files was MiniTool Power Data Recovery (free version limited to 1 GB), where a guide is found here. The product DiskInternals NTFS Recovery seems to be specialized in NTFS. It is commercial and the limitations of the trial version are not specified. Another commercial product I have seen mentioned is Restorer Ultimate Data Recovery (demo trial available). If all fails, and since you (should) have a backup of the VHDX, you could re-format it as NTFS and run data recovery products. Note that file recovery from a formatted hard drive is not always practical when a file was stored over non-consecutive sectors and the file-table is lost. You may also lose all file-names, and in that case will have to identify files or file-fragments by their content.
{ "pile_set_name": "StackExchange" }
Q: What is the proper procedure for us laypeople to edit an answer? How do I get rid of adware from Search Conduit/White Smoke? A few days ago, I had this question answered with the assistance of another user. His answer did not entirely solve my problem, however. There were still a couple of things I had to figure out on my own to finally solve my issue. In the interest of leaving a complete answer behind for future users, I added a few things to the guy's answer before accepting it. The thing is, I'm told that my edits are sitting in a queue, waiting to be accepted. Here are my concerns: Are my edits being overlooked because I already accepted an (incomplete) answer? Should I simply have posted my own answer to my question with the info from his answer and mine added together? What if my changes never get accepted? The accepted answer to my question will forever be an incomplete one A: It depends on how substantial your adjustments to the post are. Regular editing guidelines apply, even if it's an answer to your own question. For your information, 3 people reviewed your edit. 1 person approved it, the other two rejected it for the following reasons: This edit is incorrect or an attempt to reply to or comment on the existing post. Should probably be its own answer rather than such a radical change to this one. Now, to your questions. No, your edits are never overlooked. Every edit is reviewed. If the context of the question is taken into account during the review process is dependent upon the reviewer. Maybe. If your addition is more "valuable" than the initial answer, then you should post your own answer. If you're just adding details or you're polishing the answer, then you should edit. Correct, this is the "risk" you take when editing another answer. p.s. Please don't introduce changes to your post by prefixing them with "EDIT". If someone wants to review the chronological order of changes to the post, they can review the edit history.
{ "pile_set_name": "StackExchange" }
Q: Android Java: Too many imageviews? I have an arraylist of 50 imageviews containing the same bitmap using this code: for (int i = 0; i < 50; i++) { ImageView imageView = new ImageView(getApplicationContext()); imageView.setImageResource(R.drawable.pic1); imageView.setVisibility(ImageView.VISIBLE); imageView.setScaleType(ScaleType.CENTER); imageViews.add(imageView); view.addView(imageView); } This code does not cause lag except for when I move each one: final Runnable bulletData2 = new Runnable(){ public void run(){ if(i=0;i<=50;i++){ movex = Math.cos((imageViews.get(i).getRotation() - 90) * Math.PI / 180) * 32; movey = Math.sin((imageViews.get(i).getRotation() - 90)* Math.PI / 180) * 32; imageViews.get(i).setX((float) (imageViews.get(i).getX() + movex)); imageViews.get(i).setY((float) (imageViews.get(i).getY() + movey)); } handler2.postDelayed(this, 2); } }; The bitmap is only 6kB and I tried a 600 byte version of the bitmap and it still lags. If I set the imageviews to invisible then there is no lag, and if the images overlap and the app runs fast. I have tried adding hardware acceleration and largeheap but I only see a slight difference. Could anyone let me know what I should change? Edit: Imageviews is an arraylist, and view is a viewgroup = my frameLayout A: The problem is that you are updating the 50 ImageViews position every 2 millisecond which is incredibly fast that android have trouble rendering at that fast rate and causes lag on your device. solution: Increase the delay of your handler and calculate the movex and movey on a separate thread and update the imageView's position in the main thread to prevent exception.
{ "pile_set_name": "StackExchange" }
Q: Choosing specific dataview values from a SQL statement and assigning them a variable VB Good morning! I am attempting to create a timelog for a current project, I need to somehow assign a value to the variable 'depart' from a dataview that I've pulled. I'm sorry if this is like another question but I couldn't seem to find something to help my answer. Please note: depart, firstDate, etc. are all declared already. dataview = dba.Query("SELECT Time, Status FROM Timelog WHERE [Date] = '" & firstDate & "' AND USERNAME LIKE '" & AgentList.SelectedValue & "' ") For Each rowView AS DataRowView in dataview DIM row as DataRow = rowView.Row If dataview.Find("Departed") Then depart = dataview.Find("time" End If Next I plan on using the DateDiff function to calculate the hours between a departure and return from lunch, and then lunch and arrival. A: I have no idea what dba.Query() returns but I assume it is some type of collection, based on the fact you are iterating through it on the next line. Because of that, dataview.find() would NOT be returning a value from a row, but more like the index of the column that has that name. What you need to do is get the value of the field for the current row of your iteration: depart = rowView("Time")
{ "pile_set_name": "StackExchange" }
Q: PHP Order Second Array ASC by Key I have an array inside an array that has the filename, modification time and size, but I need to be able to order the array either ascending or descending by each one of these properties. I have the following, which gets the information //SCAN THE DIRECTORY $directories = scandir($dir); $directinfo = array(); foreach($directories as $directory){ if ($directory === '.' or $directory === '..') continue; if(!stat($dir.'/'.$directory)){ } else { $filestat = stat($dir.'/'.$directory); $directinfo[] = array( 'name' => $directory, 'modtime' => $filestat['mtime'], 'size' => $filestat['size'] ); } } The array is structured as so: Array ( [0] => Array ( [name] => 0 Organisation Details [modtime] => 1398164749 [size] => 4096 ) [1] => Array ( [name] => 1 Permission Form [modtime] => 1398164749 [size] => 4096 ) [2] => Array ( [name] => 6 Invoices [modtime] => 1400802471 [size] => 4096 ) ) and then use this to output: foreach($directinfo as $dirInfo){ foreach($dirInfo as $key=>$drInfo){ echo "Output: ".$key."=>".$drInfo."<br />"; } } But I need to arrange the array before this, and somehow make it so I don't need two arrays or I'm suspecting the ordered output wouldn't work. I've looked at array_multisort but can't figure out how this would work in this instance. Any help with this is really appreciated. A: Using example #3 on the array_multisort manual page: $directories = array( array('name'=>'filec','modtime'=>'12303403434','size'=>'12401'), array('name'=>'fileb','modtime'=>'12303403432','size'=>'12400'), array('name'=>'filez', 'modtime'=>'12304445405','size'=>'65200') ); // Obtain a list of columns $name = $modtime = $size = array(); foreach ($directories as $key => $row) { $name[$key] = $row['name']; $modtime[$key] = $row['modtime']; $size[$key] = $row['size']; } // Sort the data with name ascending, modtime ascending, size ascending array_multisort($name, SORT_ASC, $modtime, SORT_ASC, $size, SORT_ASC, $directories); print_r($directories); Online demo here
{ "pile_set_name": "StackExchange" }
Q: Is there a way to avoid constexpr function used in header file from entering global scope without extra namespace for it? I have a header file with code simply looking like this: constexpr uint32 GenTag(const char tag[5]) { ... } class SomeClass { static constexpr uint32 TAG1 = GenTag("smth"); static constexpr uint32 TAG2 = GenTag("abcd"); }; //constexpr needed for switch-case statement The problem is that function GenTag() belongs to global scope and I would like to avoid it if possible. I wanted to declare it inside class but it is not possible with constexpr (explanation here: constexpr not working if the function is declared inside class scope). Does c++ have anything like "undeclare" function at the end of the header (maybe some macro tricks)? Or any other options I missed? If no better ways exist I would probably go with extra (maybe excessive) namespace, but want to ask if there are any other ideas. A: There's no way to "undeclare" a function or variable in C++ (header file or not -- a header file is just included into the current translation unit). You'll need to use a namespace, or make GenTag into a macro. You can undefine macros with #undef MACRONAME.
{ "pile_set_name": "StackExchange" }
Q: Can't open module file using gfortran I am using gfortran to run an .F90 code, and I am getting two errors, program fhello_world_mpi.F90 1 Error: Invalid form of PROGRAM statement at (1) fhello_world_mpi.F90:2:6: use mpi 1 Fatal Error: Can't open module file ‘mpi.mod’ for reading at (1): No such file or directory compilation terminated. I have checked the mpi installation libraries (mpich, openmpi libraries exist in the system). The program is as follows: program fhello_world_mpi.F90 use mpi implicit none integer ( kind = 4 ) error integer ( kind = 4 ) id integer p character(len=MPI_MAX_PROCESSOR_NAME) :: name integer clen integer, allocatable :: mype(:) real ( kind = 8 ) wtime call MPI_Init ( error ) call MPI_Comm_size ( MPI_COMM_WORLD, p, error ) call MPI_Comm_rank ( MPI_COMM_WORLD, id, error ) if ( id == 0 ) then wtime = MPI_Wtime ( ) write ( *, '(a)' ) ' ' write ( *, '(a)' ) 'HELLO_MPI - Master process:' write ( *, '(a)' ) ' FORTRAN90/MPI version' write ( *, '(a)' ) ' ' write ( *, '(a)' ) ' An MPI test program.' write ( *, '(a)' ) ' ' write ( *, '(a,i8)' ) ' The number of processes is ', p write ( *, '(a)' ) ' ' end if call MPI_GET_PROCESSOR_NAME(NAME, CLEN, ERROR) write ( *, '(a)' ) ' ' write ( *, '(a,i8,a,a)' ) ' Process ', id, ' says "Hello, world!" ',name(1:clen) call MPI_Finalize ( error ) end program Update1 Removing the period solved the first problem. I used these commands: mpif90 fhello_world_mpi.F90 and mpirun -np 2 ./fhello_world_mpi It gave the following errors: mpirun was unable to launch the specified application as it could not access or execute an executable: Executable: ./fhello_world_mpi Node: user while attempting to start process rank 0. 2 total processes failed to start`` Update2 It worked. Ran commands: mpif90 -o fhello_world_mpi fhello_world_mpi.F90 mpirun -np 2 ./fhello_world_mpi Output HELLO_MPI - Master process: FORTRAN90/MPI version An MPI test program. The number of processes is 2 Process 1 says "Hello, world!" user Process 0 says "Hello, world!" user A: Change the first line of the program to remove the period. program fhello_world_mpi Periods (.) are not allowed in the names of Fortran entities (such as programs, variables, constants, types, etc). Try mpif90 filename.F90. The MPI feature is usually implemented as a "library" and for the code to compile, you need to provide extra information: location of the .mod files when compiling and of the lib*.so files when linking. This is achieved by the compiler wrapper mpif90 (often, the name may vary): mpif90 -o fhello_world_mpi fhello_world_mpi.F90 Likewise, to execute the code you need a wrapper: mpirun -np 2 ./fhello_world_mpi I assumed the filename was fhello_world_mpi.F90, correct as needed. In general, you should not try to use the flags manually but if you wish to see them you can use mpif90 -show. mpirun is needed anyway because it initializes the parallel environment.
{ "pile_set_name": "StackExchange" }
Q: neo4j, python and netbeans I'm having trouble with my code in python using neo4j. My code: from neo4jrestclient.client import GraphDatabase db = GraphDatabase("http://localhost:7474",username="neo4j", password="neo4j") # Create some nodes with labels user = db.labels.create("User") u1 = db.nodes.create(name="Marco") user.add(u1) u2 = db.nodes.create(name="Daniela") user.add(u2) beer = db.labels.create("Beer") b1 = db.nodes.create(name="Punk IPA") b2 = db.nodes.create(name="Hoegaarden Rosee") # You can associate a label with many nodes in one go beer.add(b1, b2) # User-likes->Beer relationships u1.relationships.create("likes", b1) u1.relationships.create("likes", b2) u2.relationships.create("likes", b1) # Bi-directional relationship? u1.relationships.create("friends", u2) The error: Traceback (most recent call last): File "/home/jessica/NetBeansProjects/NovoBanco/src/novobanco.py", line 1, in from neo4jrestclient.client import GraphDatabase ImportError: No module named neo4jrestclient.client A: The neo4jrestclient package isn't accessible to the the Python interpreter that you're using. E.g. $ python >>> from neo4jrestclient.client import GraphDatabase Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named neo4jrestclient.client Install the package: $ sudo pip install neo4jrestclient [...] Successfully installed neo4jrestclient-2.1.1 ... and then you should be able to move forward with your project: >>> from neo4jrestclient.client import GraphDatabase (no error this time).
{ "pile_set_name": "StackExchange" }
Q: how to force stop Intellij on linux I am using a scratch file for some Kotlin work. I accidentally created an endless loop in one of my functions and ran the file, so Intellij is not responding. There is no button for stopping the execution of the scratch file and even if there were, that wouldn't work because Intellij is not responding to mouse clicks. How do I force stop or restart Intellij in this case? A: You can kill the process by name using pkill -9 intellij or by killall -9 intellij or even kill -9 ps aux | grep intellij | awk '{print $2}'
{ "pile_set_name": "StackExchange" }
Q: Setting TexParams on sprite in Cocos2dx 3.0 I will be grateful for advice, how to update this code from cocos2dx 2.2.1 to 3.0: ccTexParams tp = {GL_LINEAR, GL_LINEAR,GL_REPEAT , GL_REPEAT}; sprite->getTexture()->setTexParameters(&tp); Now I got an error that ccTexParams is unknown type. A: Remove the cc. It is just TexParams now. They moved the TexParams typedef inside the Texture2D class in Cocos2D-X 3.0 so you will need to change your code like so: Texture2D::TexParams tp = {GL_LINEAR, GL_LINEAR, GL_REPEAT, GL_REPEAT}; Cocos2D-X 3.0 has pretty much removed the CC prefix from their naming conventions. You can check out the documentation at http://www.cocos2d-x.org/reference/native-cpp/V3.0beta2/d4/d2c/struct_tex_params.html
{ "pile_set_name": "StackExchange" }
Q: The proper order of time stamp and content under a heading in org mode I just wonder whether there is some instruction on the proper order of the time stamp and the contents under one heading. For example, Style 1: * Heading 1 <2015-11-13 Fri 10:30> Some contents. Style 2: * Heading 1 Some contents. <2015-11-13 Fri 10:30> Which style is the proper one? A: It doesn't matter at all. The proper style is the one that suits you best. You can even put timestamps right in the middle if you want. * Watch out On <2015-11-13 Fri> something will happen. Be prepared. org-mode treats every timestamp it finds in the body the same and the entry will correctly appear in the agenda on every day for which there is an active timestamp in the body or the heading. You can make every reference to time a timestamp (active or inactive depending on context) and rely on the agenda and exporters to do something sensible with them.
{ "pile_set_name": "StackExchange" }
Q: sys.exit(): is there a less extreme alternative? I was hoping to get some kind of advice regarding the use of sys.exit(). I have used sys.exit() to stop a script from running any further: My code: if x != 20: query = raw_input("X does not equal 20. Do you want to continue? (Y/N)") if query in ['y', 'Y']: pass else: sys.exit() I have done some searching (and am still searching) but I was hoping to gain some clarity regarding the best practices use of sys.exit(). Is there something a little less extreme than killing the script? I'm considering the combination of extra loop and a more inquisitive question. A: Since this is used at the beginning of your script (as mentioned by you). Use the coding pattern written below. And use return instead of sys.exit (actually since you are exiting from the script itself thereby terminating the process altogether sys.exit is not a bad practice). Whether you use return or sys.exit return appropriate integer. its a good practice. def do_something(): //process something return 1 if __name__ == '__main__': query = raw_input("Do you want to continue? (Y/N)") if query.lower() == 'y': //do something do_something() else: print 'ERROR: Cant Understand Input. It has to be (Y/N). Exiting...' return 0 A: Place your code in the main() function: def main(): // your code if __name__ == '__main__': main() Then you can exit from your script just by return A: As other commenters have noted, a function provides you the option of using return to bail out from anywhere in the script and that's probably the best choice - I just thought I'd mention one piece of trivia: Technically sys.exit raises a SystemExit exception. You can catch a SystemExit with an ordinary try-catch, effectively 'canceling' the exit if you want to. This might come in handy if you have more complex code in which a low level function might not have enough context to make a good decision but higher level code may want to step in and clean up. People from C/C++ and lots of other languages get hives from this tactic but it's not uncommon in Pythonland. It's not a good idea to use exceptions for flow control in general but if you are using other people's functions, or combining smaller scripts into a larger application, it may be useful. Don't forget, btw, that if control falls through to the bottom of your script it will just return 'None' anyway, so in your example: if x != 20: query = raw_input("X does not equal 20. Do you want to continue? (Y/N)") if query in ['y', 'Y']: // do something is the same as if x != 20: query = raw_input("X does not equal 20. Do you want to continue? (Y/N)") if query in ['y', 'Y']: // do something else: sys.exit() EXCEPT for the fact that you could try/catch around the second but not the first... though I assume your example is snipped from a larger sample where return is the better escape route
{ "pile_set_name": "StackExchange" }
Q: R using max function in data table I'm using R and have a problem in a data.table Both of these commands return NA for all rows: AfAm[, sizediffpos := max(0,sizediff)] AfAm[, sizediffpos := max(0,sizediff, na.rm = TRUE)] Is there any way I can rectify the error? A: As rawr points out, the correct way is to use pmax: AfAm[, sizediffpos := pmax(0,sizediff)]
{ "pile_set_name": "StackExchange" }
Q: In Managed C++, what is the proper way to define a static singleton instance in a class? Jumping to Visual Studio 2015 from Visual Studio 2013, I've noticed some differences in how static self-instances in managed C++ classes are accepted by the compiler. Consider these two examples: Method 1: public ref class CResourceManager { public: static property CResourceManager^ Instance { CResourceManager^ get() { return %m_Instance; } } private: static CResourceManager m_Instance; }; Method 2: public ref class CResourceManager { public: static property CResourceManager^ Instance { CResourceManager^ get() { return m_Instance; } } private: static CResourceManager^ m_Instance = gcnew CResourceManager; }; Method 1 used to work on 2013, but it's failing to compile on 2015. I unfortunately do not have the exact compiler error handy, but it was one of those "Missing semicolon before variable name" errors, basically saying it couldn't find the type CResourceManager (pointing to the static variable declaration). So on to my questions: Is method 1 supposed to work or be valid in managed C++? Why would the second method work in 2015, but not the first (i.e. what are the differences)? Which method is the proper way to accomplish the end goal? A: Method 2 is the proper way to do it. The code you have listed is the equivalent of the C# idiom. Method 1 is a bit unusual. The lack of a ^ on a declaration would normally mean that the variable is not allocated on the managed heap. However, since it's a static class member, I'm not sure where it actually gets created. % is normally used for declaring tracking references, the equivalent of passing a variable by ref or out in C#. To be honest, I didn't think that applying % to a variable without either ^ or % and taking the result as a ^ was even valid. (Though considering the 2015 compiler rejects it, it may not be.) Even if Method 1 is valid, I'd still go with Method 2: The storage location of m_Instance and how it's returned are both plain, common, and easy to understand. This beats having to think about how the code works any day.
{ "pile_set_name": "StackExchange" }
Q: My specified font size does not apply when i install the program in windows7 I specify a font and its size for my listview items using win32 api and it works properly in Windows Xp. I install it in Windows 7 and see size of fonts are too small and hard to read although i specified 17 for its size. I increased default font sizes in Windows 7 but still the fonts in my program are too small. This is the code that i specify font for the listview items inside Window procedure : case WM_DRAWITEM: { LPDRAWITEMSTRUCT pDIS=(LPDRAWITEMSTRUCT)lParam; HDC hDC=pDIS -> hDC; RECT rc = pDIS -> rcItem; HBRUSH bg = (HBRUSH) (::GetStockObject(DC_BRUSH)); HPEN pn=(HPEN)(::GetStockObject(NULL_PEN)); ::SelectObject( hDC , bg ); ::SelectObject( hDC , pn ); ::SetTextColor( hDC , RGB(0,0,0)); HFONT hF; hF=CreateFont(17, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, L"Tahoma"); HFONT hOldFont = (HFONT) SelectObject(hDC, hF); if( (pDIS->itemID % 2) != 0 ) ::SetDCBrushColor(hDC, RGB(255,255,255)); else{ ::SetDCBrushColor(hDC, RGB(223, 241, 255)); } ::Rectangle( hDC , rc.left , rc.top , rc.right , rc.bottom ); char buffer[1000] = {0}; ListView_GetItemText(pDIS -> hwndItem, pDIS -> itemID, 0, (LPWSTR)buffer, 1000); ::DrawText(hDC, (LPWSTR)buffer, -1, &rc, DT_SINGLELINE | DT_VCENTER); SelectObject(hDC, hOldFont); DeleteObject(hF); } break; How can i make Windows display my desired font size and not that small font? Thanks! A: Use SystemParametersInfo to find the default font as follows: NONCLIENTMETRICS metrics; metrics.cbSize = sizeof(NONCLIENTMETRICS); ::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &metrics, 0); hfont = CreateFontIndirect(&metrics.lfMessageFont); Use .lfMessageFont for ListView and other child controls. This will retrieve the correct font name and font size. This font size is already adjusted for DPI settings of system and application. You can create this font once during windows creation. Then assign it as the main font for the window and listview control. This will update the header control for the listview. HFONT hfont; ... case WM_CREATE: { if (!hfont) { NONCLIENTMETRICS metrics; metrics.cbSize = sizeof(NONCLIENTMETRICS); ::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &metrics, 0); hfont = CreateFontIndirect(&metrics.lfMessageFont); } hListView = CreateWindow(WC_LISTVIEW ...); SendMessage(hWnd, WM_SETFONT, (WPARAM)hfont, MAKELPARAM(TRUE, 0)); SendMessage(hListView, WM_SETFONT, (WPARAM)hfont, MAKELPARAM(TRUE, 0)); ... break; } Also, do not use (LPWSTR) cast to hide compiler warnings and errors. Use casting only when you are sure it's applicable. In this case, char and wchar_t are very different storage types, casting may in some special cases, but it's far from reliable. char buffer[1000] creates a buffer of size 1000 bytes. But you are making a call to ListView_GetItemText to read 1000 Unicode characters, which in this case is 2000 bytes and results in buffer overrun. You can change as follows: case WM_DRAWITEM: { LPDRAWITEMSTRUCT pDIS = (LPDRAWITEMSTRUCT)lParam; HDC hDC = pDIS->hDC; RECT rc = pDIS->rcItem; COLORREF textcolor = RGB(0, 0, 0); COLORREF bkcolor = RGB(255, 255, 255); if((pDIS->itemID % 2) == 0) { bkcolor = RGB(223, 241, 255); } if(pDIS->itemState & ODS_SELECTED) { textcolor = RGB(255, 255, 255); bkcolor = RGB(0, 0, 255); } SetDCBrushColor(hDC, bkcolor); SelectObject(hDC, GetStockObject(DC_BRUSH)); SelectObject(hDC, GetStockObject(NULL_PEN)); SetTextColor(hDC, textcolor); Rectangle(hDC, rc.left, rc.top, rc.right, rc.bottom); auto oldfont = SelectObject(hDC, hfont); wchar_t buffer[1000] = { 0 }; ListView_GetItemText(pDIS->hwndItem, pDIS->itemID, 0, buffer, 1000); DrawText(hDC, buffer, -1, &rc, DT_SINGLELINE | DT_VCENTER); SelectObject(hDC, oldfont); return TRUE; } *hfont is not destroyed in above window procedure. It should be cleaned up elsewhere.
{ "pile_set_name": "StackExchange" }
Q: StackOverflowError in servlet mapping with url-pattern "/*" I have a set of JSP pages and I want to hide the .jsp extension (after a bit of research it seems it's good for SEO). One solution I came across was the following: <servlet> <servlet-name>mypage</servlet-name> <jsp-file>/some-page.jsp</jsp-file> </servlet> <servlet-mapping> <servlet-name>mypage</servlet-name> <url-pattern>/some-page</url-pattern> </servlet-mapping> And while this works, I believe I have to set up this mapping for every jsp page on my site. I came across another solution posted here (Easy friendly URL's): Hidden features of JSP/Servlet ... which uses a simple servlet to forward the request. In my web.xml I have the following and it works fine: <servlet> <servlet-name>MyServletName</servlet-name> <servlet-class>myservlets.PrettyUrlServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyServletName</servlet-name> <url-pattern>/myservlet/*</url-pattern> </servlet-mapping> Now the problem is I don't want to hit the URL: www.mydomain.com/myservlet/some-page I want to use the URL: www.mydomain.com/some-page So I changed the url-pattern to "/*" <servlet> <servlet-name>MyServletName</servlet-name> <servlet-class>myservlets.PrettyUrlServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyServletName</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> But this causes an infinite loop: Exception in thread "http-bio-8080-exec-1" java.lang.StackOverflowError at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:219) at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:228) . . at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:228) at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:228) at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:379) at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329) at myservlets.PrettyUrlServlet.doGet(PrettyUrlServlet.java:22) Which I'm not sure how to fix. Any ideas? A: A servlet which is mapped on /* will also run on RequestDispatcher#forward() calls. So if you're performing a forward in that servlet, it would call itself everytime in an infinite loop. That explains the StackOverflowError. After all, you should not be using /* for servlets at all. It only makes sense on servlet filters. Put the servlet mapping back on a more specific URL pattern and create a filter on /* which forwards to the desired servlet when necessary. You of course don't want to have the servlet to handle for example images/CSS/JS files. Assuming that they're all placed in /resources folder and that your front controller is mapped on /myservlet/*, then do the following job in doFilter(): HttpServletRequest req = (HttpServletRequest) request; String path = req.getRequestURI().substring(req.getContextPath().length()); if (path.startsWith("/resources/")) { // Just let container's default servlet do its job. chain.doFilter(request, response); } else { // Delegate to your front controller. request.getRequestDispatcher("/myservlet" + path).forward(request, response); } See also: URL mapping in Tomcat to FrontController servlet
{ "pile_set_name": "StackExchange" }
Q: Anonymous struct with enable/disable I have the following vector class (vector as in spatial, not array): template<typename T0, size_t S, typename = typename std::enable_if<std::is_arithmetic<T0>::value && (S > 1 && S < 5)>::type> struct Vec { using value_type = T0; using vector_type = Vec<T0, S>; using array_type = std::array<T0, S>; using index_type = size_t; using size_type = size_t; enum { num_components = S }; array_type v; }; , such that I can make a vector type with 2, 3 or 4 elements: template<typename T0> using Vec2 = Vec<T0, 2>; template<typename T0> using Vec3 = Vec<T0, 3>; template<typename T0> using Vec4 = Vec<T0, 4>; Access is of the form v[0], v[1], etc. (for brevity I don't include the [] operator overloads). Sometimes I prefer x, y and so on but don't want the extra "." from naming the structs in the union. So using a non-standard "feature" of Visual Studio 2013, tried to use an anonymous union, only enabling the value if S (dimension) is 2, 3 or 4, as follows: template<typename T0, size_t S, typename = typename std::enable_if<std::is_arithmetic<T0>::value && (S > 1 && S < 5)>::type> struct Vec { using value_type = T0; using vector_type = Vec<T0, S>; using array_type = std::array<T0, S>; using index_type = size_t; using size_type = size_t; enum { num_components = S }; union { array_type v; template<typename = typename std::enable_if<S == 2>::type> struct { value_type x, y; }; template<typename = typename std::enable_if<S == 3>::type> struct { value_type x, y, z; }; template<typename = typename std::enable_if<S == 4>::type> struct { value_type x, y, z, w; }; }; }; Unfortunately this gives me the following error: **error C2332: 'struct' : missing tag name** And in a way I suppose it is. Is there any way to achieve what I'm trying here? I'm sure enable/disable of an anoymous struct almost certainly gives the compiler a migrane. I can use anonymous union like this if I give the struct a name of course. A: Why do you decide that memory layout of std::array and struct{ T x, T y, ... T} will be identical? It can be reached only if you reset alignment setting to 1 for your class with #pragma pack. For others the alignment is unpredictable. You want to have such class that provides access via data member selectors such as .x, .y and so on provides direct access to data member via operator[] does not break default data member alignment (std::array is linear, it breaks compiler optimization alignment for your class data member) The following code meets the above requirements without any non-standard features: template<typename T, size_t S> struct Vec; template<typename T> struct Vec<T, 1> { enum {count = 1}; T x; T& operator[](size_t i) { assert(i == 0); return x; } const T& operator[](size_t i) const { assert(i == 0); return x; } }; template<typename T> struct Vec<T, 2> { enum { count = 2 }; T x; T y; T& operator[](size_t i) { assert(0 <= i && i < count); return this->*(pointer(i)); } const T& operator[](size_t i) const { assert(0 <= i && i < count); return this->*(pointer(i)); } static T Vec::* pointer(size_t i) { static T Vec::* a[count] = { &Vec::x, &Vec::y }; return a[i]; } }; template<typename T> struct Vec<T, 3> { enum { count = 3 }; T x; T y; T z; T& operator[](size_t i) { assert(0 <= i && i < count); return this->*(pointer(i)); } const T& operator[](size_t i) const { assert(0 <= i && i < count); return this->*(pointer(i)); } static T Vec::* pointer(size_t i) { static T Vec::* a[count] = { &Vec::x, &Vec::y, &Vec::z }; return a[i]; } }; int main() { Vec<int, 2> v1{ 1, 2 }; assert(v1[0] == v1.x); assert(v1[1] == v1.y); Vec<unsigned char, 3> v2{ 4, 5, 6 }; assert(v2[0] == v2.x); assert(v2[1] == v2.y); assert(v2[2] == v2.z); return 0; }
{ "pile_set_name": "StackExchange" }
Q: How to use an element belonging to an if-else cycle outside the cycle? I need to use the variable of an if-else loop as an argument of a method or lets say somewhere out of the if-else loop but in the same class. public static String myvar; if(x > 5) { myvar = 0 ; Double y = Double.parseDouble(myvar); System.out.println("The value is: "+ y); } else { Double y= Double.parseDouble(myvar); System.out.println("The value is: "+ y); } So whenever i use the variable y somewhere out of the loop, it can not be resolved to a variable..How to use this variable out of the if-else loop? A: Just declare variable outside if-else, right before. Double y = 0; if () y =X; else y =Y; A: You have to declare and initialize the y variable out of the if-else loop. Also your statement myvar = 0; will not compile as myvar is a String. String myvar = "0"; Double y = 0.0; if(x > 5) { y = Double.parseDouble(myvar); System.out.println("The value is: "+ y); } else { y= Double.parseDouble(myvar); System.out.println("The value is: "+ y); }
{ "pile_set_name": "StackExchange" }
Q: Sylow $p$-subgroup of GL I know that for general linear group $\mathrm{GL}(n,p^r)$, one Sylow $p$-subgroup is the set of all unitriangular matrices. I need a reference for this theorem. Thank you. A: Steinberg's "Lecture Notes on Chevalley Groups" the Corollary of Lemma 54 on page 132. There is possibly a more modern reference. EDIT: Sorry the reference to Steinberg is not sufficient as he does not treat arbitrary finite reductive groups. However all that is needed is to obtain a slightly more general formula for the order of an arbitrary finite reductive group. This is obtained, for instance, in Corollary 4.2.5 of Geck's book "An Introduction to Algebraic Geometry and Algebraic Groups". the important point is a theorem of Rosenlicht about the fixed points of a connected unipotent group under a Frobenius endomorphism. If $\mathbf{U}$ is a connected unipotent affine algebraic group with Frobenius endomorphism $F' : \mathbf{U} \to \mathbf{U}$ then the finite group $\mathbf{U}^{F'}$ has order $q^{\dim\mathbf{U}}$, (see Geck - Theorem 4.2.4). Now take $\mathbf{G} = \mathrm{GL}_n(\overline{\mathbb{F}}_p)$ and $F$ to be the map given by $F(x_{ij}) = (x_{ij}^q)$ where $q = p^a$ for some integer $a$ then $\mathbf{G}^F = \mathrm{GL}_n(q)$. The subgroup $\mathbf{B} \leqslant \mathbf{G}$ of upper triangular matrices is an $F$-stable Borel subgroup of $\mathbf{G}$ and its unipotent radical $\mathbf{U} \leqslant \mathbf{B}$ is the subgroup of all upper uni-triangular matrices. This has maximal dimension amongst all connected unipotent subgroups of $\mathbf{G}$, which can be seen in the following way. Assume $\mathbf{V} \leqslant \mathbf{G}$ is a connected unipotent subgroup of $\mathbf{G}$ then as $\mathbf{V}$ is solvable it is contained in a Borel subgroup $\mathbf{B}'$ of $\mathbf{G}$. As $\mathbf{V}$ is a unipotent subgroup of $\mathbf{B}'$ it is contained in the unipotent radical of $\mathbf{B}'$ and as all Borel subgroups of $\mathbf{G}$ are conjugate we have the unipotent radicals of $\mathbf{B}$ and $\mathbf{B}'$ have the same dimension. In particular, we have $\dim\mathbf{V} \leqslant \dim \mathbf{U}$. Now applying Rosenlicht's theorem we see that the order of $\mathbf{U}^F$ is a power of $p$. We can now apply Steinberg's argument to the order formula for finite reductive groups to deduce that the index of $\mathbf{U}^F$ in $\mathbf{G}^F$ is coprime to $p$. This approach has the advantage that it shows that the fixed points of the unipotent radical of any $F$-stable Borel subgroup of $\mathbf{G}$ is a Sylow $p$-subgroup of $\mathbf{G}^F$.
{ "pile_set_name": "StackExchange" }
Q: Repartition my existing hard disk First time Mac user here. I'm quite aware with all the posts here about repartitioning hard disk but I'm quite confused if repartitioning would erase all my data on my hard disk. I recently bought my Mac and it was pre-installed with Lion, and my hard disk size is 750GB, and under in one partition only. I would like to divide the disk into at least 2 partitions where I can put my music files so that it would be easier to backup with any backup/imaging software. With my current setup, it means that I have a recovery partition on my disk that would allow me to reinstall Lion if problems would occur. If it would erase all existing data on the disk if I repartition it, then my only choice is to do this: 1) Backup first my data using Time Machine 2) Boot from the recovery partition and erase and partition (3) the hard disk 3) Restore the image to the disk to the desire partition What do you guys think? A: Make sure to back up all of your data first, just in case. Next, create a USB Recovery HD (at least 1GB) with these Apple forum instructions: Create a USB thumb drive Recovery HD using the Lion Recovery Disk Assistant. Download this and install it. Then, insert a thumb drive and create your bootable Recovery HD. Last, boot from the USB thumb drive and from inside the Recovery HD on that, try the resize. You should be able to resize your main partition after booting from the USB Recovery HD. Another option is to use the Recovery HD on your Mac, as noted in the solution that @bmike suggested in another question - boot to your Recovery HD and use Disk Utility there to resize. The solution that you've mentioned will work, but is a bit more work.
{ "pile_set_name": "StackExchange" }
Q: Does the green-flame blade extra damage work on normal attacks? Can you do a green-flame blade cantrip (duration of 1 round), do an Action Surge and then a normal attack action with Extra Attack and have all attacks have the green-flame blade bonus damage since it have a duration of 1 round and should also work with opportunity attack in the same round? A: You don't get extra damage on the later attacks Green flame blade doesn't have a duration of 1 round. It is Instantaneous. The spell has you make one attack, which gets extra damage. No other attacks do so. As part of the action used to cast this spell, you must make a melee attack with a weapon against one creature within the spell’s range, otherwise the spell fails. On a hit, the target suffers the attack’s normal effects, and [extra damage is applied] If other attacks would get damage from green flame blade it would have a longer duration, as would say something along the lines of For the duration of this spell, when you hit with a melee weapon attack a creature within 5 feet of the target takes [...] You can use Action Surge to get an another attack with extra damage by casting green flame blade using the extra action, but you would only get the attack described by the spell.
{ "pile_set_name": "StackExchange" }
Q: dplyr lag across groups I am trying to do something like a lag, but across and not within groups. Sample data: df <- data.frame(flag = c("A", "B", "A", "B", "B", "B", "A", "B", "B", "A", "B"), var = c("AB123","AC124", "AD125", "AE126", "AF127", "AG128", "AF129", "AG130","AH131", "AHI132", "AJ133")) ) The goal for every flag="B" is to create lagvar with the previous var value where flag="A". This will show the desired output: df1 <- data.frame(flag = c("A", "B", "A", "B", "B", "B", "A", "B", "B", "A", "B"), var = c("AB123","AC124", "AD125", "AE126", "AF127", "AG128", "AF129", "AG130","AH131", "AHI132", "AJ133"), lagvar = c("","AB123","","AD125","AD125","AD125","","AF129","AF129","","AHI132") ) A dplyr solution is preferred, but I'm not picky! EDIT: I found a solution using the zoo package but am interested if others have better ideas. df$lagvar <- ifelse(df$flag == "A", df$var, NA) df <- df %>% mutate(lagvar = na.locf(lagvar) A: Here you go. I used NA instead of blanks, but you can adjust as needed: df %>% mutate(lagvar = ifelse(flag == "A", as.character(var), NA), lagvar = zoo::na.locf(lagvar), lagvar = ifelse(flag == "A", NA, lagvar)) # flag var lagvar # 1 A AB123 <NA> # 2 B AC124 AB123 # 3 A AD125 <NA> # 4 B AE126 AD125 # 5 B AF127 AD125 # 6 B AG128 AD125 # 7 A AF129 <NA> # 8 B AG130 AF129 # 9 B AH131 AF129 # 10 A AHI132 <NA> # 11 B AJ133 AHI132
{ "pile_set_name": "StackExchange" }
Q: STP in a mixed environment Good day all, We have some a mixed environment of Dell Powerconnect and Cisco switches. On both brands of switches, I am seeing numerous STP topology changes. I've decided to try on work on the Dell switches first. The root switch is a Cisco 6500. Though the logs on the Dell switches show numerous topology changes within seconds, the root bridge remains the same. It is my understandings that topology changes should only really occur when switches are added or removed or root ports go down. Should I be concerned about these topology changes? Any help will be greatly appreciated. Thank you. A: Are you actually seeing Toplogoy changes or are you seeing only Topology Change Notifications? If the latter than that's fairly normal but TCN's can cause a degree of network flooding if there are too many of them. One source of TCN's that can cause TCN flooding are host ports that aren't configured with the Cisco equivalent of portfast. If your host connected ports aren't configure for portfast they should be.
{ "pile_set_name": "StackExchange" }
Q: C#: How does the static object.Equals check for equality? Say you have two different classes where each have their own implementation of Equals; which one is used? What if only one of them have one? Or none of them? Are any of the following lines equivalent? object .Equals( first, second ) first .Equals( second ) second .Equals( first ) I'm guessing that the first two might be equivalent, but I don't really have a clue. What does it really do? A: Basically it does three things: Check for reference equality (return true if so) Check for reference nullity (return false if either value is null; by now the null == null case has been handled) Check for value equality with first.Equals(second) The ordering shouldn't matter if both values have well-behaved equality implementations, as equality should be implemented such that x.Equals(y) implies y.Equals(x). However, the offline documentation I've got installed does state that first.Equals(second) (or objA.equals(objB) to use the real parameter naming) is specified. The online documentation doesn't mention this, interestingly enough. Just to make all of this concrete, the implementation could look like this: public static bool Equals(object x, object y) { if (x == y) // Reference equality only; overloaded operators are ignored { return true; } if (x == null || y == null) // Again, reference checks { return false; } return x.Equals(y); // Safe as we know x != null. }
{ "pile_set_name": "StackExchange" }
Q: How can I optimize my Two Sums code in Python? I'm attempting the first problem on leetcode and my code passes the first 19 tests but fails due to a time exceeded failure on the last test. This is what I have so far: class Solution: def twoSum(self, nums, target): k = 0 n = len(nums)-1 temp = [] for x in range(k,n): for y in range(k+1,n+1): if (nums[x]+nums[y] == target) and (x < y): temp.append(x) temp.append(y) break return temp Please let me know if you have any information that you think could potentially help me. For those of you unfamiliar with the two sums problem. Here it is: Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1] I'm asking about the specifics about how to optimize MY code, not have other people write the code for me. Afterall, memorizing code won't do me any good if I don't know how to do it myself with my own thought processes. I'm asking for advice. A: You can probably speed things up a little bit using itertools, e.g.: for i, j in it.combinations(range(len(nums)), r=2): if nums[i] + nums[j] == target: return [i, j] Or alternatively: for (i, x), (j, y) in it.combinations(enumerate(nums), r=2): if x+y == target: return [i, j] An improvement to your code is in your second loop, to start from x+1 vs k+1, this removes the need for the and expression. And just immediately return vs. .append() which is relatively expensive. E.g.: n = len(nums)-1 for x in range(0, n): for y in range(x+1, n+1): if nums[x]+nums[y] == target: return [x, y] Loops in this structure is exactly what itertools.combinations() does.
{ "pile_set_name": "StackExchange" }
Q: Does iOS 6 support the timezone PHT when trying to use NSDateFormat? I am having problems with my code and not sure what is wrong with it. NSString* dateFormat1 = @"EEE MMM dd HH:mm:ss V yyyy"; NSString* dateString1 = @"Fri Jul 26 00:00:00 PHT 2013"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; [dateFormatter setDateFormat:dateFormat1]; My result for iOS5.1: 2013-08-02 11:59:08.459 MySandbox[41502:c07] 2013-07-25 16:00:00 +0000 For iOS 6.0 2013-08-02 12:02:37.454 MySandbox[41581:c07] (null) *Note, I used V, instead of zzz or Z because it still is null. *Note 2, I tried to change PHT to PST and it worked. Changed it to JST, it didn't work. I am guessing that I am not using the correct format. Not really sure which I should use. *Note 3, as per this question, there really was a change in iOS5 and iOS6 so I guess that is the reason why iOS5 worked. A: According to these docs from Apple, NSDateFormatter uses the Unicode date format patterns, which are part of "Unicode Technical Standard #35". This standard is evolving, and iOS 5 uses version 19 while iOS 6 uses version 25. You can read about the supported values for the time zone in "Appendix J: Time Zone Display Names" (version 19 or version 25). I am not exactly sure why PHT was supported before and not it isn't. But in general, the best advice I can give is to avoid using time zone abbreviations. While PHT is unique, there are many other abbreviations that are ambiguous. See the list here. Instead, you should uses the IANA time zone name whenever possible. (The tr-35 standard calls this the "Golden Zone"). In your case, it would be Asia/Manila. You can find a full list here. I am not an Objective C developer, so I'm not sure exactly how you would use this in your input string. You can try the VVVV format specifier, but I'm not sure if it directly accepts the IANA name or not. You might want to check the results from [NSTimeZone abbreviationDictionary] as shown in this answer. In that post, it does show PHT = "Asia/Manila", but I assume by the date that it was posted that these were generated from iOS 5.
{ "pile_set_name": "StackExchange" }
Q: How to encode Email if it contains "+" to %2B in Ruby How to encode URL parameters with UTF8 encoding: URL?email=test+@gmail.com to URL?email=test%2B@gmail.com I tried 'test+@gmail.com'.encode("UTF-8") CGI::escape('test+@gmail.com') it returns 'test%2B%40gmail.com But i need test%2B@gmail.com email=test+@gmail.com should encode to "+"only rest remain same URL?email=test%2B@gmail.com A: The uri std-lib has a method for that URI::Escape#escape. URI extends the URI::Escape module, so also has this method. URI.escape('test+@gmail.com', '+') #=> "test%2B@gmail.com" ^ the characters to escape with URL encoding However like @spickermann says in the comments: Why do you want to encode the + in the URL but not the @? @ must be encoded too.
{ "pile_set_name": "StackExchange" }
Q: Runnig python from sublime text extremely slow I'm testing Sublime Text 2 with Python. A simple hello python script takes multiple seconds. print "Hello from Python" Hello from Python [Finished in 11.8s] Any ideas why? A: Just the first run, since the second it's fast. Because it takes time to load python interpreter, parsing the byte-codes and actually running. First: Hello from Python [Finished in 5.4s] Second and later: Hello from Python [Finished in 0.1s]
{ "pile_set_name": "StackExchange" }
Q: Design of high volume TCP Client I have a .NET TCP Client that sends high volumes of messages to a (.NET async) TCP server. I need to keep sending messages to the server but I run out of ports on the client due to TIME_WAIT. How can a program continually and reliably send messages without using all of the available ports? Is there a method to keep reusing the same socket. I have looked at Disconnect() and the REUSEADDRESS socket flag but cannot find any good examples of their use. In fact most sources say not to use Disconnect as it is for lower level use (i.e. it only recycles the socket handle). I'm thinking that I need to switch to UDP or perhaps there is a method using C++ and IOCP? A: You can keep the socket open if your server and client are aware of the format of the data. You're closing the socket so that the server can "see" that the client is "done". If you have some protocol, then the server can "know" when it's finished receiving a block of data. You can look for an End-of-message token of somekind, you can pass in the length of the message, and read the rest based on size, etc. Different ways of doing it. But there's no reason to constantly open and close connections to the server -- that's what's killing you here.
{ "pile_set_name": "StackExchange" }
Q: Does the Burning Disarm spell allow the target to attempt a Reflex save if the metal object is worn, but not locked? The Burning Disarm spell says the target gets a Reflex save if they can drop it, but don't if they can't drop it (emphasis mine): This spell causes a metal object to instantly become red hot. A creature holding the item may attempt a Reflex save to drop it and take no damage (even if it is not their turn), otherwise the hot metal deals 1d4 points of fire damage per caster level (maximum 5d4). Circumstances that prevent the creature from dropping the item (such as a locked gauntlet) mean the creature gets no saving throw. The heat does not harm the item, and it does not get hot enough or last long enough to ignite flammable objects. The item cools to its previous temperature almost instantly. If cast underwater, burning disarm deals half damage and boils the surrounding water. What about if they are wearing something that isn't locked? It seems to me that if you have to grab it off yourself, then you would take the damage, but I couldn't find a clarification regarding this. A: The target of Burning Disarm is a held metal object. It can't be cast on something worn. The reference to a locked gauntlet is to a specific piece of equipment that stops you from dropping your held item promptly.
{ "pile_set_name": "StackExchange" }
Q: free() collecting garbage value in c code and code doesn't work even when setting the pointer to NULL after freeing When I try to call free() function to free the memory, it isn't working properly. Here is my code: unsigned char *indata; unsigned char *outdata; int file_func(const char *filename) { //some other variables for(i=0;i < no_of_files;i++) { indata = malloc(sizeof(unsigned char)); outdata = malloc(sizeof(unsigned char)); //counts the number of characters from filename numCharacters = readfile(filename, indata); /* perform some operation on indata and get outdata(size is same as indata)*/ writefile(filename, outdata); //writes outdata to filename free(indata); free(outdata); } } The above code does not work properly because free() is storing some random garbage value at indata & outdata(as they become dangling pointers). So I tried setting the pointers to null after freeing since I'm reusing the same pointers as: free(indata); indata = NULL; free(outdata); outdata = NULL; Even then my code gets crashed as : double free or corruption (out): 0x00000000025aa240 * How can I overcome this problem or is there any other alternative to use dynamic sized pointers in a loop. Thank you. A: You're only allocating 1 byte (sizeof(unsigned char)) for each of those variables. Either that's a mistake and you wanted to allocate sizeof(unsigned char) * some_number where some_number is dynamic, or you could just allocate on the stack: unsigned char indata, outdata; // then use &indata and &outdata where you need a pointer or unsigned char indata[some_number]; unsigned char outdata[some_number]; or you can malloc once before the loop and free once after it. The double free problem looks like one of the functions you're calling in the loop is calling free. Look carefully at readfile and writefile.
{ "pile_set_name": "StackExchange" }
Q: R difftime off by 1 year I'm trying to calculate the difference-in-years between 2 dates. time1 <- as.Date(x = "2017-02-14", format = "%Y-%m-%d", origin = "", tz = "") time2 <- as.Date(x = "1972-02-17", format = "%Y-%m-%d", origin = "", tz = "") as.integer(x = difftime(time1 = time1, time2 = time2, tz = "", units = "days")) / 365 According to the above code, the difference-in-years is about 45.02466. A glance at the 2 dates confirms that the difference-in-years is close to, but less than, 45. The difference-in-years value should begin with 44. Why is difftime inflating the number of years by 1? A: Probably this happens since you divide by 365 days, whereas at least 44/4 = 11 years had a duration of 366 days. You could consider to divide by 365.25, which is a more correct average duration of a year. Also, you might like to look up the lubridate package to see the interval of how many years have passed between two dates library(lubridate) > time1 <- as.Date(x = "2017-02-14", + format = "%Y-%m-%d", + origin = "", + tz = "") > > time2 <- as.Date(x = "1972-02-17", + format = "%Y-%m-%d", + origin = "", + tz = "") > > > interval(time2, time1) %/% years(1) [1] 44
{ "pile_set_name": "StackExchange" }
Q: How to find unknown character in mysql or in array First I created database with utf8mb4_general_ci collation and created table with same collation. Then I import csv file with load data local infile '/mnt/c/Users/justi/Desktop/enml/enml.csv' into table dict CHARACTER SET utf8mb4 fields terminated by '\t' IGNORE 1 ROWS; Sample data +--------+----------------+----------------+---------------------------------+ | # id | english_word | part_of_speech | malayalam_definition | +--------+----------------+----------------+---------------------------------+ | 174569 | .net | n | പുത്തന്‍ കമ്പ്യൂട്ടര്‍ സാങ്കേതികത ഭാഷ | +--------+----------------+----------------+---------------------------------+ | 116102 | A bad patch | n | കുഴപ്പം പിടിച്ച സമയം | +--------+----------------+----------------+---------------------------------+ | 219752 | a bag of bones | phr | വളരെയതികം മെലിഞ്ഞ വ്യക്തി അഥവാ മൃഗം | +--------+----------------+----------------+---------------------------------+ I check with SELECT malayalam_definition from dict; then var_dump($row); gives array(1) { ["malayalam_definition"]=> string(19) "ശരശയ്യ " } array(1) { ["malayalam_definition"]=> string(22) "പൂമെത്ത " } array(1) { ["malayalam_definition"]=> string(41) "സുഖകരമായ അവസ്ഥ " } array(1) { ["malayalam_definition"]=> string(44) "അസുഖകരമായ അവസ്ഥ " } array(1) { ["malayalam_definition"]=> string(22) "പൂമെത്ത " } array(1) { ["malayalam_definition"]=> string(123) "സുഖകരമെങ്കിലും സ്വാതന്ത്യ്രമില്ലാത്ത അവസ്ഥ " } ... You can find an unknown character after each word like "ശരശയ്യ ". I tried select trim(malayalam_definition) from dict but gives same result. how to find out that character after each words? A: Converting the string to hex is one way: SELECT HEX(malayalam_definition),CONCAT("{",malayalam_definition,"}") FROM dict WHERE id=116102
{ "pile_set_name": "StackExchange" }
Q: Using "there're" to abbreviate "there are" Possible Duplicate: Is “there're” (similar to “there's”) a correct contraction? Since using there's for a plural object would be incorrect, would it be possible to use there're to abbreviate there are? e.g. I've been told there're many different ways to solve this problem. A: There's no special "watchdog" likely to come knocking on the door in the middle of the night if you use it, but it's relatively uncommon (witness that thin blue line at the bottom of the chart)... On the other hand, there're over 400,000 instances, and it is more common than it was... In short, there're doesn't have anything like the "accepted status" of there's, so if you want to be beyond reproach, avoid it. But don't feel you're completely alone if you insist on using it. Personally, I wouldn't criticise the usage, but it's not something I'd normally (ever?) do myself. A: It's not incorrect, but it's difficult to say /'ðɛrər/, with two /r/s in a row, so mostly nobody does. The purpose of a contraction is to make things easier to say, not harder. This difficulty is one of the forces that has led to widespread use and acceptance of there's as an unchanging existential idiom, like Es gibt in German, Hay in Spanish, Il y a in French, Yeʃ in Hebrew, etc. Another is the fact that, if you think about it, number agreement contributes nothing to the meaning in this idiom, and should not appear at all, since the subject is there, which is a dummy noun that means nothing and is neither singular nor plural by logic, so by convention it should be singular. That's good enough for nobody as a subject, too: Nobody is coming, even though it's neither singular nor plural, and even though it may represent many individual people and their individual decisions. A: In rapid speech, there are will come out as something like /ðɛərə/ (rhyming with ‘tear a’). A writer who wants to give some idea of the actual speech of the participants in a dialogue may choose to represent it as there’re, but otherwise the contraction would not, I suspect, normally be found in formal prose.
{ "pile_set_name": "StackExchange" }
Q: Detect repetitive pixel patterns in an image and remove them using matlab I'm using Matlab R2017a and I have a RGB image (TIFF 128x128 uint16), shown below as a png image: Actual TIFF image: http://s000.tinyupload.com/index.php?file_id=13823805859248753003 As shown above, there's a repeating pattern of really light pixels (yellow and light blue). Because I'm using pixel data, the really light pixels are skewing my graphs, so I want to "neutralize" them. I looked everywhere but I couldn't find a clean pattern recognition/removal set of commands, so I ended up finding the rows in the image where there were more than 10 pixels with intensity value > 1036 - there were 19 rows. From there, I found the indices where these brightest pixels occur, and stored them in a 19-cell cell array - cellarray{}. I can get those brightest pixel values by running image(cellarray{n}), where n goes from 1-19. From here, I want to "neutralize" these super bright pixels by taking the average of the "normal" pixels above and below it. But if it is adjacent to another really bright pixel, I want its new pixel value to be the average of the closest pixels that are "normal". I hope that makes sense... Can someone help me with the code or suggest an easier method? Thanks so much! A: Two methods are proposed, one using cross correlation the other using brightness. They work with both grayscale and multiband images. You should play with the settings a bit to improve the result. Important: fillmissing requires Matlab 2016b or newer Method A) Using cross correlation This works by extracting a single occurrence of the pattern and finding the location on the images where the correlation is very high. While it provides better results than Method B, it is also more complicated and needs a bit more knowledge about what you are doing: I = double(yourimage); % Show image imagesc(I) % You have to select a part of single occurrence of the pattern (a template) on the image! See below image. rect = round(getrect); % In case it is a multiband image make grayscale image if size(I,3)>1 BW = rgb2gray(I); else BW = I; end % Extract template from BW template = BW(rect(2):rect(2)+rect(4),rect(1):rect(1)+rect(3),:); % Show template - this is the extent you selected during "getrect" imagesc(template) % Calculate how much said template correlates on each pixel in the image C = normxcorr2(template,BW); % Remove padded borders from correlation pad = floor(size(template)./2); center = size(I); C = C([false(1,pad(1)) true(1,center(1))], ... [false(1,pad(2)) true(1,center(2))]); % Plot the correlation figure, surf(C), shading flat Correlation of the template on the image. Note that it both highly correlates with the bright yellow patterns and the light blue pattern bellow. % Get all indexes where the correlation is high. Value read from previous figure. % The lower the cut-off value, the more pixels will be altered idx = C>0.5; % Dilate the idx because else masked area is too small idx = imdilate(idx,strel('disk',1)); % Replicate them if multiband image. Does nothing if only grayscale image idx = repmat(idx,1,1,size(I,3)); % Replace pattern pixels with NaN I(idx) = NaN; % Fill Nan values with 4x4 median filter I = fillmissing(I,'movmedian',[4 4]); % Display new image figure; imagesc(I) It catches both the yellow and light blue pattern but also some false positives. You have to experiment with different templates, cut-off values, dilation radii and median filter sizes to improve the result. Method B) Using brightness of image A bit offtopic because no pattern recognition is used but instead that the yellow patterns are just very bright. But since the result isn't too bad and a lot simpler I felt it might be useful. A lot easier to avoid finding false positives. % I = your image I = double(I); % get indexes where very bright in red channel idx = cdata(:,:,1)>157; % 157 = brightest non-pattern pixel in your image % From now on same as end from method A)! % dilate the idx to also get the adjacent pixels because else too few pixels will be erased idx = imdilate(idx,strel('disk',1)); % replacate them if multiband image. Does nothing if only grayscale image idx = repmat(idx,1,1,size(I,3)); % replace pattern pixels with NaN I(idx) = NaN; % fill Nan values using 50x50 median filter I = fillmissing(I,'movmedian',[50 50]); % display new image figure; imagesc(I)
{ "pile_set_name": "StackExchange" }
Q: How to set an alert box in Android and is there any API to send data from an app to a URL I am a new developer. I am facing some problems in my new app. I have placed three edit boxes. When the user hits the button next to those edit boxes, I want to set up an alert box if any of the edit boxes is not yet filled up. When the user hits the button next to those edit boxes after filling up all the data correctly, it must intents to the new page and at the same time I want to send the data to a particular URL. Is there any API for this? I am familiar with normally moving over from one page to the other. I have already asked about sending data to an URL in SO but I didn't get a clear answer. Please help me in clearing these problems. I am a fresher to this Android and I don't have any colleague in the same field. Please help me. A: This is the answer of First Question . Show Alert Dialog This is the Answer of Second Question . Send Data To Server . In second answer it only send data to the server and you have to implemented script at the sever side to fetch the data.
{ "pile_set_name": "StackExchange" }
Q: How to hide a custom text attribute which displayed in product edit backend I am using Magento 2.2.5 I need to hide a text attribute which I'm using to save serialized data of custom options of product. I think this can be done using adminhtml/ui_component/product_form.xml file, but don't know how. Thanks A: You can try below steps to hide product fields Step 1: create catalog_product_edit.xml under app/code/Vendor/Module/view/adminhtml/layout File : catalog_product_edit.xml <referenceContainer name="content"> <block class="Magento\Framework\View\Element\Template" name="myattribHide" before="before.body.end" template="Vendor_Module::product/edit/fieldhide.phtml" /> </referenceContainer> Step 2: Create file fieldhide.phtml under app/code/Vendor/Module/view/adminhtml/templates/product/edit File : fieldhide.phtml <script> require([ 'jquery', 'uiRegistry' ], function($,uiRegistry){ uiRegistry.get("product_form.product_form.content.container_yourcustomfield.yourcustomfield", function (element) { element.hide(); }); }) </script> Note : Please replace "yourcustomfield" with your attribute code Step 3: Please remove static files and refresh cache
{ "pile_set_name": "StackExchange" }
Q: Symfony2 Doctrine2 - generate Many-To-Many annotation from existing database by doctrine:mapping:import I want to generate Entities from an Existing Database by using Doctrine tools for reverse engineering you can ask Doctrine to import the schema and build related entity classes by executing the following two commands. 1 $ php app/console doctrine:mapping:import AcmeBlogBundle annotation 2 $ php app/console doctrine:generate:entities AcmeBlogBundle but now the doctrine detect only ManyToOne relation in many side only "ProviderCountry" table if i need to add the ManyToMany relation i have to add the annotation by my hand by adding the follwing annotation in Country.php add /** * * @var Provider $provider * * @ORM\ManyToMany(targetEntity="Provider") * @ORM\JoinTable(name="provider_country", * joinColumns={@ORM\JoinColumn(name="countryId", referencedColumnName="id")}, * inverseJoinColumns={@ORM\JoinColumn(name="providerId", referencedColumnName="id")} * ) * */ private $providers; in Provider.php add /** * @var Country $country * * @ORM\ManyToMany(targetEntity="Country") * @ORM\JoinTable(name="provider_country", * joinColumns={@ORM\JoinColumn(name="providerId", referencedColumnName="id")}, * inverseJoinColumns={@ORM\JoinColumn(name="countryId", referencedColumnName="id")} * ) * */ private $countrys; so how can I generate Many-To-Many annotation by doctrine command [doctrine:mapping:import] Thanks in advance. A: you can do this by add the following lines in vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php $tables = array(); $tables[] = $schemaManager->listTableDetails("country"); $tables[] = $schemaManager->listTableDetails("provider_country"); $tables[] = $schemaManager->listTableDetails("provider"); $this->setTables($schemaManager->listTables(), $tables); inside __construct public function __construct(AbstractSchemaManager $schemaManager) Note: That will override OneToMany annotation.
{ "pile_set_name": "StackExchange" }
Q: Обобщения по Шилдту закрытый / открытый тип Господа, учу обобщения по Шилдту и наткнулся на такую вот цитату: C# чаще определяются такие понятия, как открытый и закрытый типы. Открытым типом считается такой параметр типа или любой обобщенный тип, для которого аргумент типа является параметром типа или же включает его в себя. А любой тип, не относящийся к открытому, считается закрытым. Сконструированным типом считается такой обобщенный тип, для которого предоставлены все аргументы типов. Если все эти аргументы относятся к закрытым типам, то такой тип считается закрыто сконструированным. А если один или несколько аргументов типа относятся к открытым типам, то такой тип считается открыто сконструированным. Если честно, то не понял ни слова из этой фразы. Понял лишь, что сконструированный тип - это тип, которому выписали аргументы. А вот что такое открытый и закрытый тип - вообще не въехал. Если не трудно, объясните, пожалуйста, на пальцах, что это значит (открыты/закрытый тип). Буду дико благодарен. A: эта ваша книга случайно не гуглопереводчиком переведена? Давно не встречал такого косноязычия. Если у вас книга переведена автоматически, то найдите нормальный перевод. Если же перлы типа "C# чаще определяются такие понятия" - дело рук человека-переводчика, то такому толмачу надо забить гвоздь в голову. Я не первый год работаю с шарпом, но в этом заклинании честно говоря тоже мало что понял A: Как я понял, этот текст имеет в виду отличие generic-типа, в котором есть конкретные типы-аргументы, и типа, в котором их нет (List<int> против List<T> для generic-параметра T). И кстати: не советую учить по Шилдту. Он был не очень хорошим автором, и вряд ли стал лучше.
{ "pile_set_name": "StackExchange" }
Q: Ansible - combining string with an existing variable to register into another variable I want to combine a fact set with set_facts with a string variable and register it as a new variable. I think, we cannot register a new variable in an Ansible playbook. So can I use set_facts again to combine a previous set_fact with an existing variable? I am not sure about the syntax here. Here is an example: - vars: list_1: usera,userb,userc - set_fact: list_2: "userd,usere,userf" Now I want to combine both of the string with comma in between and get a variable value like this: final_list: usera,userb,userc,userd,usere,userf A: set_fact: final_list: "{{ list_1 }},{{ list_2 }}" or use the string concatenation operator set_fact: final_list: "{{ list1 ~ ',' ~ list_2 }}"
{ "pile_set_name": "StackExchange" }
Q: Why is $e$ a good base to use whenever you have a moving exponent While trying to evaluate a limit involving $x^x$ our professor told us that whenever dealing with moving exponents the best thing to do is to use "base $e$", why is that? A: Using $e$ simplifies lot of calculation, because number $e$ itself is the result of simple analytic processes. We can use any other number like $2$ and write $x^x=2^{x\log_{2}x}$ but then the derivatives of $2^x$ and $\log_{2}x$ don't have as simple forms as those of $e^x, \log x$. The functions $e^x, \log x$ have been created to have simple derivatives.
{ "pile_set_name": "StackExchange" }
Q: Verifying email and hashed password always returns None when details are definitely in DB I have a simple program to check if an email and hashed password are in a Postgres database (It's meant to be a cgi app, but because it fails, I'm testing it as a script first): import cgi import cgitb import hashlib import psycopg2 from dbconfig import * cgitb.enable() print "Content-Type: text/plain\n\n"; def checkPass(): email = "person@gmail.com" password = "mypassword" password = hashlib.sha224(password.encode()).hexdigest() result = cursor.execute('SELECT * FROM logins WHERE email=%s AND passhash=%s', (email, password)) print result if __name__ == "__main__": conn_string = "host=%s dbname=%s user=%s password=%s" % (host, database, dbuser, dbpassword) conn = psycopg2.connect(conn_string) cursor = conn.cursor() checkPass() This program always returns None on the print. The email and hashed password are definitely in the database though. I put them there with this: email = "person@gmail.com" allpass = "mypassword" password = hashlib.sha224(allpass.encode()).hexdigest() cursor.execute('INSERT INTO logins (email, passhash) VALUES (%s, %s);', (email, password)) conn.commit() And checking the db shows there's that email and hashed password. So why doesn't the first program return something upon the SELECT statement? Are hashes not stored in the same way? Any help would be greatly appreciated. A: I worked out what was wrong. As it happens, cursor.execute() doesn't actually return anything. You have to use fetchone() for that. cursor.execute('SELECT * FROM logins WHERE email=%s AND passhash=%s;', (email, password)) result = cursor.fetchone() print result This prints a tuple of the correct results.
{ "pile_set_name": "StackExchange" }
Q: Does an RL agent still learn if its actions are "blocked"? Say we have a game that is a maze environment where there is a character to be controlled through the maze. When the agent (the character) approaches a wall, it may try to execute an action that would lead it into the wall, which is not permitted. Instead of executing this action, we place an if statement in the code that checks if the action is permitted, and if not, does not execute the action, and simply proceeds to the next state. Another similar example is if an RL agent is being trained in a stock trading environment, where say it tries to sell more stock than it actually owns, or buy less than the minimum amount. Similarly as before, we place an if statement that checks for these conditions and either allows the action (allows the trade) or moves on to the next state. Does the agent still learn, even if we "override" it and block certain actions? How else would we go about restricting the agent to certain actions in certain states e.g. if a wall is to the left of the agent in the game environment, how would we restrict the agent to only move forward, backward or right, but not left? A: By overriding the Agent's action, Agent can theoretically take this action over and over and do nothing else, there is nothing to stop the agent from doing this, or teach the agent that this is not the intended action here. What I usually do in these situations is, I punish the agent if the action is not desirable. So if agent take the action to go to the left, but there is a wall on the left side, I would not change the state of the environment (So the agent won't move), but I would also send a minus value (punishment) as a reward. This way after some training, the agent would learn that this action is not desirable. The same can be applied to you Stock example. So if the agent tries to sell more stock that it actually has, you just don't sell the stock but also punish it with a big minus reward. This way it makes it easier for the agent to actually understand the environment. Hope this helps.
{ "pile_set_name": "StackExchange" }
Q: Laravel form submission sending to the wrong route? I have a very simple form: {!! Form::open(['route' => ['complete.order']]) !!} {!! Form::hidden('date', \Carbon\Carbon::now()->format('F j, Y ')) !!} {!! Form::hidden('web_token', $order->web_token) !!} {!! Form::submit('Place this order', ['class'=>'btn btn-primary']) !!} {!! Form::close() !!} When I visit the page, this renders as follows: <form method="POST" action="http://site.localhost/place-order" accept-charset="UTF-8"> <input name="_token" type="hidden" value="kc6d4XoZ78RvJNtQbN8lavpLP7e1lI7rTGBvbeIP"> <input name="date" type="hidden" value="December 21, 2018 "> <input name="id" type="hidden" value="15"> <input class="btn btn-primary" type="submit" value="Place this order"> </form> Here are the relevant routes: Route::get('/orders/form', 'OrdersController@viewform')->name('orderform'); Route::post('/orders/review', 'OrdersController@review')->name('orders.review'); Route::post('/place-order', 'OrdersController@store')->name('complete.order'); Route::resource('/orders', 'OrdersController', ['except'=>['edit', 'update', 'destroy', 'show', 'store']])->middleware('auth'); Route::get('/orders/{order}', 'OrdersController@show')->name('orders.show'); When I click on the submit button, I'm directed to site.localhost/orders/review, which according to the debug bar is being passed to as a GET request, not POST. I can't figure out why this is happening. The form should be going to site.localhost/place-order, which currently just outputs return('place') for testing. The code in OrdersController@show currently outputs return('show'). I've done the same across all of the OrdersController methods for testing. Adding php artisan route output +--------+-----------+-------------------------------+-----------------------+------------------------------------------------------------------------+------------------------------------------------------+ | Domain | Method | URI | Name | Action | Middleware | +--------+-----------+-------------------------------+-----------------------+------------------------------------------------------------------------+------------------------------------------------------+ | | GET|HEAD | / | | App\Http\Controllers\HomeController@index | web,auth | | | GET|HEAD | _debugbar/assets/javascript | debugbar.assets.js | Barryvdh\Debugbar\Controllers\AssetController@js | Barryvdh\Debugbar\Middleware\DebugbarEnabled,Closure | | | GET|HEAD | _debugbar/assets/stylesheets | debugbar.assets.css | Barryvdh\Debugbar\Controllers\AssetController@css | Barryvdh\Debugbar\Middleware\DebugbarEnabled,Closure | | | DELETE | _debugbar/cache/{key}/{tags?} | debugbar.cache.delete | Barryvdh\Debugbar\Controllers\CacheController@delete | Barryvdh\Debugbar\Middleware\DebugbarEnabled,Closure | | | GET|HEAD | _debugbar/clockwork/{id} | debugbar.clockwork | Barryvdh\Debugbar\Controllers\OpenHandlerController@clockwork | Barryvdh\Debugbar\Middleware\DebugbarEnabled,Closure | | | GET|HEAD | _debugbar/open | debugbar.openhandler | Barryvdh\Debugbar\Controllers\OpenHandlerController@handle | Barryvdh\Debugbar\Middleware\DebugbarEnabled,Closure | | | GET|HEAD | api/user | | Closure | api,auth:api | | | GET|HEAD | confirm-account/{token} | | App\Http\Controllers\UserController@create | web | | | GET|HEAD | home | home | App\Http\Controllers\HomeController@index | web,auth | | | GET|HEAD | login | login | App\Http\Controllers\Auth\LoginController@showLoginForm | web,guest | | | POST | login | | App\Http\Controllers\Auth\LoginController@login | web,guest | | | POST | logout | logout | App\Http\Controllers\Auth\LoginController@logout | web | | | GET|HEAD | my-account | my-account.index | App\Http\Controllers\UserController@index | web,auth | | | POST | my-account | my-account.store | App\Http\Controllers\UserController@store | web,auth | | | GET|HEAD | my-account/create | my-account.create | App\Http\Controllers\UserController@create | web,auth | | | PUT|PATCH | my-account/{my_account} | my-account.update | App\Http\Controllers\UserController@update | web,auth | | | DELETE | my-account/{my_account} | my-account.destroy | App\Http\Controllers\UserController@destroy | web,auth | | | GET|HEAD | my-account/{my_account} | my-account.show | App\Http\Controllers\UserController@show | web,auth | | | GET|HEAD | my-account/{my_account}/edit | my-account.edit | App\Http\Controllers\UserController@edit | web,auth | | | POST | orders | orders.store | App\Http\Controllers\OrdersController@store | web,auth | | | GET|HEAD | orders | orders.index | App\Http\Controllers\OrdersController@index | web,auth | | | GET|HEAD | orders/create | orders.create | App\Http\Controllers\OrdersController@create | web,auth | | | GET|HEAD | orders/form | orderform | App\Http\Controllers\OrdersController@viewform | web | | | POST | orders/review | orders.review | App\Http\Controllers\OrdersController@review | web | | | GET|HEAD | orders/{order} | orders.show | App\Http\Controllers\OrdersController@show | web | | | POST | password/email | password.email | App\Http\Controllers\Auth\ForgotPasswordController@sendResetLinkEmail | web,guest | | | POST | password/reset | | App\Http\Controllers\Auth\ResetPasswordController@reset | web,guest | | | GET|HEAD | password/reset | password.request | App\Http\Controllers\Auth\ForgotPasswordController@showLinkRequestForm | web,guest | | | GET|HEAD | password/reset/{token} | password.reset | App\Http\Controllers\Auth\ResetPasswordController@showResetForm | web,guest | | | POST | place-order | complete.order | App\Http\Controllers\OrdersController@store | web | | | POST | register | | App\Http\Controllers\Auth\RegisterController@register | web,guest | | | GET|HEAD | register | register | App\Http\Controllers\Auth\RegisterController@showRegistrationForm | web,guest | | | POST | user/store | user.store | App\Http\Controllers\UserController@store | web | +--------+-----------+-------------------------------+-----------------------+------------------------------------------------------------------------+------------------------------------------------------+ A: Okay, I'm a complete and utter idiot. The problem was that I was using a custom request for validation, which this route didn't meet. So it was actually returning the page back with errors, but since I didn't realize this it wasn't showing any errors.
{ "pile_set_name": "StackExchange" }
Q: How can I see raw bytes stored in a MySQL column? I have a MySQL table properly set to the UTF-8 character set. I suspect some data inserted into one of my columns has been double encoded. I am expecting to see a non-breaking space character (UTF-8 0xC2A0), but what I get when selecting this column out of this table is four octets (0xC3A2 0xC2A0). That's what I would expect to see if at some point somebody had treated an UTF-8 0xC2A0 as ISO-8859-1 then attempted to encode again to UTF-8 before inserting into MySQL. My test above where I am seeing the four octets involves selecting this column out of MySQL with Perl's DBD::mysql. I'd like to take Perl and DBD::mysql out of the equation to verify that those four octets are actually what MySQL has stored. Is there a way to do this directly with a SQL query? A: mysql> SELECT HEX(name) FROM mytable; +-----------+ | hex(name) | +-----------+ | 4142C2A0 | +-----------+ A: You could try using the HEX() function [http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_hex]. From the documentation, SELECT HEX('abc'); returns 616263. A: Why not try the BINARY operator? "The BINARY operator casts the string following it to a binary string. This is an easy way to force a column comparison to be done byte by byte rather than character by character." http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: how to add sequence to primary key in plSQL I'm using pl sql developer 12.what i want is to add the make the primary key sequential using oracle 12' windows and forms , not by scripting. I can't find out how?. aslo, how can i make one to one relation between 2 tables (user,role), in user table i added role_id as foreign key; but the relation seem one to many!!! A: what I have done lastly is that i downloaded sql developer 64 w, and from it; I connected with the database then I made the column sequential
{ "pile_set_name": "StackExchange" }
Q: Crawling sites with certain domain suffix I am interested in finding as much domain names as possible that have a given domain suffix that I am interested in, for instance: ".com", ".net", ".org", etc. I tried to crawl Google, but it obviuosly isn't legal and is hard to do. Does there exist a large list with domain names? If not, how can I make a crawler that finds as much as possible domain names that end with a given domain suffix? A: CommonCrawl have recently announced the publication of [a ranked list of hosts][2] (385M in total), which you could filter by domain suffix.
{ "pile_set_name": "StackExchange" }
Q: Padrino app with REST API Within a Padrino application I have a posts controller with the conventional routes: Blog::App.controllers :posts do get :index do ... end get :show, :with => :id do ... end end This gives me therefore the normal URL access within the posts namespace http://blog.dev/posts http://blog.dev/posts/show/1 Now I want to provide access through a REST API from a different route outside the namespace, like for example: http://blog.dev/api/v1/post/all http://blog.dev/api/v1/post/1 How can I define the API for my posts controller with routes outside its normal namespace? I must admit that I am not sure if my approach is the common one. I could define a new API V1 controller but in that case, I will have to duplicate information about posts in two different places. In case this should be done with an API controller, I wonder which gems and/or conventions are commonly use for this task. Ideally I would like something that coordinates different API versions with the current model object. A: Blog::App.controllers :posts, map: '/api/v1/posts' do get :index do ... end end And then, if you want add new versions of that controller Blog::App.controllers :v2_posts, map: '/api/v2/posts' do get :index do ... end end (Yeah, it seems you can't have several files with the same controller with different map values.) So, this won't work (sorry if that works, that doesn't when I tried) correctly and will cause issues : Blog::App.controllers :posts, map: '/api/v1/posts' do get :index do ... end end Blog::App.controllers :posts, map: '/api/v2/posts' do get :index do ... end end
{ "pile_set_name": "StackExchange" }
Q: Script only partially runs on theme activation, but runs fully on deactivation? The code below is near the top of my functions.php and is set to run only when my theme is activated: if ( is_admin() && isset($_GET['activated'] ) && $pagenow == 'themes.php' ) { However, even though its creating the category "my-utilities", it is apparently not able to set the parent of the category1 and category2 items to the newly created category. Perhaps its too soon to call get_cat_id on the newly created category? I believe it has something to do with that, since the category's reparent on the 2nd time the theme is activated. This, I presume, is since the category that will be used as parent has been created previously, the routine has no problem finding its ID and using it as the parent for category1 and category2. What am I missing? // with activate make sure theme's utility categories are present and parented correctly if ( is_admin() && isset($_GET['activated'] ) && $pagenow == 'themes.php' ) { if (file_exists(ABSPATH.'/wp-admin/includes/taxonomy.php')) { require_once(ABSPATH.'/wp-admin/includes/taxonomy.php'); if(!get_cat_ID('my-utilities')){wp_create_category('my-utilities');} //find out the ID of the newly created category, "my-utilities" $my_default_cat = my_cat(); if(!get_cat_ID('category1')){wp_create_category('category1',$my_default_cat);} if(!get_cat_ID('category2')){wp_create_category('category2',$my_default_cat);} //if the categories already existed, reparent them $myCategory1['cat_ID'] = get_cat_id('category1'); $myCategory1['category_parent'] = $my_default_cat; wp_update_category($myCategory1); $myCategory2['cat_ID'] = get_cat_id('category2'); $myCategory2['category_parent'] = $my_default_cat; wp_update_category($myCategory2); } } //utility category function my_cat() { if(get_cat_ID('my-utilities')) { return get_cat_ID('my-utilities'); } else { if(term_exists(1)) return "1"; else return get_option('default_category'); } } A: You're looking for this: register_activation_hook( __FILE__, 'your_plugin_activate_function_name' ); Edit: for a theme, you can use something like this instead: $theme_version = get_option('my_theme_version'); switch ((string) $theme_version) { // an early alpha... run upgrade code case '0.1': // another version... run upgrade code case '0.5': // add other cases as needed... without any break statement. // if we're here and in the admin area (to avoid race conditions), // actually save whichever changes we did if (is_admin()) { update_option('my_theme_version', '1.0'); // do other stuff } // we're at the latest version: bail here. case '1.0': break; default: // install code goes here }
{ "pile_set_name": "StackExchange" }
Q: UITextView shouldChangeCharactersInRange in Swift Trying to disable/enable the next button (which begins disabled on the storyboard) based on how many characters are in the textView field. It isn't working, which makes me think that only the textField has this feature and not the textView (they were really lazy with developing the textView field). I have an outlet connected for the textView and next button: @IBOutlet weak var textView: UITextView! @IBOutlet weak var nextButton: UIBarButtonItem! func textView(textView: UITextView, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let oldText: NSString = textView.text let newText: NSString = oldText.stringByReplacingCharactersInRange(range, withString: string) if newText.length > 0 { nextButton.enabled = true } else { nextButton.enabled = false } return true } How do I get this to work, because it just completely ignores it even if it compiles without errors. A: Requires UITextViewDelegate reference in class line: class MyViewController: UIViewController, UITextViewDelegate { } AND it also requires a referencing outlet from the view controller to the textView delegate. Select the view controller, click on outlets, drag from referencing outlet to the textView, click delegate.
{ "pile_set_name": "StackExchange" }
Q: Best practice for single-valued result in SSRS 2012 I'm new to Reporting Services and using SQL Server Data Tools (Visual Studio 2012). I want to add an item that will display a single value - in this case, the result of a stored procedure call. The value would probably be displayed in the report header. I've looked at the Tablix data parts that can be added to the report: table, list, and matrix. Not sure which of them, if any, would be appropriate. I could add a parameter item, but it seems that these function as user input choices. I also looked at a read-only text box, but don't see how to populate it with a query result. What is the accepted method of adding a single-value result to a report? A: If this is to be displayed in the page header, your only option is a textbox; you can't add tablix type parts to page headers/footers. The textbox expression would be something like: =First(Fields!MyValue.Value, "DataSet1") By using an aggregate expression like this you can make sure only one value is returned (even though you might always have only one) and you can also specify the aggregate's Scope; in this case the DataSet you want to query. If this was going in the report body I would still recommend the same approach, though I wouldn't go so far as to call it best practise, any would work so it's really personal taste. However, if you had multiple fields returned by the SP but still only one row, in that case I would recommend a table style tablix with one header-level row; easiest to maintain and layout.
{ "pile_set_name": "StackExchange" }
Q: JAWS / Web-Aim Is there any way to specify text as "a time" for screen readers? If JAWS comes across a time in my page like so: <div> <span>20:15</span> <!-- either of these times --> <span>04:15</span> <!-- either of these times --> </div> Then it reads them as "Twenty colon fifteen" which doesn't really sound like a time. Is there any way to specify that this is a time? Maybe put text that is read but not seen by an average user as "Twenty colon fifteen o'clock" or something might be a viable answer. A: Is there any way to specify that this is a time? HTML5 provides the time element and its datetime attribute. I can’t test if JAWS recognizes it, but it would be shame if it doesn’t (and they should certainly fix this). For the time "20:15", the markup could be: <time>20:15</time> <!-- because "20:15" is a valid time string --> <time datetime="20:15">20:15</time> <!-- the datetime attribute is not needed here --> <time datetime="20:15">…</time> <!-- could have any content, as long as the datetime attribute contains a valid time string -->
{ "pile_set_name": "StackExchange" }
Q: How to create a list from another list using specific criteria in Python? How can I create a list from another list using python? If I have a list: input = ['a/b', 'g', 'c/d', 'h', 'e/f'] How can I create the list of only those letters that follow slash "/" i.e. desired_output = ['b','d','f'] A code would be very helpful. A: You probably have this input.You can get by simple list comprehension. input = ["a/b", "g", "c/d", "h", "e/f"] print [i.split("/")[1] for i in input if i.find("/")==1 ] or print [i.split("/")[1] for i in input if "/" in i ] Output: ['b', 'd', 'f']
{ "pile_set_name": "StackExchange" }
Q: how to pass id across tabs in mvc razor view I have an mvc view with multiple bootstrap tabs. Once i clicked on save in the first tab an entry will be generated in the database and an id (identity key in the db) will be generated. When i click on the next tab (i use the jQuery click event) i want to pass the id generated from the first tab. @model MyProject.ViewModels.MydatabaseMyVM <div class="container"> <div class="row"> <h2> Create Staff</h2> </div> @using (Html.BeginForm()) { <ul id="datatabs" class="nav nav-tabs nav-justified"> <li class="active"><a data-toggle="tab" href="#details" id="TabDetailsLink">Personal Details</a></li> <li><a data-toggle="tab" href="#Tab1" id="TabTab1Link">Tab1</a></li> <li><a data-toggle="tab" href="#Tab2" id="TabTab2Link">Tab2</a></li> <li><a data-toggle="tab" href="#Tab3" id="TabTab3Link">Tab3</a></li> </ul> var data = $form.serialize(); $.post(url, data).done(function () {}. In my first tab i have fields from the student model, there is an id which will get generate from the database. On save of that i want to retain that id and when i click on another tab the id should pass to the action through ajax call. I am using mvc 4 razor view and Bootstrap tab. Can someone please guide me on how to pass the id generated at database from one tab to another. EF is used for accessing database A: If I understand correctly, on first tab, when you click Save, you post the form using ajax to StaffCreate(), which in terms return a view (not so sure why you are returning a View, but I will assume it is used else where). Is it not possible when you post to StaffCreate(), you save the staffId in a session. Then when you click second tab, in your jquery click event, first do a get request to a Action which just return staff Id as Json Result, once you got the id, do what ever you want with it. So a pseudo code something like: // your current action [HttpPost] public ActionResult StaffCreate(MydatabaseMyVMstaffvm) { // previous omitted for simplicity Staff objStaff = MyService.StaffCreate(staffvm.Staff); Session["StaffId"] = objStaff.StaffID; // reset omitted for simplicity } Action for getting the StaffId public ActionResult GetCreatedStaffId() { return Json(Session["StaffId"], JsonRequestBehavior.AllowGet) } // your tab click event $("").click(function{ $.getJSON( "@Url.Action("GetCreatedStaffId")", function( data ) { // data is your StaffId } }) Method 2 Psuedo code Store StaffId in hidden input in the view which you return in StaffCreate(), do something like <input type="hidden" id="hidStaffId" value="@Model.Staff.StaffID" /> your tab click event // your tab click event $("").click(function{ var staffId = $("#hidStaffId").val(); })
{ "pile_set_name": "StackExchange" }
Q: Aligning labels at the side of tikz diagram I'm using the tikz package to create diagrams showing the formation process of simple fractals, the first one being is the Cantor set. I'm showing a couple of iterations each one below the previous with its corresponding label at the side and then a larger space before the final fractal set, along with some vertical dots between the label. This is my current code \documentclass{article} \usepackage[utf8]{inputenc} \usepackage{tikz} \begin{document} \usetikzlibrary{decorations.fractals} \begin{tikzpicture}[xscale = 3.0, yscale=1, decoration=Cantor set,very thick] \draw decorate{ (0,0) -- (3,0) }; \node at (3,0) [right] {$E_0$}; \node at (3,-1) [right] {$E_1$}; \node at (3,-2) [right] {$E_2$}; \node at (3,-3) [right] {$\vdots$}; \node at (3,-4) [right] {$F$}; \draw decorate{ decorate{ (0,-1) -- (3,-1) }}; \draw decorate{ decorate{ decorate{ (0,-2) -- (3,-2) }}}; \draw decorate{ decorate{ decorate{ decorate{ decorate{ decorate{ decorate{(0,-4) -- (3,-4) }}}}}}}; \end{tikzpicture} \end{document} My issue is that I'm unsure of how to make it so that the labels are aligned. An ideal answer would be one that would require minimal changes when applied fractal figures where the vertical spacing will be different. Thanks in advance! A: since question is not clear (to me), let helps us with following picture: is this, what you looking for? \documentclass[tikz, margin=3mm]{standalone} \usepgflibrary{decorations.fractals} \begin{document} \begin{tikzpicture}[xscale = 3.0, yscale=1, decoration=Cantor set,very thick] \draw decorate{(0,0) -- (3,0)} node[right] {$E_0$}; \draw decorate{ decorate{ (0,-1) -- (3,-1) }} node [right] {$E_1$}; \draw decorate{ decorate{ decorate{ (0,-2) -- (3,-2) }}} node[right] (e2) {$E_2$}; \draw decorate{ decorate{ decorate{ decorate{ decorate{ decorate{ decorate{(0,-4) -- (3,-4) }}}}}}} node [right] (f) {$F$}; \node at ($(e2)!0.5!(f)$) {$\vdots$}; \end{tikzpicture} \end{document}
{ "pile_set_name": "StackExchange" }
Q: Cin loop never terminating I'm having trouble getting my cin loop to terminate in my program. My program uses Linux redirection to read in input from the file hw07data, the data file look like this: 100 20 50 100 40 -1 A34F 90 15 50 99 32 -1 N12O 80 15 34 90 22 -1 The first portion is the total points for the class, the next lines are the students ID number followed by their scores, all terminated by -1. My issue: my while loop never terminates when i run the command ./a.out < hw07data, could anyone look over my code and give me some hints? I dont want the answer, as this is homework, i just need some guidance. Thanks!! #include <iostream> #include <iomanip> using namespace std; const int SENTINEL = -1; //signal to end part of file const int LTAB = 8; //left tab const int RTAB = 13; //right tab int main() { cout << "Grant Mercer Assignment 7 Section 1002\n\n"; cout << setprecision(2) << fixed << showpoint; cout << left << setw(LTAB) << "ID CODE" << right << setw(RTAB) << "POINTS" << setw(RTAB) << "PCT" << setw(RTAB) << "GRADE" << endl; double Percentage, //holds students percentage AvgPercentage; int Earnedpoints, //earned points for specific student Totalpoints, //total points possible for all students AvgPoints, //average points for all students NumClass; //counts the number of students Totalpoints = Earnedpoints = //set all vals equal to zero AvgPoints = AvgPercentage = Percentage = NumClass = 0; //first and last char for studentID char Fchar,Lchar, Num1, Num2, Grade; int TmpVal = 0; //temporary value cin >> TmpVal; while(TmpVal != -1) //reading in TOTAL POINTS { Totalpoints += TmpVal; //add scores onto each other cin >> TmpVal; //read in next value } while(cin) //WHILE LOOP ISSUE HERE! { //read in student initials cin >> Fchar >> Num1 >> Num2 >> Lchar >> TmpVal; while(TmpVal != -1) { Earnedpoints += TmpVal; //read in points earned cin >> TmpVal; } //calculate percentage Percentage = ((double)Earnedpoints / Totalpoints) * 100; AvgPercentage += Percentage; NumClass++; if(Percentage >= 90) //determine grade for student Grade = 'A'; else if(Percentage >= 80 && Percentage < 90) Grade = 'B'; else if(Percentage >= 70 && Percentage < 80) Grade = 'C'; else if(Percentage >= 60 && Percentage < 70) Grade = 'D'; else if(Percentage < 60) Grade = 'F'; //display information on student cout << left << Fchar << Num1 << Num2 << setw(LTAB) << Lchar << right << setw(RTAB-3) << Earnedpoints << setw(RTAB) << Percentage << setw(RTAB) << Grade << endl; TmpVal = Earnedpoints = 0; } AvgPercentage /= NumClass; cout << endl << left << setw(LTAB+20) << "Class size: " << right << setw(RTAB) << NumClass << endl; cout << left << setw(LTAB+20) << "Total points possible: " << right << setw(RTAB) << Totalpoints << endl; cout << left << setw(LTAB+20) << "Average point total: " << right << setw(RTAB) << AvgPoints << endl; cout << left << setw(LTAB+20) << "Average percentage: " << right << setw(RTAB) << AvgPercentage << endl; } The output continues to ask for new input. A: You may find answer there How to read until EOF from cin in C++ So you can read cin line by line using getline and parse the resulting lines, like that: #include <iostream> #include <sstream> #include <string> int main() { int a, b; std::string line; while (std::getline(std::cin, line)) { std::stringstream stream(line); stream >> a >> b; std::cout << "a: " << a << " - b: " << b << std::endl; } return 0; } EDIT: Do not forget to check parsing results and stream state for any failure!
{ "pile_set_name": "StackExchange" }
Q: Melhor centralizar por margin:auto ou text-align:center? Buscando boas práticas em HTML, qual a melhor forma de centralizar? Vejo que consigo centralizar o menu de uma página por ambas as opções, porém fico na duvida de qual a melhor forma e também de qual é a forma correta ao invés de apenas usar uma que funcione sendo errada em alguns casos. Vejamos o seguinte código: * { margin: 0; padding: 0; } #container { background-color: lightblue; height: 200px; } .menu { list-style: none; margin: auto; width: 200px; } .menu-item { display: inline-block; } a { padding: 10px; background-color: green; } <div id="container"> <ul class="menu"> <li class="menu-item"><a href="">Home</a></li> <li class="menu-item"><a href="">Work</a></li> <li class="menu-item"><a href="">Contact</a></li> </ul> </div> Só consigo centralizar o menu por margin: auto; quando defino uma largura da classe menu e isso em alguns casos pode me fazer ter problemas quando os itens excedem esse tamanho, basta mudar o width: 200px; para width: 100px; que os itens ficam sobrepondo outros. Já quando defino a classe menu sem width posso centralizar o menu definindo um text-align: center; no seletor da tag superior, que no caso é o id #container. Fazendo isso eu consigo resolver o problema da quantidade de itens da lista que pode mudar e até ficar com tamanhos diferentes dependendo das modificações que precise fazer, mas ainda assim fico me perguntando se essa é a forma correta de fazer o alinhamento no centro. * { margin: 0; padding: 0; } #container { background-color: lightblue; height: 200px; text-align: center; } /* adicionado */ .menu { list-style: none;} /* removido width: 200px e margin: auto */ .menu-item { display: inline-block; } a { padding: 10px; background-color: green; } <div id="container"> <ul class="menu"> <li class="menu-item"><a href="">Home</a></li> <li class="menu-item"><a href="">Work</a></li> <li class="menu-item"><a href="">Contact</a></li> </ul> </div> A: De acordo com a W3C The CSS margin properties are used to generate space around elements. Segue o link Ou seja, a função da propriedade "margin" é definir espaço em volta dos elementos. Já a propriedade "text-align": The text-align property specifies the horizontal alignment of text in an element. Segue o link Resumindo, serve para alinhar texto horizontalmente. Boas praticas é utilizar um recurso de acordo com sua função. Se teu objetivo é centralizar texto. Deve utilizar "text-algin". Caso contrario, utilize "margin".
{ "pile_set_name": "StackExchange" }
Q: Sorting and keeping the main format of list numbers I have a list with these elements: list={1/2 (1 + Sqrt[5]), 1, 1, 1/2 (1 - Sqrt[5]), 0}; I want to sort them with Sort[list]; I see the bellow result: Which is incorrect, because N[1/2 (1 - Sqrt[5])]= -0.6, However I can write Sort[N[list]] but I need to have the exact numbers, not their approximate values (I mean that I need 1/2 (1 - Sqrt[5]) instead of -0.6). A: Look at the Possible Issues section of the documentation for Sort: "Numeric expressions are sorted by structure as well as numerical value" list = {1/2 (1 + Sqrt[5]), 1, 1, 1/2 (1 - Sqrt[5]), 0}; The approach recommended there to Sort by numerical value only is sorted = Sort[list, Less] (* {(1/2)*(1 - Sqrt[5]), 0, 1, 1, (1/2)*(1 + Sqrt[5])} *) Verifying numeric order % // N (* {-0.618034, 0., 1., 1., 1.61803} *) Or equivalently, sorted === Sort[list, #1 < #2 &] (* True *) Or use SortBy sorted === SortBy[list, N] (* True *) A: Not a bug. The docs: "Sort usually orders expressions by putting shorter ones first, and then comparing parts in a depth‐first manner." You want SortBy[list,N], I think. For more complex cases, use Ordering[] to get a list of indexes and use that to reorder the original list: Ordering@N@list list[[%]] Perhaps you should consider the option of handing Sort[] your own ordering predicate. Just use any pure function whatsoever which works on #1 and #2 and returns True if #1 comes before #2 in your desired sort order, or False otherwise: peopleAndAges={{"Felix",50},{"Max",19},{"Sophie",22}}; CompareByName[{n1_String,_},{n2_String}]:=(ToLowerCase@n1 <= ToLowerCase@n2) CompareByAge[{_,a1_},{_,a2_}]:=(a1 >= a2) Sort[peopleAndAges,CompareByAge]
{ "pile_set_name": "StackExchange" }
Q: What is the difference between off vs. from? What is the difference between off vs. from? For example, I fall from the car or I fall off the car? A: "I fall from the car" means there was no specific relation between you and the car before you fell. In this usage it is more likely to refer to you being in the car. You could equally have been on top of it, or hanging from it. "I fall off the car" means you were on the car before you fell. It is more specific in its usage as it indicates your relation to the car before falling.
{ "pile_set_name": "StackExchange" }
Q: Solve $f(x) = 6x^3 + 27x^2 + 17x + 20 \equiv 0 \pmod{30}$ Problem Solve $f(x) = 6x^3 + 27x^2 + 17x + 20 \equiv 0 \pmod{30}$ My attempt was: Since $30 = 2.3.5$, we then have: $$ \begin{cases} f(x) \equiv 0 \pmod{2}\\ f(x) \equiv 0 \pmod{3}\\ f(x) \equiv 0 \pmod{5}\\ \end{cases} $$ By inspection, we see that: $$ \begin{cases} x \equiv 0 \pmod{2}\\ x \equiv 1 \pmod{2}\\ x \equiv 2 \pmod{3}\\ x \equiv 0 \pmod{5}\\ x \equiv 1 \pmod{5}\\ \end{cases} $$ Hence, there will be four cases: Case 1 $$ \begin{cases} x \equiv 0 \pmod{2}\\ x \equiv 2 \pmod{3}\\ x \equiv 1 \pmod{5}\\ \end{cases} $$ Case 2 $$ \begin{cases} x \equiv 0 \pmod{2}\\ x \equiv 2 \pmod{3}\\ x \equiv 0 \pmod{5}\\ \end{cases} $$ Case 3 $$ \begin{cases} x \equiv 1 \pmod{2}\\ x \equiv 2 \pmod{3}\\ x \equiv 1 \pmod{5}\\ \end{cases} $$ Case 4 $$ \begin{cases} x \equiv 1 \pmod{2}\\ x \equiv 2 \pmod{3}\\ x \equiv 0 \pmod{5}\\ \end{cases} $$ Apply Chinese Remainder Theorem for the four system of equation, where $M = 30$: $$ \begin{cases} M_1 = \frac{30}{2} = 15\\ M_2 = \frac{30}{3} = 10\\ M_3 = \frac{30}{5} = 6\\ \end{cases} $$ And, $$ \begin{cases} 15y_1 \equiv 1 \pmod{2} \implies y_1 = 1\\ 10y_2 \equiv 1 \pmod{3} \implies y_2 = 1\\ 6y_3 \equiv 1 \pmod{5} \implies y_3 = 1\\ \end{cases} $$ Therefore, the four solutions are: $$ \begin{cases} x_1 = 1.15.0 + 1.10.2 + 1.6.1 = 26\\ x_2 = 1.15.0 + 1.10.2 + 1.6.0 = 20\\ x_3 = 1.15.1 + 1.10.2 + 1.6.1 = 41\\ x_4 = 1.15.1 + 1.10.2 + 1.6.0 = 35\\ \end{cases} $$ Edit Add missing cases suggested by yunone Case 5 $$ \begin{cases} x \equiv 0 \pmod{2}\\ x \equiv 2 \pmod{3}\\ x \equiv 2 \pmod{5}\\ \end{cases} $$ Case 6 $$ \begin{cases} x \equiv 1 \pmod{2}\\ x \equiv 2 \pmod{3}\\ x \equiv 2 \pmod{5}\\ \end{cases} $$ And the last two solutions are: $$ \begin{cases} x_5 = 1.15.0 + 1.10.2 + 1.6.2 = 32 \equiv 2 \pmod{30}\\ x_6 = 1.15.1 + 1.10.2 + 1.6.2 = 47 \equiv 17 \pmod{30}\\ \end{cases} $$ Am I in the right track? Any idea? Thanks, A: So far this looks like you're on the right track. You may want to reduce the solutions $41$ and $35$ modulo $30$ to $11$ and $5$, respectively. Also, note that $x\equiv 2$ is a solution to $f(x)\equiv 0 \pmod{5}$, so you should address those two extra cases to find a total of $6$ solutions modulo $30$. As a side note, you can use the $\LaTeX$ code \cdot to produce the multiplication symbol. For example, $30=2\cdot 3\cdot 5$ produces $30=2\cdot 3\cdot 5$.
{ "pile_set_name": "StackExchange" }
Q: Adding a button for google signin using f#/fable/asp.net/react I'm working with the SAFE stack (https://safe-stack.github.io/) and through the example dojo. It's great so far. I'd like to extend the example to include a button to login/auth via Google. So I looked at an example on the Google website (https://developers.google.com/identity/sign-in/web/build-button). And then I had a look how to do authentication using ASP.NET (https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/google-logins?view=aspnetcore-2.1&tabs=aspnetcore2x) As a result I ended up confused as to how to integrate this into a SAFE project. Can someone tell me what they would do? SHould I be trying to use ASP.NET Identity or should I be using the JWT approach? I don't even know if they are the same since I'm very new to web frameworks..... The other question I have is how would one inject raw Javascript into the client side of a SAFE project. The google example above shows raw JS/CSS/HTML code? Should I be injecting that as is or should I look in React for some button that does this and map that idea back through Fable? A: Setting up OAuth The easiest way to use Google OAuth is to wait until the next release of Saturn, at which point Saturn will include the use_google_oauth feature that I just added. :-) See the source code if you're interested in how it works, though I'm afraid you can't implement this yourself with use_custom_oauth because you'll run into a type error (the underlying ASP.NET code has a GoogleOptions class, and use_custom_oauth wants an OAuthOptions class, and they aren't compatible). To use it, add the following to your application CE: use_google_oauth googleClientId googleClientSecret "/oauth_callback_google" [] The last parameter should be a sequence of string * string pairs that represent keys and values: you could use a list of tuples, or a Map passed through Map.toSeq, or whatever. The keys of that sequence are keys in the JSON structure that Google returns for the "get more details about this person" API call, and the values are the claim types that those keys should be mapped to in ASP.NET's claims system. The default mapping that use_google_oauth already does is: id → ClaimTypes.NameIdentifier displayName → ClaimTypes.Name emails[] (see note) → ClaimTypes.Email Those three are automatically mapped by ASP.NET. I added a fourth mapping: avatar.url → `"urn:google:avatar:url" There's no standard ClaimTypes name for this one, so I picked an arbitrary URN. Caution: this feature hasn't been released yet, and it's possible (though unlikely) that this string might change between now and when the feature is released in the next version of Saturn. With those four claim types mapped automatically, I found that I didn't need to specify any additional claims, so I left the final parameter to use_google_oauth as an empty list in my demo app. But if you want more (say you want to get the user's preferred language to use in your localization) then just add them to that list, e.g.: use_google_oauth googleClientId googleClientSecret "/oauth_callback_google" ["language", "urn:google:language"] And then once someone has logged in, look in the User.Claims seq for a claim of type "urn:google:language". Note re: the emails[] list in the JSON: I haven't tested this with a Google account that has multiple emails, so I don't know how ASP.NET picks an email to put in the ClaimTypes.Email claim. It might just pick the first email in the list, or it might pick the one with a type of account; I just don't know. Some experimentation might be needed. Also note that third-party OAuth, including GitHub and Google, has been split into a new Saturn.Extensions.Authorization package. It will be released on NuGet at the same time that Saturn's next version (probably 0.7.0) is released. Making the button Once you have the use_google_oauth call in your application, create something like the following: let googleUserIdForRmunn = "106310971773596475579" let matchUpUsers : HttpHandler = fun next ctx -> // A real implementation would match up user identities with something stored in a database, not hardcoded in Users.fs like this example let isRmunn = ctx.User.Claims |> Seq.exists (fun claim -> claim.Issuer = "Google" && claim.Type = ClaimTypes.NameIdentifier && claim.Value = googleUserIdForRmunn) if isRmunn then printfn "User rmunn is an admin of this demo app, adding admin role to user claims" ctx.User.AddIdentity(new ClaimsIdentity([Claim(ClaimTypes.Role, "Admin", ClaimValueTypes.String, "MyApplication")])) next ctx let loggedIn = pipeline { requires_authentication (Giraffe.Auth.challenge "Google") plug matchUpUsers } let isAdmin = pipeline { plug loggedIn requires_role "Admin" (RequestErrors.forbidden (text "Must be admin")) } And now in your scope (NOTE: "scope" will probably be renamed to "router" in Saturn 0.7.0), do something like this: let loggedInView = scope { pipe_through loggedIn get "/" (htmlView Index.layout) get "/index.html" (redirectTo false "/") get "/default.html" (redirectTo false "/") get "/admin" (isAdmin >=> htmlView AdminPage.layout) } And finally, let your main router have a URL that passes things to the loggedInView router: let browserRouter = scope { not_found_handler (htmlView NotFound.layout) //Use the default 404 webpage pipe_through browser //Use the default browser pipeline forward "" defaultView //Use the default view forward "/members-only" loggedInView } Then your login button can just go to the /members-only route and you'll be fine. Note that if you want multiple OAuth buttons (Google, GitHub, Facebook, etc) you'll probably need to tweak that a bit, but this answer is long enough already. When you get to the point of wanting multiple OAuth buttons, go ahead and ask another question.
{ "pile_set_name": "StackExchange" }