source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0032025365.txt" ]
Q: Does the Clojure compiler check if records and types implement protocols? Is the Clojure compiler meant to check if a record or type that says it instantiates a protocol actually implements the methods listed in it? I'm trying this out now and so far, it doesn't seem to. A: A record can implement a protocol without implementing any of its methods: (defprotocol Structure (weight [this]) (balanced? [this])) (defrecord Mobile [] Structure ) ... is accepted. If you try to use a non-existent method: (balanced? (Mobile.)) ;java.lang.AbstractMethodError: user.Mobile.balanced_QMARK_()Ljava/lang/Object; As usual, type errors are found at run time.
[ "stackoverflow", "0008387744.txt" ]
Q: Rails Admin - Become Another User I'm using Rails 3.0.10 and I'm currently using CanCan for determining the different abilities that users have within the application. I am using Devise for the user authentication itself. Is there a good way for an admin user to "become" another user temporarily using CanCan? This would be especially useful to become specific users who may be experiencing unique issues pertaining to their account. So in simple terms, I just want to be able to sign in as any given user to see what they see. Not sure if there is a CanCan or Devise feature out there. UPDATE I just came across this: How-To: Sign in as another user if you are an Admin. I haven't tested it yet, but it may be the answer I was looking for!! Feel free to provide some insight if this is the approach you took, or if you have another idea! A: I found what I was looking for, and there's a gem for it! switch_user It was really easy to use. I just have to add gem switch_user to my Gemfile. Then add <%= switch_user_select %> to my layout. Exactly what I wanted!
[ "stackoverflow", "0002760289.txt" ]
Q: performance monitoring tools for multi-tenant web application We have a need to monitor performance of our java web app. We are looking for some tolls which can help us with this task. The major difficulty is that we are SaaS provider with multi-tenant server architecture with hundreds of customers running on the same hardware. So far we tried commercial products like DynaTrace and Coradinat but unfortunately they don't get the job done so far. What we need is a simple report which would tell us if we had performance problems on each customer site in a specified period of time. Mostly it will be response time per customer but also we will need some more specifics based on the URLs. please let me know if someone had any experience with setting up such monitoring. Thanks! A: Take a look at stagemonitor. It is an open source java web application performance monitoring library capable of multi-tenancy. It captures response time metrics, JVM metrics, request details and more. The overhead is very low. It uses the great timeseries database graphite that automatically downsamples historical datapoints which leads to a low storage overhead. Here is a screenshot. You can find more on the project site. Note: I am the developer of stagemonitor
[ "math.stackexchange", "0000033706.txt" ]
Q: Is there a standard category-theoretic way to express a loop or quasigroup? The standard way to encode a group as a category is as a "category with one object and all arrows invertible". All of the arrows are group elements, and composition of arrows is the group operation. A loop obeys similar axioms to a group, but does not impose associativity. Inverses need not exist, but a "cancellation property" exists -- given $xy = z$, and any two of $x$, $y$, and $z$, the third is uniquely determined. Quasigroups need not even have a neutral element. Given the lack of associativity, arrows under composition do not work to encode loop elements. Is there a natural way to do this? A: As expressed by Qiaochi Yuan in this and this comment, the way that category theory applies to studying loops and quasigroups is in the form of a category whose objects are loops, resp. quasigroups. Only a few structures can actually be described as categories having certain special properties (among which sets, groups, partially ordered sets). For a structure to have any chance of being a "special type of category", it is of course necessary that the defining properties for a category are somehow satisfied by the structure in question. For loops and quasigroups, this is not obvious to say the least, due to the lack of associativity (which is all-important in category theory).
[ "stackoverflow", "0060653833.txt" ]
Q: write several txt to directory automatically We have this if else iteration with the goal to split a dataframe into several dataframes. The result of this iteration will vary, so we will not know how much dataframes we will get out of a dataframe. We want to save that several dataframe as text (.txt): txtDf = open('D:/My_directory/df0.txt', 'w') txtDf.write(df0) txtDf.close() txtDf = open('D:/My_directory/df1.txt', 'w') txtDf.write(df0) txtDf.close() txtDf = open('D:/My_directory/df2.txt', 'w') txtDf.write(df0) txtDf.close() And so on .... But, we want to save that several dataframes automatically, so that we don't need to write the code above for 100 times because of 100 splitted-dataframes. This is the example our dataframe df: column_df 237814 1249823 89176812 89634 976234 98634 and we would like to split the dataframe df to several df0, df1, df2 (notes: each column will be in their own dataframe, not in one dataframe): column_df0 column_df1 column_df2 237814 89176812 976234 1249823 89634 98634 We tried this code: import copy import numpy as np df= pd.DataFrame(df) len(df) if len(df) > 10: print('EXCEEEEEEEEEEEEEEEEEEEEDDD!!!') sys.exit() elif len(df) > 2: df_dict = {} x=0 y=2 for df_letter in ['A','B','C','D','E','F']: df_name = f'df_{df_letter}' df_dict[df_name] = copy.deepcopy(df_letter) df_dict[df_name] = pd.DataFrame(df[x:y]).to_string(header=False, index=False, index_names=False).split('\n ') df_dict[df_name] = [','.join(ele.split()) for ele in df_dict[df_name]] x += 2 y += 2 df_name else: df for df_ in df_dict: print(df_) print(f'length: {len(df_dict[df_])}') txtDf = open('D:/My_directory/{df_dict[df_]}.txt', 'w') txtDf.write(df) txtDf.close() The problem with this code is that we cannot write several .txt files automatically, everything else works just fine. Can anybody figure it out? A: If it is a list then you can iterate through it and save each element as string import os for key, value in df_dict.items(): with open(f'D:/My_directory/{key}.txt', "w") as file: file.write('\n'.join(str(v) for v in value))
[ "stackoverflow", "0018810671.txt" ]
Q: form to email PHP script I have this simple script I found online but it does not work. What am I missing? <?php if(!isset($_POST['submit'])) { //This page should not be accessed directly. Need to submit the form. echo "error; you need to submit the form!"; } $name = $_POST['name']; $visitor_email = $_POST['email']; $message = $_POST['message']; $email_from = $visitor_email; $email_subject = "New Message"; $email_body = "You have received a new message from $name.\n". "\n\n $message". $to = "myemail@domain.com"; $headers = "From: $email_from \r\n"; $headers .= "Reply-To: $visitor_email \r\n"; try{ mail($to,$email_subject,$email_body,$headers); //done. redirect to thank-you page. header('Location: thank-you.html'); } catch(Exception $e){ //problem, redirect to sorry page header('Location: sorry.html'); } ?> I am always redirected to the thank-you page but I do not get any emails. All HTML stuff are correct. A: Assuming you have a form similar to the following with named fields: (input fields must be named). <!DOCTYPE html> <html> <head> <title></title> </head> <body> <form method="post" action="handler.php"> Name: <input type="text" name="name" /> <br/> Your Email: <input type="text" name="email" /> <br/> Message: <br> <textarea id="body" name="message" cols="100" rows="20"></textarea><br/> <input type="submit" name="submit" value="Send Email" /> </body> </html> This line would cause you problems because of the dot at the end of $message. $email_body = "You have received a new message from $name.\n". "\n\n $message". The dot should be a semi-colon ; such as: $email_body = "You have received a new message from $name.\n". "\n\n $message"; In testing, the message I typed did not come through until changed to a semi-colon. This line echo "error; you need to submit the form!"; should be a die() directive in order to stop executing. Such as: die("Error. You need to submit the form."); or you could use exit; under your echo also. Such as: echo "error; you need to submit the form!"; exit; PHP (handler.php) Tested and working on my end using the form shown above. <?php if(!isset($_POST['submit'])) { //This page should not be accessed directly. Need to submit the form. // echo "Error. You need to submit the form."; // exit; die("Error. You need to submit the form."); } $name = $_POST['name']; $visitor_email = $_POST['email']; $message = $_POST['message']; $email_from = $visitor_email; $email_subject = "New Message"; $email_body = "You have received a new message from $name.\n". "\n\n $message"; $to = "myemail@domain.com"; $headers = "From: $email_from \r\n"; $headers .= "Reply-To: $visitor_email \r\n"; try{ mail($to,$email_subject,$email_body,$headers); //done. redirect to thank-you page. // header('Location: thank-you.html'); echo "Success"; // My echo test } catch(Exception $e){ //problem, redirect to sorry page // header('Location: sorry.html'); echo "Sorry"; // My echo test } ?>
[ "apple.stackexchange", "0000107447.txt" ]
Q: Roll back to Mountain Lion but don't lose saved documents I have a Time Machine backup of my system from last week right before I installed Mavericks. I've determined that Mavericks breaks too many programs that I need to use and doesn't add enough features (yet) for me to want to be using it, so I want to roll back to Mountain Lion. BUT… (there's always a but, right? I suppose if there weren't, I wouldn't be asking here) here's the catch: I haven't plugged in my Time Machine drive since upgrading. I have saved documents in the past week. If I were to just roll back to last week's backup, I'd lose all the work I've done since upgrading. Can I safely run a Time Machine backup under Mavericks, revert to last week's backup, and then restore individual files from the Mavericks backup? Do I need to be buying another external drive to first back up this week's system, then restore last week's system, then pull files? What needs to happen here to restore my system to ML without losing a week's work? A: Yes, you can safely backup with Time Machine in OS X Mavericks and restore your newer files later when you're back on OS X Mountain Lion. Complete a backup using Time Machine on OS X Mavericks to get your new/updated files into the backup Reboot the machine with the Time Machine disk connected At startup, hold Cmd+R to get into Recovery mode (or hold Option to select the volume to boot from and choose the Recovery HD from the Time Machine disk) Choose Restore From Time Machine Backup from the list of actions Select the Time Machine volume and then the backup dated before the upgrade that you wish to restore from (it will show you a list of all available backups) After booting into the OS X Mountain Lion system, turn off Time Machine in System Preferences > Time Machine (to avoid another backup starting soon, thus slowing down the system and adding to the cognitive load on you to choose the correct versions to restore) Browse the Time Machine disk from the Time Machine interface and pick the specific files from the latest backup to restore Turn on Time Machine again in System Preferences
[ "stackoverflow", "0049064895.txt" ]
Q: How to intercept field accesses (without getter/setter) using Bytebuddy I am trying to use bytebuddy to intercept getfield and putfield accesses. I have read the rather comprehensive documentation on the site, but from what I can understand, it covers adding getters and setters to fields, rather than intercepting field accesses. Here is basically what I am trying to do: ... obj.prop = value; x = obj.prop; ... That in both these cases, I am trying to have some method called (or some bytecode inserted) before/after the field access. I was thinking of using Advice to do it, but I am unable to find a way to have it for something other than methods. Edit: I am using a Java Agent to do it. I had an idea of adding a dup to duplicate the object reference followed by the call to a static method I defined to intercept the access (I only care about the object being referred to, not the field). A: There is a new component that is still under development but that is already exposed with a basic API. It is called MemberSubstitution and allows you to replace a method call or field access with another execution. This component does however rely on replacing the code that executes an instruction. Field access is non-virtual, therefore it is not possible to create any proxy class that would intercept a virtual access. Instead, you have to redefine any existing class that reads or writes the field, for example by using a Java agent. As for your more specific question: At the moment, there is only a 1-to-1 substitution possible. I have not yet had the time to include a mechanism for adjusting the stack and local variable sizes. Also, you would also have to dup objects lower down on the stack if the field is non-static. The problem is not trivial so to say but I hope to offer such functionality some day. At the moment you can however replace the field access with a static method call. Possibly, you can execute the original field operation from this method.
[ "stackoverflow", "0006925832.txt" ]
Q: Switch off GPS programmatically What i have: Currently my app is giving location through gps. what i want: Gps to turn off automatically after i exit from the application. Because it keeps on telling me the location time and again that looks odd and also gps consume a lot battery. A: Looking at above comment thread it seems its possible to turn OFF GPS programatically (But seeing only 12 Upvotes) But if you switch OFF GPS from your application programatically, what if other applications use GPS Service ? The solution would be like Open Settings of android and then tell user to turn OFF GPS when he exits from the application... For this you can do like : Intent i = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(i); OR You can try like locationManager.removeUpdates(myLocationListener); locationManager = null; This shutdown gps for this app, but its still available for use by other apps.
[ "wordpress.stackexchange", "0000002571.txt" ]
Q: Making a Contact Form 7 calendar entry "required" I'm using the Contact Form 7 Calendar "plugin plugin", but I can't figure out how to make the date field required. The syntax is [datetimepicker your-label], and in the parent plugin (Contact Form 7), you would just put an asterisk in, like [datetimepicker* your-label] but this doesn't work with the calendar widget... Of course, I could always style it in CSS to appear as if its required, but I kinda need the validation there. I've looked in the plugin's documentation, but this isn't covered, and the author is not responding on the WP Support Forums. Has anyone used the Calendar add-on and been able to make the date field required? Anything I can do to tweak the javascript or whatever is used for validation -- I'm assuming its javascript (I'm sure js is very easy but I've never managed to find the time to learn it)? Or the php (I'm much more comfortable in php), but without breaking on plugin updates... A: Apparently the answer is to read the installation instructions properly the first time round. The syntax within a contact 7 form is: [cf7cal inputname] or [cf7cal* inputname]
[ "stackoverflow", "0011767455.txt" ]
Q: BS doesn't "see" all tables? I'm using BeautifulSoup to parse through data on baseball-reference.com and it works find for every page, except for a few like this one Same pages (different data) work perfectly, ie this one. I'm trying to filter out tables with 'stats_table' as one of the classes. I use this code: bs = BeautifulSoup(stream, 'lxml', parse_only=SoupStrainer('table')) and then I do sth like: for table in bs.find_all('table'): print table.attrs ... bla bla... It is obvious out of table.attrs that this code doesn't see batting and pitching tables and that they are there... I repeat: the same code works fine for almost all other pages like this. Looking over str(bs) clearly shows that ANY ideas? A: As you posted in the comments there are errors on the page. You should use HTML Tidy to clean it up : http://pypi.python.org/pypi/pytidylib/0.2.1 You can check HTML Tidy at work: http://validator.w3.org/
[ "stackoverflow", "0012120898.txt" ]
Q: What is "model" in context of CodeIgniter application? Recently I have started working with Codeigniter framework in order to develop RESTFul web service for mobile application. As I was looking at various tutorials on web sites and on youtube, I found that the concept of a Model is being used differently in PHP application context. How differently? Well, as I always thought Model classes should look like, Cat.php <?php class Cat { // Class variables private $colour; public __construct() { $colour = 'Brown'; } // Getters and Setters public function getColour() { return $this->colour; } public function setColour($newColour) { $this->colour = $newColour; } } ?> but, while searching for good tutorials over the internet I found that people are just using functions that has access to the database for data and returning it to Controller. I haven't seen any one writing normal classes in Model (If you are Java person then, we call it POJO) Now, What I entailed after reading and watching these tutorials that, In context of PHP application frameworks, The Model classes are connectors to the database which returns the application related data upon query. In language of SQL people we call it, CRUD functions Create Read Update Delete So, correct me if I am wrong. In web application created by taking base of Codeigniter like framework, where the MVC pattern is used to design an application. The Model classes are the one which will have functions that connects application to the database and returns the data, as well as helps to perform all CRUD operations on application's database. A: Well, if you have used C# or Ruby, there you can find a good way to apply the MVC pattern. In PHP, in my opinion, people sometimes are confused about the terms. The way I use the MVC pattern in PHP is like the following: CONTROLLER class UserController { private $repo; public function __construct() { $this->repo = new UserRepository(); // The file which communicates with the db. } // GET // user/register public function register() { // Retrieve the temporary sessions here. (Look at create function to understand better) include $view_path; } // POST // user/create public function create() { $user = new User($_POST['user']); // Obviously, escape and validate $_POST; if ($user->validate()) $this->repo->save($user); // Insert into database // Then here I create a temporary session and store both the user and errors. // Then I redirect to register } } MODEL class User { public $id; public $email; public function __construct($user = false) { if (is_array($user)) foreach($user as $k => $v) $this->$$k = $v; } public function validate() { // Validate your variables here } }
[ "stackoverflow", "0022521483.txt" ]
Q: gwt generic page level click handler I have this situation, where I display a success/error message on a page and then I want it to disappear when the user does anything on the page (I assume that that triggers a click event, I can ignore events like going to new tab/windows etc.). I have other "uihandlers" and "clickhandlers" on the page. So if I click empty regions on the page only the hidemessage call fires, else if I click valid 'clickable' elements my hidemessage fires first followed by the relevant handler. Is there a way I can achieve this without adding hidemessage to all my clickhandlers on the page? Edit: The message widget is not a PopupPanel, so setAutohide(true) won't work. But it is exactly the behavior I'm looking for. The widget is a custom widget which extends Composite implements HasWidget, HasClickHandlers A: You can do this on your error message: myPopupPanel.setAutoHideEnabled(true); It does exactly whet you need. You may also consider setting auto-hide on history events (mostly back button): myPopupPanel.setAutoHideOnHistoryEventsEnabled(true); EDIT: If you are not using a PopupPanel, you can make your Widget implement EventPreview, and then: public boolean onEventPreview(Event event) { Element target = DOM.eventGetTarget(event); boolean widgetIsTarget = (target != null) && DOM.isOrHasChild(getElement(), target); setVisible(widgetIsTarget):
[ "stackoverflow", "0020574887.txt" ]
Q: I can't make these few simple line of code work correctly and have no idea why I tried to this simple exercise , i did get it to work but not correctly. It's supposed to give you a random number between 0 and 1000 as you click a button. When you click the button again , it creates another random number , if its bigger than the last one , it displays it. If it is not , it does nothing. And while it does this , it counts how many times it had run the function. The one i made did give me random numbers but sometimes , it displayed smaller numbers than the last one and sometimes it didn't. I can't figure out why. I suspect it might be because of the line of code where i tried to change what the button does. <!DOCTYPE html> <html> <head> <input id="btn" type="button" onclick="initiate(1)" value="Click me!"><br> <script> function geid(id) { return document.getElementById(id); } var count = 0; function initiate(n) { var x = n; n = Math.floor(Math.random() * 1000); document.getElementById("btn").onclick = function () { initiate(n); } if (n > x) { geid("fid").innerHTML = n; count += 1; geid("fid2").innerHTML = count + " times"; } else { count += 1; geid("fid2").innerHTML = count + " times"; } } </script> </head> <body> Number : <div id="fid">0</div> Tried <div id="fid2">0</div> </body> </html> A: The problem is that you're always changing the onclick function, regardless of whether the newly chosen n value is greater than the previous value (x) or not. Take this example: suppose that the statement Math.floor(Math.random()*1000); produces this sequence of values when you run it multiple times: 100, 500, 200, 300. With the first click, the function was called as initiate(1), the spot fid1 was set to hold 100, and the onclick handler was set to call initiate(100). With the second click, the function was called as initiate(100), the spot fid1 was set to hold 500, and the onclick handler was set to call initiate(500). So far so good. With the third click, the function was called as initiate(500), the spot fid1 was left unchanged at 500, and the onclick handler was set to call initiate(200). Um... With the fourth click, the function was called as initiate(200), the spot fid1 was set to hold 300, and the onclick handler was set to call initiate(300). So the issue is that if you want to change the handler to hold always the current value in fid1, then you shouldn't change the handler unless n > x.
[ "stackoverflow", "0049097397.txt" ]
Q: PHP converting an array of strings to a two-dimensional array with custom keys I'm new in PHP and have to convert data from a JS array, which I read from a text file, to a PHP array. So far, after file reading and some "cleaning" and sorting, I have the following array of strings: $workArray[0] = "\"20180125_0363\",\"363\",\"25.01.2018\",\"Some long text here\",false,\"\""; $workArray[1] = "\"20180125_0364\",\"364\",\"25.01.2018\",\"Some long text here\",true,\"Some short text here\""; $workArray[2] = "\"20180125_0365\",\"365\",\"25.01.2018\",\"Some long text here\",true,\"Some short text here\""; ... ... etc. I need some help with the following task: How to convert the $workArray to a two-dimensional $dataArray array, whose elements are arrays with custom keys, and values, extracted from above strings? $dataArray[0] = array( "uid" => "20180125_0363", "number" => "363", "date" => "25.01.2018", "title" => "Some long text here", "docFlag" => false, "docTitle" => "" ); $dataArray[1] = array( "uid" => "20180125_0364", "number" => "364", "date" => "25.01.2018", "title" => "Some long text here", "docFlag" => true, "docTitle" => "Some short text here" ); $dataArray[2] = array( "uid" => "20180125_0365", "number" => "365", "date" => "25.01.2018", "title" => "Some long text here", "docFlag" => true, "docTitle" => "Some short text here" ); ... ... etc. A: Store the keys in an array, then use str_getcsv() to explode each element into an array, and finally use array_combine() to pair the keys and the values: <?php $keys = [ "uid", "number", "date", "title", "docFlag", "docTitle", ]; $workArray[0] = "\"20180125_0364\",\"363\",\"25.01.2018\",\"Some long text here\",false,\"\""; $workArray[1] = "\"20180125_0363\",\"364\",\"25.01.2018\",\"Some long text here\",true,\"Some short text here\""; $workArray[2] = "\"20180125_0358\",\"365\",\"25.01.2018\",\"Some long text here\",true,\"Some short text here\""; foreach ($workArray as &$el) { $values = str_getcsv($el); $el = array_combine($keys, $values); } var_dump($workArray); Demo Note that each element is passed by reference so as to modify each element itself and not a copy. Or, a little more elegant, use array_walk() to apply a function to each element in the array. Again, the element is passed by reference, and use() is used to bring the $keys array into the scope of the anonymous function: array_walk($workArray, function(&$el) use($keys) { $values = str_getcsv($el); $el = array_combine($keys, $values); }); Result array (size=3) 0 => array (size=6) 'uid' => string '20180125_0364' (length=13) 'number' => string '363' (length=3) 'date' => string '25.01.2018' (length=10) 'title' => string 'Some long text here' (length=19) 'docFlag' => string 'false' (length=5) 'docTitle' => string '' (length=0) 1 => array (size=6) 'uid' => string '20180125_0363' (length=13) 'number' => string '364' (length=3) 'date' => string '25.01.2018' (length=10) 'title' => string 'Some long text here' (length=19) 'docFlag' => string 'true' (length=4) 'docTitle' => string 'Some short text here' (length=20) 2 => array (size=6) 'uid' => string '20180125_0358' (length=13) 'number' => string '365' (length=3) 'date' => string '25.01.2018' (length=10) 'title' => string 'Some long text here' (length=19) 'docFlag' => string 'true' (length=4) 'docTitle' => string 'Some short text here' (length=20)
[ "stackoverflow", "0032073725.txt" ]
Q: How to pass Javascript array value to PHP and then send MySQL query with this value? As I mentioned in title, how can I pass JS array value to PHP and then send it using mysqli? Here are functions that will help in getting values to be send later. function getPlayerName() { return player.Name; } function getPlayerClass() { return player.Class; } function getPlayerLevel() { return player.Level; } Most important thing for me is that how can I pass this arrays to PHP? @Edit I'm using store.js to save player arrays value (Local Storrage). And here is function that saves it when new player is created. function saveData(){ var playerName = document.getElementById('nickname'); var warriorClass = document.getElementById('warrior'); var mageClass = document.getElementById('mage'); var archerClass = document.getElementById('archer'); if(warriorClass.checked){ store.set('player', { Name: playerName.value, Class: 'Warrior', Level: playerLevel, XP: playerXP, HP: playerHP, MaxHP: playerMaxHP }); } else if(mageClass.checked){ store.set('player', { Name: playerName.value, Class: 'Mage', Level: playerLevel, XP: playerXP, HP: playerHP, MaxHP: playerMaxHP }); } else if(archerClass.checked){ store.set('player', { Name: playerName.value, Class: 'Archer', Level: playerLevel, XP: playerXP, HP: playerHP, MaxHP: playerMaxHP }); } } @Edit2 With Skamielina advice I did something like this: $.ajax({ method: "POST", url: "top15.php", data: { Name: player.Name, Class: player.Class, Level: player.Level } }) And top15.php has this: <?php echo 'Name: ' . $_POST['Name'] . '<br/>'; echo 'Level: ' . $_POST['Level'] . '<br/>'; echo 'Class: ' . $_POST['Class'] . '<br/>'; ?> Now, on webpage it's Name: Level: Class: But, FireBug console shows Name: Oen<br/>Level: 1<br/>Class: Mage<br/> Stupid me... Not Array, I mean Variables. God, sorry for this mistake :x A: Use jQuery and $.ajax function (see docs): $.ajax({ method: "POST", url: "some.php", data: { name: player.Name, class: player.Class, level: player.Level } }) Next you need have that php file to handle request from the browser, and eventually return results. A: Sorry for my mistake, I meant Variables not Arrays. My bad, solution is way easier than i thought. <?php echo '<script>'; echo "var player = store.get('player')"; echo '</script>'; echo "Name: <script> document.writeln(player.Name)</script><br/>"; echo "Level: <script> document.writeln(player.Level)</script><br/>"; echo "Class: <script> document.writeln(player.Class)</script><br/>"; ?>
[ "stackoverflow", "0003523054.txt" ]
Q: Python string.replace() not replacing characters Some background information: We have an ancient web-based document database system where I work, almost entirely consisting of MS Office documents with the "normal" extensions (.doc, .xls, .ppt). They are all named based on some sort of arbitrary ID number (i.e. 1245.doc). We're switching to SharePoint and I need to rename all of these files and sort them into folders. I have a CSV file with all sorts of information (like which ID number corresponds to which document's title), so I'm using it to rename these files. I've written a short Python script that renames the ID number title. However, some of the titles of the documents have slashes and other possibly bad characters to have in a title of a file, so I want to replace them with underscores: bad_characters = ["/", "\\", ":", "(", ")", "<", ">", "|", "?", "*"] for letter in bad_characters: filename = line[2].replace(letter, "_") foldername = line[5].replace(letter, "_") Example of line[2]: "Blah blah boring - meeting 2/19/2008.doc" Example of line[5]: "Business meetings 2/2008" When I add print letter inside of the for loop, it will print out the letter it's supposed to be replacing, but won't actually replace that character with an underscore like I want it to. Is there anything I'm doing wrong here? A: That's because filename and foldername get thrown away with each iteration of the loop. The .replace() method returns a string, but you're not saving the result anywhere. You should use: filename = line[2] foldername = line[5] for letter in bad_characters: filename = filename.replace(letter, "_") foldername = foldername.replace(letter, "_") But I would do it using regex. It's cleaner and (likely) faster: p = re.compile('[/:()<>|?*]|(\\\)') filename = p.sub('_', line[2]) folder = p.sub('_', line[5]) A: You are reassigning to the filename and foldername variables at every iteration of the loop. In effect, only * is being replaced. A: You should look at the python string method translate() http://docs.python.org/library/string.html#string.translate with http://docs.python.org/library/string.html#string.maketrans Editing this to add an example as per comment suggestion below: import string toreplace=''.join(["/", "\\", ":", "(", ")", "<", ">", "|", "?", "*"]) underscore=''.join( ['_'] * len(toreplace)) transtable = string.maketrans(toreplace,underscore) filename = filename.translate(transtable) foldername = foldername.translate(transtable) Can simplify by making the toreplace something like '/\:,' etc, i just used what was given above
[ "stackoverflow", "0040951735.txt" ]
Q: Changing phrases to vectors with while function in Python I would like to change the following phrases to vectors with sklearn: Article 1. It is not good to eat pizza after midnight Article 2. I wouldn't survive a day withouth stackexchange Article 3. All of these are just random phrases Article 4. To prove if my experiment works. Article 5. The red dog jumps over the lazy fox I got the following code: from sklearn.feature_extraction.text import CountVectorizer vectorizer = CountVectorizer(min_df=1) n=0 while n < 5: n = n + 1 a = ('Article %(number)s' % {'number': n}) print(a) with open("LISR2.txt") as openfile: for line in openfile: if a in line: X=line print(vectorizer.fit_transform(X)) Which gives me the following error: ValueError: Iterable over raw text documents expected, string object received. Why does this happen? I know this should work because if I type in individually: X=("It is not good to eat pizza","I wouldn't survive a day", "All of these") print(vectorizer.fit_transform(X)) It gives me my desired vectors. (0, 8) 1 (0, 2) 1 (0, 11) 1 (0, 3) 1 (0, 6) 1 (0, 4) 1 (0, 5) 1 (1, 1) 1 (1, 9) 1 (1, 12) 1 (2, 10) 1 (2, 7) 1 (2, 0) 1 A: Look at the docs. It says CountVectorizer.fit_transform expects an iterable of strings (e.g. a list of strings). You are passing a single string instead. It makes sense, fit_transform in scikit does two things: 1) it learns a model (fit) 2) it applies the model on the data (transform). You want to build a matrix, where columns are all the words in the vocabulary and rows correspond to the documents. For that you need to know the whole vocabulary in your corpus (all the columns). A: This problem occurs when you provide the raw data, means directly giving the string to the extraction function ,instead you can give Y = [X] and pass this Y as the parameter then you will get it correct i faced this problem too
[ "stackoverflow", "0007646397.txt" ]
Q: Import a single Excel cell into SSIS Am trying to import a number of metric values from an Excel file into SSIS. I have named each of the cells with data and was hoping to be able to configure a Connection, that would be updated in a ForEach container, to point to each Named Range in turn, in order to bring over the data one value at a time. I see many articles on how to connect to a Sheet or Table in Excel, but none to a Named Range? I saw one article on how to bring over one single cell, but that cell was a part of a table. Can I setup a Connection in SSIS to a single cell, Named or otherwise, and bring back that value? JK A: I can see you implementing this in one of two ways. The first is just a straight Execute SQL Task that returns a single row. The other being a data flow with, probably a script task as your source. With each pass through your loop, you'd probably need to modify the Excel connection manager and/or your query string to point to the correct named range In the section To create a linked server against an Excel spreadsheet To access data from an Excel spreadsheet, associate a range of cells with a name. A named range can be accessed by using the name of the range as the table name. The following query can be used to access a named range called SalesData using the linked server set up in the previous example. This article also describes programmatically access Excel via C#, albeit from ASP.NET but the principal should be the same. My hazy recollection is that the worksheet name would have a $ appended to it, thus sheet1$ while accessing the named range would be without the $. One thing we ran into with our implementation was our servers did not have the appropriate drivers on them and it required us to install the Access engine Lots of generalities in this answer so if you run into specifics, feel free to ping me.
[ "stackoverflow", "0004045921.txt" ]
Q: Problem with DataBindings, explain please public partial class Form1 : Form { MyClass myClass = new MyClass("one", "two"); public Form1() { InitializeComponent(); textBox1.DataBindings.Add("Text", myClass, "Text1", false, DataSourceUpdateMode.Never); textBox2.DataBindings.Add("Text", myClass, "Text2", false, DataSourceUpdateMode.Never); } private void saveButton_Click(object sender, EventArgs e) { myClass.Text1 = textBox1.Text; myClass.Text2 = textBox2.Text; //textBox1.DataBindings["Text"].WriteValue(); //textBox2.DataBindings["Text"].WriteValue(); } } public class MyClass : INotifyPropertyChanged { private string _Text1; private string _Text2; public event PropertyChangedEventHandler PropertyChanged; public string Text1 { get { return _Text1; } set { _Text1 = value; OnPropertyChanged(new PropertyChangedEventArgs("Text1")); } } public string Text2 { get { return _Text2; } set { _Text2 = value; OnPropertyChanged(new PropertyChangedEventArgs("Text2")); } } public MyClass(string text1, string text2) { Text1 = text1; Text2 = text2; } protected void OnPropertyChanged(PropertyChangedEventArgs e) { if (PropertyChanged != null) PropertyChanged(this, e); } } I think is pretty clear what I'm trying to achieve. I want my form to save the changes made in my two TextBoxes to myClass. But whenever I press the save button after editing both text boxes, and saveButton_Click is invoked, the second textBox2's Text goes back to the original text ("two"). I tried using Binding's WriteValue function but the same thing happens. Using .net 4.0. Edit Thanks for your answers, but I don't need workarounds. I can find them myself. I just need to understand a little bit better how binding works. I would like to understand why is this happening? A: Apparently, updating any value on the data source will cause all bindings to be updated. This explains the behavior (setting myClass.Text1 causes textBox2 to be updated with the current value of myClass.Text2). Unfortunately, the few posts I was able to find pretty much just said, "that's how it works". One way to handle this is to create a BindingSource, set BindingSource.DataSource = myClass, and then bind your TextBoxes to the BindingSource. BindingSource raises ListChanged events if the underlying data source is a list and items are added, removed, etc., or if the DataSource properties change. You can suppress these events by setting BindingSource.RaiseListChangedEvents to false, which would let you set multiple properties on myClass without data-binding updating the bound controls. public partial class Form1 : Form { MyClass myClass = new MyClass("one", "two"); BindingSource bindingSource = new BindingSource(); public Form1() { InitializeComponent(); bindingSource.DataSource = myClass; textBox1.DataBindings.Add("Text", bindingSource, "Text1", true, DataSourceUpdateMode.Never); textBox2.DataBindings.Add("Text", bindingSource, "Text2", true, DataSourceUpdateMode.Never); } private void button1_Click(object sender, EventArgs e) { bindingSource.RaiseListChangedEvents = false; myClass.Text1 = textBox1.Text; myClass.Text2 = textBox2.Text; bindingSource.RaiseListChangedEvents = true; } } HTH
[ "stackoverflow", "0002985651.txt" ]
Q: assigning in system of differential equations when i solve numerically a system of two differential equations: s1:=diff(n[Di](t), t)=...; s2:=diff(n[T](t), t)=...; ics:={...}; #initial condition. sys := {s1, s2, ics}: sol:=dsolve(sys,numeric); with respect to "t",then the solution (for example)for "t=4" is of the form, sol(4): [t=4, n1(t)=const1, n2(t)=const2]. now, how is possible to use values of n1(t) and n2(t) for all "t"'s in another equation, namely "p", which involved n1(t) or n2(t)(like: {p=a+n1(t)*n2(t)+f(t)},where "a" and "f(t)" are defined), and to plot "p" for an interval of "t"? A: Perhaps an example will help. s1:=diff(n1(t), t)=sin(t); s2:=diff(n2(t), t)=cos(t); ics:={n1(0)=1,n2(0)=0}: sys := {s1, s2} union ics: sol:=dsolve(sys,numeric,output=listprocedure); N1:=eval(n1(t),sol); N2:=eval(n2(t),sol); N1(0); N1(1.1); N2(0); N2(1.1); p := 11.3 + N1*N2 + tan: plot(p, 0..1.1); You might look at the DEplot routine, which is specialized for plotting ode solutions.
[ "stackoverflow", "0023520938.txt" ]
Q: No Session found for current thread I am trying to get the size of attendees (a list, which is a oneToMany in class Presentation) Planning contains a OneToMany with the corresponding presentations Every time i try to get the size of attendees it fails to lazy load them. I tried writing a query but it says that i can't use the fetch twice. Is there any good way to get the data i need? There are a lot of discussions on the internet about this but none of them seem to solve my problem. I am running on the latest version of hibernate (4.1.7.Final) and am using spring Release 3.2.3 Planning repo: public interface PlanningRepository extends JpaRepository<Planning, Long>{ @Query("select pl from Planning pl join fetch pl.presentations p join fetch p.attendees a where pl.id = ?1") Planning findOneById(Long id); } The relation in class Presentation: @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinTable(name = "presentation_attendees", joinColumns = {@JoinColumn(name = "presentation_id")}, inverseJoinColumns = {@JoinColumn(name = "student_id")}) private List<Student> attendees; The relation in student: @ManyToMany(mappedBy = "attendees") private List<Presentation> presentationsAttending; Where i call it in PlanningController: Planning planning = planningRepository.findOneById(1L); JSONArray pArray = new JSONArray(); JSONObject planningJSON = new JSONObject(); //List<Presentation> presentations = (List<Presentation>)presentationRepository.findByPlanning(planning.getId()); for(Presentation p : planning.getPresentations()) { sessionFactory.openSession(); sessionFactory.getCurrentSession().getTransaction().begin(); //i need the size of attendees presentationJSON.put("subscribers", p.getAttendees().size()); sessionFactory.getCurrentSession().getTransaction().commit(); sessionFactory.close(); } dispatcher-servlet.xml: <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="persistenceUnitName" value="school"/> <property name="dataSource" ref="dataSource" /> </bean> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/> A: I solved this by changing List<> to Set<> on the ManyToMany and OneToMany relations
[ "stackoverflow", "0035065512.txt" ]
Q: Running Multiple Node.js Versions in Tandem I'm working on two applications. The first one has been migrated to 4.2, the other one still needs to be migrated. So, I'm wondering... is there a way to run two different processes against two diff Node.js binaries? In this case, it would be 4.2 and 0.12. A: Yes. If you use nvm (https://github.com/creationix/nvm) you'll be able to do this easily. Using nvm install both Node.js v4.2 and v0.12: nvm install 4.2 nvm install 0.12 When you run nvm use <version>, nvm will set the Node.js version to <version> for just that terminal window/tab. So, in one terminal you can run nvm use 4.2 then run your node.js application, and in another terminal window or tab run nvm use 0.12 and run your node.js application that uses v0.12. If you don't want that terminal window or tab to be scoped to a specific version of Node.js, you can use nvm to just run the server using nvm run <version> <args>. For example: nvm run 0.12 server.js
[ "stackoverflow", "0025096810.txt" ]
Q: Img after a div with jquery Is it possible to insert an img after a div with jquery? If so how to control its position? Please try your answer here: http://jsfiddle.net/cPtU9/2/ HTML: <div id="grey"></div> CSS: #grey { position: absolute; top: 50px; left: 50px; width:200px; height: 200px; background-color: #eee; } JQuery: $('#grey').after("<img src='http://www.w3.org/html/logo/downloads/HTML5_Badge_128.png' />"); A: Not sure what you are trying to accomplish here. Right now the image is created right after the div...i.e outside the div. If thats intentional, you can do the following css to change the image layout: #grey{ position: relative; /*<-- changed to relative*/ top: 50px; left: 50px; width: 200px; height: 200px; background-color: #eee; } img{ position: relative; /* additional css goes here */ } If you are trying to put the image inside the div element then you can use the prepend as follows: $('#grey').prepend('<img src='http://www.w3.org/html/logo/downloads/HTML5_Badge_128.png' />');
[ "math.stackexchange", "0002428900.txt" ]
Q: limit of $\frac{1-\sin x+\cos x }{x-\frac{\pi }{2}}$ how can i show that $$\lim _{x\to \frac{\pi }{2}}\left(\frac{1-\sin \:x\:+\cos \:x\:}{x-\frac{\pi }{2}}\right)=-1$$ $$\left(\frac{1-\sin \:x\:+\cos \:x\:}{x-\frac{\pi }{2}}\right)=\left(\frac{1+\cos \:x -\sin x}{x-\frac{\pi }{2}}\right)$$ any help thanks A: Let $\frac\pi2-x=2y$ using $\sin2y=2\sin y\cos y,\cos2y=1-2\sin^2y$ $$\lim _{x\to \frac{\pi }{2}}\left(\frac{1-\sin \:x\:+\cos \:x\:}{x-\frac{\pi }{2}}\right)=-\lim_{y\to0}\dfrac{1-\cos2y+\sin2y}{2y}$$ $$=-\lim_{y\to0}\dfrac{\sin y}y\cdot\lim_{y\to0}(\sin y+\cos y)=?$$
[ "stackoverflow", "0009891028.txt" ]
Q: How to get the current test filename from RSpec? I'm trying to speed up a large RSpec project's tests. In addition to using RSpec's --profile option I wanted to get the longest running test files [1] printed out. In my spec_helper.rb I dump the classes being tested and total time to a file, however as we have spec/model and spec/request directories I'd really like to be able to print the current test's filename and not just the class name (described_class), so that the user can disambiguate between model/foo_spec.rb and request/foo_spec.rb when optimizing. In a before block in the spec/spec_helper.rb, how can I get the current test file's filename? My (heavily trimmed) spec_helper looks like this: config.before :all do @start_time = Time.now end config.after :all do |test| timings.push({ :name => test.described_class, :file => 'I do not know how to get this', :duration_in_seconds => (Time.now - @start_time) }) end config.after :suite do timing_logfile_name = 'log/rspec_file_times.log' timing_logfile = "#{File.dirname(__FILE__)}/../#{timing_logfile_name}" file = File.open(timing_logfile, 'w') timings.sort_by{ |timing| timing[:duration_in_seconds].to_f }.reverse!.each do |timing| file.write( sprintf("%-25.25s % 9.3f seconds\n", timing[:name], timing[:duration_in_seconds]) ) end file.close tell_if_verbose("Overall test times are logged in '#{timing_logfile_name}'") end This doesn't seem to be available in the curretn RSpec meta-data, but I'm hoping someone more familiar with the internals can think of a way to expose it. Thanks, Dave [1] Often a file with, say, 100 examples in it yields more speed up than a single example from --profile - when that large file's before :each / before :all blocks are targetted, obviously even a ms saved is multiplied up by the number of tests in the file. Using this technique in addition to --profile helped me a lot. A: As long as you're just using this for profiling your tests to identify which files need to be improved, you should be able to toss this into your spec_helper.rb file (and remove it afterwards). I fully understand that this is not pretty/clean/elegant/acceptible in production environments and I disavow that I ever wrote it :) config.before(:each) do |example| path = example.metadata[:example_group][:file_path] curr_path = config.instance_variable_get(:@curr_file_path) if (curr_path.nil? || path != curr_path) config.instance_variable_set(:@curr_file_path, path) puts path end end
[ "stackoverflow", "0042503073.txt" ]
Q: How to make array of objects in JS I want to send a multi level array via AJAX. so I tried to make an object of objects as follow: var info = {}; info.pickup = {}; info.pickup.contact = {}; info.pickup.items_quantity = {}; info.pickup.items = {}; info.delivery = {}; info.delivery.contact = {}; info.delivery.level = {}; then I started filling the objects, for example: $('.operation-create .pickup .contact-details').each(function () { var arr = {}; arr['contact_name'] = $(this).find('input[name="pickup-contact-name"]').val(); arr['contact_phone'] = $(this).find('input[name="pickup-contact-phone"]').val(); arr['pickup-suburb'] = $(this).find('select[name="pickup-suburb"]').val(); arr['single-pickup-address'] = $(this).find('input[name="single-pickup-address"]').val(); info.pickup.contact.push(arr); }); info.pickup.push(info.pickup.contact); etc... However unfortunately it didn't work. I get this error: info.pickup.contact.push is not a function What I should do here? What is the right way to send this array via AJAX? A: You need an array as value info.delivery.contact = []; // ^^ The last line info.pickup.push(info.pickup.contact); makes no sense, because you have properties in this object. For pushing some values, you need an array info.pickup = []; // ^^ An while you already have an array for info.pickup.contact, you could skip the line info.pickup.push(info.pickup.contact); A: info.pickup.contact = {}; That is an object declaration, not array. An array should be info.pickup.contact = []; // `[]` A: It's important to understand the difference between an object and an array. {} creates a plain object, which doesn't have a push method. [] creates an array, which is an object with additional features, including a push method. Looking at your code, at the least, you want info.pickup.contact and probably info.delivery.contact to be arrays (I'm guessing probably items_quantity and items as well, but it's hard to be sure). (The thing you call arr in your looping function isn't an array and doesn't need to be.) So at a minimum: info.pickup.contact = []; // -------------------^^ and info.delivery.contact = []; // ---------------------^^ You also want to remove the info.pickup.push(info.pickup.contact); at the end; info.pickup isn't an array, and you've already put the contacts in info.pickup.contact. Side note: Your code might also benefit from using object initializers: var info = { pickup: { contact: [], items_quantity: {}, // This might also want to be an array items: {} // This might also want to be an array }, delivery: { contact: [], level: {} // No idea what you're doing with this, so... } }; $('.operation-create .pickup .contact-details').each(function () { info.pickup.contact.push({ contact_name: $(this).find('input[name="pickup-contact-name"]').val(), contact_phone: $(this).find('input[name="pickup-contact-phone"]').val(), pickup-suburb: $(this).find('select[name="pickup-suburb"]').val(), single-pickup-address: $(this).find('input[name="single-pickup-address"]').val() }); }); ...but it's a matter of style.
[ "math.stackexchange", "0003588899.txt" ]
Q: Fitting a line through intercept 0 I need to code a least squares routine to fit a line $$y = m*x$$ into a 2d set of points $$(x_i,y_i)$$ How can I find the regression line without an interceptor? A: If I understand your problem, you want to find the regression line without an interceptor, in which case you can use the estimator of $\beta$ $$\hat{\beta} = \frac{\overline{xy}}{\overline{x^2}}$$
[ "stackoverflow", "0024655847.txt" ]
Q: Very slow matrix transpose operation with CUBLAS I'm trying to parallelize a matrix transpose operation using the CUBLAS library (with cublasSgeam function). The output data are correct, but It's taking on average 150 more time than my CPU version. Why? CPU code (For transposing a matrix of N = 5000 by M=140) // Starting the timer float *matrixT = (float *) malloc (N * M * sizeof(float)); for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) matrixT[(j*N)+i] = matrix[(i*M)+j]; // matrix is obviously filled //Ending the timer GPU code (For transposing a matrix of N = 5000 by M=140) float *h_matrixT , *d_matrixT , *d_matrix; h_matrixT = (float *) malloc (N * M * sizeof(float)); cudaMalloc((void **)&d_matrixT , N * M * sizeof(float))); cudaMalloc((void**)&d_matrix , N * M * sizeof(float))); cudaMemcpy(d_matrix , matrix , N * M * sizeof(float) , cudaMemcpyHostToDevice)); //Starting the timer const float alpha = 1.0; const float beta = 0.0; cublasHandle_t handle; cublasCreate(&handle); cublasSgeam(handle, CUBLAS_OP_T, CUBLAS_OP_N, N, M, &alpha, d_matrix, M, &beta, d_matrix, N, d_matrixT, N); cublasDestroy(handle); //Ending the timer cudaMemcpy(h_matrixT , d_matrixT , N * M * sizeof(float) , cudaMemcpyDeviceToHost)); cudaFree(d_matrix); cudaFree(d_matrixT); Elapsed times CUBLAS : 148.461 ms CPU : 0.986944 ms PS: Running on GeForce GTX 660 & Intel Core i5 660 A: Run your code with one of the profilers to see where the time is being spent. Move the cublasCreate function out of your timing region. That is picking up all sorts of CUDA and library start up time, which should not be incorporated in benchmarking a single function (or if you intend to benchmark this way, there is obviously little point in using a GPU to perform this one single function. It will not accelerate it, as you have discovered.) I would also recommend moving the cublasDestroy out of the timing loop. You may then wish to include a cudaDeviceSynchronize(); before your final timing closure. Here's a fully worked example, choosing M = 1000 and N = 1000, with the changes above implemented: $ cat t469.cu #include <stdio.h> #include <cublas_v2.h> #include <time.h> #include <sys/time.h> #define uS_PER_SEC 1000000 #define uS_PER_mS 1000 #define N 1000 #define M 1000 int main(){ timeval t1, t2; float *matrix = (float *) malloc (N * M * sizeof(float)); // Starting the timer gettimeofday(&t1, NULL); float *matrixT = (float *) malloc (N * M * sizeof(float)); for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) matrixT[(j*N)+i] = matrix[(i*M)+j]; // matrix is obviously filled //Ending the timer gettimeofday(&t2, NULL); float et1 = (((t2.tv_sec*uS_PER_SEC)+t2.tv_usec) - ((t1.tv_sec*uS_PER_SEC)+t1.tv_usec))/(float)uS_PER_mS; printf("CPU time = %fms\n", et1); float *h_matrixT , *d_matrixT , *d_matrix; h_matrixT = (float *) (malloc (N * M * sizeof(float))); cudaMalloc((void **)&d_matrixT , N * M * sizeof(float)); cudaMalloc((void**)&d_matrix , N * M * sizeof(float)); cudaMemcpy(d_matrix , matrix , N * M * sizeof(float) , cudaMemcpyHostToDevice); //Starting the timer gettimeofday(&t1, NULL); const float alpha = 1.0; const float beta = 0.0; // gettimeofday(&t1, NULL); cublasHandle_t handle; cublasCreate(&handle); gettimeofday(&t1, NULL); cublasSgeam(handle, CUBLAS_OP_T, CUBLAS_OP_N, N, M, &alpha, d_matrix, M, &beta, d_matrix, N, d_matrixT, N); cudaDeviceSynchronize(); gettimeofday(&t2, NULL); cublasDestroy(handle); //Ending the timer float et2 = (((t2.tv_sec*uS_PER_SEC)+t2.tv_usec) - ((t1.tv_sec*uS_PER_SEC)+t1.tv_usec))/(float)uS_PER_mS; printf("GPU time = %fms\n", et2); cudaMemcpy(h_matrixT , d_matrixT , N * M * sizeof(float) , cudaMemcpyDeviceToHost); cudaFree(d_matrix); cudaFree(d_matrixT); return 0; } $ nvcc -O3 -arch=sm_20 -o t469 t469.cu -lcublas $ ./t469 CPU time = 8.744000ms GPU time = 0.327000ms $ If instead, I change the above code to leave the timing function start before the cublasCreate call, I get this: $ ./t469 CPU time = 9.475000ms GPU time = 78.393997ms $
[ "stackoverflow", "0009243959.txt" ]
Q: How to append x-header information in generated .eml / .msg file My requeriment is to open the email content to,cc,subject,body, attachement retrive from DB and open the content in user email client ( Outlook ). To achieve this i'm creating .eml/.msg file with the retrieved information and saving into the local disk and opening the .eml file, all this flow happens programmatically in C#. But when the content opened in  outlook email client it opens as send mode( Although when opening a email to read/send). I want to open the email in differnet mode Compose/ Reply/ Forward. When i gone through many article understand have to add x-header when generating the .eml file will do the magic. But i'm sure how to achieve this solution. Can anyone help ? A: var mail = new MailMessage(); mail.Headers.Add("X-Unsent", "1");
[ "math.stackexchange", "0001804851.txt" ]
Q: numbers from $1$ to $2046$ We have randomly taken $21$ integers from $1$ to $2046$. Show that we can take $a$, $b$ and $c$ from the previous $21$ integers in a way such that the following inequality holds \begin{equation} bc<2a^2<4bc \end{equation} My Attempt: I have found $3$ triplets of such integers, but I do not think the above inequalities hold for every triplet. Any hints ? A: Let the 21 numbers be $x_1<x_2<\ldots <x_{21}$. It is not possible to have $x_{k+2}\ge 2x_k+1$ (or equivalently $x_{k+2}+1\ge 2(x_k+1)$) for all $k$ as that would lead to $2047 \ge x_{21}+1\ge 2^{10}(x_1+1)\ge 2^{11}=2048$. Thus we find $k$ such that $x_{k+2}\le 2x_k$. With $b:=x_k$, $a:=x_{k+1}$, $c:=x_{k+2}\le 2b$, we have $$ bc\le 2b^2<2a^2<2c^2\le 4bc$$ as desired. The above proof suggests that the conditions are sharp (i.e., drawing only 20 numbers from $1,\ldots 2046$, or drawing 21 numbers from $1,\ldots,2047$ might not suffice to guarantee the existence of such triples. However, we see that already $x_3=3$ allows to pick $a=2, b=1,c=3$ with $bc=3<2a^2=8<4bc=12$. Hence we may assume $x_3\ge 4$ and obtain $x_{21}\ge 2^9\cdot (x_3+1)-1=2559$. We conclude that $2046$ can be replaced with $2558$ in the problem statement. Further investigation shows that we can even go up to $3070$: If $x_3\ge 5$ we find as above that $x_{21}\ge2^9(x_3+1)-1=3071$. So we may assume $x_3=4$. If $x_2=2$, we find $x_1=1$ and have our triple; and if $x_2=3$ then $x_2,x_3,x_4$ is our triple as long as $x_4\le 10$. We conclude $x_4\ge 11$, $x_{21}>x_{20}\ge 2^8(x_4+1)-1\ge 3071$. A: Note that for any three positive integers $a,b,c$, if $2^k\leqslant b<a<c<2^{k+1}$ for some $k\in\mathbb{Z}_{>0}$, then $$bc<ac<a\cdot 2^{k+1}=2a\cdot 2^k\leqslant 2a\cdot a=2a^2,$$ and $$bc>ba\geqslant 2^ka=\frac{1}{2}\cdot 2^{k+1}a>\frac{1}{2}\cdot a\cdot a=\frac{1}{2}a^2.$$ Thus, $2^k\leqslant b<a<c<2^{k+1}$ for some $k\in\mathbb{Z}_{>0}\Rightarrow bc<2a^2<4bc.$ And $b=1,a=2,c=3$ also satisfies the requirement. Note that we can divide the integers from $1$ to $2046$ into ten parts: \begin{align*} & A_1=\{1,2,3<2^2\}\\ & A_2=\{2^2=4,5,6,7<2^3\}\\ & \dots \\ & A_{10}=\{2^{10}=1024, 1025,\dots, 2046<2^{11}\} \end{align*} If we choose $21=10\times 2+1$ integers in $[1,2046]$,we can always find three of them $x_1<x_2<x_3$ falls in the same part $A_i$. Then we can let $b=x_1,a=x_2,c=x_3$. A: Let set $S$ be the set of integers from $1$ to $2046$, we split $S$ to $S_i$s like this: $$S_1=\{1,2,3\}\\S_i=\{s\in\mathbb{Z}\,|\,2^{i}\le s\lt2^{i+1}\}\quad (2\le i\lt10)\\ S_{10}=\{1024,1025,\dots,2046\}$$ So we have $10$ sets in total, by Pigeonhole principle there's a set which has at least $\lceil\frac{21}{10}\rceil=3$ elements from those $21$ chosen ones. Name these three $a,b,c$ such that $c\lt a\lt b$, then try to prove these inequalities.
[ "gamedev.stackexchange", "0000183464.txt" ]
Q: How to flip a rectangle I'm curently working on a system that make the player character look towards the mouse pointer. My system is effective but i'm having an issue while displaying the rectangle. In the Following code i test the mouse position by translating it in the world and then i test if the world pos of the mouse is greater than the position of the player or not. if the mouse is on left side of the boundary, the player will rotate to look at it. To make the rotation, i put the X coordinate on the other side of the position and i make the width negative. THis normaly should emulate the rotation. but my rectangle does not shows up. Point MousePos = Vector2.Transform(Mouse.GetState().Position.ToVector2(), Matrix.Invert(Camera.GetViewMatrix())).ToPoint; if (MousePos.X > Position.ToPoint().X) { EntityDisplayRectangle.X = Position.ToPoint().X - (int)EntitySize.X * (int)TileSize.X * _displayResizeFactor / 2; EntityDisplayRectangle.Width = (int)EntitySize.X * (int)TileSize.X * _displayResizeFactor; }else{ EntityDisplayRectangle.X = Position.ToPoint().X + (int)EntitySize.X * (int)TileSize.X * _displayResizeFactor / 2; EntityDisplayRectangle.Width = -((int)EntitySize.X * (int)TileSize.X * _displayResizeFactor); } EntityDisplayRectangle.Y = (int)Position.Y - ((int)EntitySize.Y + 1); here is two screenshots of what i curently have: the red dot is a point drawn by this line spriteBatch.DrawPoint(new Vector2(getEntityDisplayRectangle().X, getEntityDisplayRectangle().Y), Color.Red, 3); So, is there an other way to do or is it even possible? The player texture is from a tileSet and i use a source rectangle to pick the correct image from it here is the code that draws the player: spriteBatch.Draw(TileSet, EntityDisplayRectangle, TileSetOffsetRectangle, Color.White); Up: here is the rectangle drawn with a draw rectangle Note: the red box is the collision box. it's showwn just for debug purpose it seems that the rectangle struggle to exist when it's width is negative. A: Answer: Very simple. i've just created a public bool variable called facing. in the ancient code i've made i replaced everything by facing=true or =false according to the position of the mouse. true for right and false for left. then when i draw the sprite i test for this variable and depending on the direction i Apply a different effect. when it's true the effect is empty ( new SpriteEffects()) but when it's false, i Apply the effect SpriteEffects.FlipHorizontally this give the Following code (at the draw method of the entity class): SpriteEffects effect; if (facing) { effect = new SpriteEffects(); } else { effect = SpriteEffects.FlipHorizontally; } spriteBatch.Draw(TileSet, destinationRectangle: EntityDisplayRectangle, sourceRectangle: TileSetOffsetRectangle, color: Color.White, rotation: 0, origin: new Vector2(0, 0), effects: effect, layerDepth: 0); so with this method, no need to actually flip the rectangle. but only to flip at drawing. i've found the answer in this stackex question I Hope it helped people in the same situation. P.S. the code to detect mouse pos is now really small: Point MousePos = Vector2.Transform(Mouse.GetState().Position.ToVector2(), Matrix.Invert(Camera.GetViewMatrix())).ToPoint(); if (MousePos.X > Position.ToPoint().X) { facing = true; } else { facing = false; }
[ "stackoverflow", "0052742437.txt" ]
Q: MySQL server doesn't run via MAMP on mac OS I upgraded my MAMP PRO 3.5.2 version to the 5th and MySQL start fails. I killed mysqld processes via killall -9 mysqld, cleaned log files like ib_logfile* and tried manipulations with innodb recovery. The log I've got looks like this: 2018-10-10T14:16:12.6NZ mysqld_safe Logging to '/Applications/MAMP/logs/mysql_error.log'. 2018-10-10T14:16:12.6NZ mysqld_safe Starting mysqld daemon with databases from /Library/Application Support/appsolute/MAMP PRO/db/mysql57 2018-10-10T14:16:13.043096Z 0 [Warning] Insecure configuration for --secure-file-priv: Current value does not restrict location of generated files. Consider setting it to a valid, non-empty path. 2018-10-10T14:16:13.051110Z 0 [Note] /Applications/MAMP/Library/bin/mysqld (mysqld 5.7.23) starting as process 5538 ... 2018-10-10T14:16:13.064223Z 0 [Warning] Setting lower_case_table_names=2 because file system for /Library/Application Support/appsolute/MAMP PRO/db/mysql57/ is case insensitive 2018-10-10T14:16:13.074890Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins 2018-10-10T14:16:13.074926Z 0 [Note] InnoDB: Uses event mutexes 2018-10-10T14:16:13.074936Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier 2018-10-10T14:16:13.074943Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.3 2018-10-10T14:16:13.074972Z 0 [Note] InnoDB: Adjusting innodb_buffer_pool_instances from 8 to 1 since innodb_buffer_pool_size is less than 1024 MiB 2018-10-10T14:16:13.079521Z 0 [Note] InnoDB: Number of pools: 1 2018-10-10T14:16:13.084840Z 0 [Note] InnoDB: Using CPU crc32 instructions 2018-10-10T14:16:13.089357Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M 2018-10-10T14:16:13.114376Z 0 [Note] InnoDB: Completed initialization of buffer pool 2018-10-10T14:16:13.140491Z 0 [Note] InnoDB: Highest supported file format is Barracuda. 2018-10-10T14:16:13.145746Z 0 [ERROR] InnoDB: Trying to access page number 527111 in space 0, space name innodb_system, which is outside the tablespace bounds. Byte offset 0, len 16384, i/o type read. If you get this error at mysqld startup, please check that your my.cnf matches the ibdata files that you have in the MySQL server. 2018-10-10T14:16:13.145772Z 0 [ERROR] InnoDB: Server exits. 2018-10-10T14:16:13.6NZ mysqld_safe mysqld from pid file /Applications/MAMP/tmp/mysql/mysql.pid ended Would appreciate any hint which direction to go as I start to consider to uninstall and reinstall of MAMP which means I will lose few local DB installations. Thanks! A: So the issue was solved and MySQL runs locally via MAMP 5.1. While figuring out what was going wrong in the my.cnf following settings were applied: increased innodb_buffer_pool_size value: innodb_buffer_pool_size = 1024M force recovery mode was on innodb_force_recovery = 1 That lead to the error that mentioned in the question: [ERROR] InnoDB: Trying to access page number 527111 in space 0, space name innodb_system, which is outside the tablespace bounds. Byte offset 0, len 16384, i/o type read. If you get this error at mysqld startup, please check that your my.cnf matches the ibdata files that you have in the MySQL server. At this point default settings for the ibdata dir and path were uncommented inside of my.cnf: innodb_data_home_dir = "/Library/Application Support/appsolute/MAMP PRO/db/mysql57" innodb_data_file_path = ibdata1:10M:autoextend innodb_log_group_home_dir = "/Library/Application Support/appsolute/MAMP PRO/db/mysql57" Error log was reported on access limits (don't have an exact sentence at front of me), was lost a bit here, and as a guess measure, I extended rights for the folder /Library/Application Support/appsolute/MAMP PRO/db/mysql57 to my current user. That didn't change the log. The error about a wrong path to the ibdata was still there. In the end the renaming of the folder mysql (where was the full version of ibdata (~40Gb)) to mysql57 helped. There was following folder structure in /Library/Application Support/appsolute/MAMP PRO/db/ after the installation of MAMP 5.1: -- mysql -- mysql56_TIMESTAMP -- mysql57 with the same structure of files, but a closer comparison of the content showed that the full version of the file inside of mysql, so renamed it, and removed all folders after tests that MAMP works correctly without them. So now I have only one mysql folder inside of /Library/Application Support/appsolute/MAMP PRO/db/. The settings inside of my.cnf that I customized in the process rolled back.
[ "stackoverflow", "0010740039.txt" ]
Q: "error occurred while loading or saving configuration information" i have two accounts in my redhat instance. one is ora112 user and other user is root user by default. i have been updating ora112 users bashrc file using root account, but i did change my command prompt to ora112 before editing. this is what i did. root$ su ora112 password: ora112$ vi ~.bashrc but when doing that, i had logged into the system using root even thought command prompt is changed to ora112 but when i login to the system as ora112 , it gives me following screen. could anybody help me to find what is going wrong here, thanks in advance for anyhelp A: su - ora112 "su - user" gives you the environment for the user "su user" does not
[ "raspberrypi.stackexchange", "0000046622.txt" ]
Q: Raspberry Pi 3 - WiFi Stopped Working - How to debug and fix without restarting I believe my question is different from the suggested duplicate in that the other questioner never had access to the internet over Wifi, whereas I had access to Wifi without any problems for one week but no longer do. Along with a fix, I am asking to debug it to see what happened. KDMs answer also permitted me to reactivate the WiFi without restarting; whereas the other answer required a firmware update and a restart. I hooked up my new Raspberry Pi 3 and the Wifi was very easy to set up. However, about 1 week after this I could not SSH into the pi. My router's UI didn't show the RPI3 registered any more over Wifi. I plugged in an Ethernet cable and my Pi immediately registered with my router. I SSH'd into it and attached to my session of screen and saw that my application was still running. This means the Pi never turned off or restarted -- only the Wifi stopped working. It has been about one more week and the Wifi has never come back online by itself. My RPi2, cellphone, laptop, etc. still have access to WiFi. Aside from doing a restart, how do I fix this? How do I debug this? Solution Update: @KDM's solution, which use used on RP1/RP2 for wifi dongle problems, also worked for me (I believe this proves that this question is not a duplicate): sudo ifdown wlan0 sudo ifup wlan0 However, I am concerned that the WiFi stopped working in the first place. I don't want to have to plug in an ethernet cable and issue these two commands every week. I have two RPI 1s with two different WiFi dongles. One of them never had any issues at all, while the other one needed to be restarted every so often. I'm worried that there could be something wrong with the RPI3's in built WiFi. I have the latest version of Raspbian Lite, version March 2016. Issuing sudo apt-get dist-upgrade shows that the following packages will be upgraded: apt apt-utils gnupg gpgv initramfs-tools libapt-inst1.5 libapt-pkg4.12 libc-bin libc-dev-bin libc6 libc6-dbg libc6-dev libhogweed2 libnettle4 libpcre3 libsystemd0 libtalloc2 libudev1 libwbclient0 locales multiarch-support openssh-client openssh-server openssh-sftp-server raspberrypi-sys-mods raspi-config samba-common ssh systemd systemd-sysv tzdata udev I can sudo iwlist wlan0 scan > scan.log and find my SSID in the list. I can post this if it would be helpful. Running ifconfig shows the wlan0. I am using the default /etc/network/interfaces file that comes loaded on Raspbian Jesse for RPI3: source-directory /etc/network/interfaces.d auto lo iface lo inet loopback iface eth0 inet manual allow-hotplug wlan0 iface wlan0 inet manual wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf allow-hotplug wlan1 iface wlan1 inet manual wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf A: (Edit: good point, Matthew Moisen) I had a problem with my RPi2 (with an external USB WiFi dongle). Ultimately I found a replacement adapter, but my solution (unfortunately, as you've discovered, you'll need a hardwired connection) to resetting it without rebooting the RPi was to restart the WLAN interface: sudo ifdown wlan0 sudo ifup wlan0 I've subsequently swapped out my dongle for one which didn't originate in Hong Kong and I've not had any bother with it since ... even though it lives in my airing cupboard, which is not the favoured environment for computing equipment! Edited again: The other thing, I've just remembered. Try rebooting your router. I've never fallen foul of this with the Pi, but my android phone loses WiFi every other week and will not re-connect (even after a battery yank). There is an upper limit on the number DHCP addresses which my router can "remember" issuing. My suspicion is that if 10 devices all have a 7 day lease to run, the 11th doesn't get issued an IP. Rebooting seems to clear the leases. Suck it and see.
[ "stackoverflow", "0045163723.txt" ]
Q: How to post table with a form in php? I have a form with a table (values in it can be edited) in it, like this: <form action="file.php" id="myform" method="POST"> <input name="inp"> <div class="divclass"> <table id="mytable" name="mytable"> <tr><th>col1</th><th>col2</th></tr> <tr><td contenteditable='true'>val11</td> <td contenteditable='true'>val12</td></tr> <tr><td contenteditable='true'>val21</td> <td contenteditable='true'>val21</td></tr> </table> </div> <input type='submit' name='submit' value='Submit'> </form> <?php print_r ($_POST) ?> So, when I click on submit, the entire form should be submitted right? But just the inputs - inp & submit get submitted to the form, which I know when I print the post parameter array in php. Can someone please explain how I can get the table data too in my post parameter array $_POST? Also how do I trigger an onchange event on the table? I tried this, but it didn't seem to work : $("#mytable").change(function (event) { console.log("changed") console.log($("#keno_config_table").val()) }) A: I offer you to do this <form action="file.php" id="myform" method="POST"> <input name="inp"> <div class="divclass"> <table id="mytable" name="mytable"> <tr> <th>col1</th> <th>col2</th> </tr> <tr> <td><input name='col1[]' style='border:0;outline:0;display:inline-block' value='value'></td> <td><input name='col2[]' style='border:0;outline:0;display:inline-block' value='value'></td> </tr> <tr> <td><input name='col1[]' style='border:0;outline:0;display:inline-block' value='value'></td> <td><input name='col2[]' style='border:0;outline:0;display:inline-block' value='value'></td> </tr> </table> </div> <input type='submit' name='submit' value='Submit'> </form> (of course, make a class for styles, I just wanted to do it simpler). Inputs will look like contenteditable tags without borders and you will be able to get an array of all col1 and col2 like $_POST['col1'] and $_POST['col2'] Also, you may change values to placeholders if you don't want default data to be sent.
[ "stackoverflow", "0063046152.txt" ]
Q: How do I install Bulma in Angular? I am getting an error, visible via the browser inspector after installing Bulma I have angular-10. The steps I took are npm -i bulma. The bulma directory is in node_modules/bulma npm i -D @creativebulma/bulma-collapsible Load javascript in angular.json as "styles": [ "src/styles.css", "./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css", "./node_modules/bulma/css/bulma.css" ], Load the css in a component css file @import '~@angular/material/prebuilt-themes/deeppurple-amber.css'; @import '~bulma/css/bulma.css'; The error message via the console is Could not load content for http://localhost:4200/node_modules/bulma/css/bulma.css A: You load the bulma.css multiple time, once at angular.json and again at css import. The steps could be simply, Create new Angular application by ng new angular-bulma Add bulma to the project by npm install bulma Update the angular.json for bulma css by "styles": [ "src/styles.scss", "node_modules/bulma/css/bulma.css" ],
[ "stackoverflow", "0020548109.txt" ]
Q: Could someone explain this description of System.nanoTime()? This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow. I'm not sure how the the values are not precise and logic behind the numerical overflow. A: This method provides nanosecond precision, but not necessarily nanosecond accuracy The method will give you a number in nanoseconds, but the clock it uses may not actually be able to track nanoseconds. Some number of the last digits may be wrong. In the applications for which this method is used, this inaccuracy is fine. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow. 2^63 nanoseconds is too many nanoseconds for a long to represent. If you run your code for 292 years, so much time will have passed that Java is unable to express just how long it's been running.
[ "ru.stackoverflow", "0000760431.txt" ]
Q: Динамическая проверка строк в txt и запуск/остановка потоков по строкам Есть рабочий скрипт, который запускает поток с функцией на каждую строку загруженного txt: def work(): while True: requests.get(line) time.sleep(11) for line in base: threading.Thread(target=work,args=(line)).start() вопрос: как сделать так, чтобы например каждую минуту строки в base.txt проверялись повторно, и если одну строку удалили- ее поток завершался, а если добавили- то стартовал новый поток с этой строкой? В base.txt содержатся адреса сайтов, с новой строки каждый, например: mysite.com yoursite.com В фунцкии work бесконечным циклом к этим сайтам идет запрос и проверка определенной информации A: Попытка убить потоки снаружи указывает на ошибку в дизайне программы. Потоки следует останавливать (если это вообще оправданно), только с кооперацией с их стороны. Это не случайность, что нет Thread.stopметода, в отличии от к примеру Process.terminate. Чтобы периодически выполнять функцию в отдельных потоках и запускать/останавливать выполнение отдельных циклов повторения раз в минуту в соответствии с текущим содержимым входного файла, можно call_repeatedly() использовать и простой временно́й цикл: import time stop_calls_to = {} # hostname -> cancel future calls while True: with open('base.txt') as file: hostnames = set(filter(None, map(str.strip, file))) # stop calls to hostnames that are not in base.txt for hostname in (stop_calls_to.keys() - hostnames): stop_calls_to[hostname]() del stop_calls_to[hostname] # add new repeating calls from base.txt for hostname in (hostnames - stop_calls_to.keys()): stop_calls_to[hostname] = call_repeatedly(11, check_site, hostname) time.sleep(60) # wait a minute until the next sync watchdog позволяет следить за файлом, чтобы без долгой паузы новые изменения отслеживать. При большом количестве сайтов, лучше асинхронные вызовы использовать (к примеру, с помощью aiohttp) вместо создания отдельного потока для каждого сайта.
[ "stackoverflow", "0062938288.txt" ]
Q: Function "eliminate selected polygons" doesn't work with PyQGIS I have a vector layer (correction) based on a raster layer. It contains some little features and I want to merge those features to bigger ones. The function "eliminate selected polygons" seems to do the trick when used in QGIS but when I used it in pyQGIS the selected features aren't taken into account. This is my layer with the selection This is the expected output, the one from QGIS This is my actual output, the one from pyQGIS When I run my code the function doesn't trigger the CRITICAL error. The first log is my code and the second is the process without any polygon selection. Does anyone already have this issue ? Is it possible to use another similar function ? Thanks in advance QGIS Version : 3.14 (pi) OS : Linux Mint 20 Ulyana (Ubuntu focal 20.04) This is my code : chemin_sortie = "/projet_qgis/pente/donnees_traitement/" #Input correction = chemin_sortie + 'correction' + '.shp' correction_layer = iface.addVectorLayer(correction, '', 'ogr') #Output pente_vecteur_grand = chemin_sortie + 'pente_vecteur_grand' + '.shp' #Selection and process correction_layer.selectByExpression('$area < 500') processing.run("qgis:eliminateselectedpolygons", {'INPUT':correction_layer,'MODE':2,'OUTPUT':pente_vecteur_grand}) pente_vecteur_grand_layer = iface.addVectorLayer(pente_vecteur_grand, '', 'ogr') A: I made a function to realize the same operation as qgis:eliminateselectedpolygons. There is still some differences, I think it's related to the order of the polygons to merge. This function is optimizable but works for me. This is my layer with the selection This is the output with the qgis function with min area This is the output of the pyqgis function with min area This is the output with the qgis function with max area This is the output of the pyqgis function with max area This is the code : import types chemin_sortie = "/projet_qgis/pente/donnees_traitement/" # Input correction = chemin_sortie + 'correction' + '.shp' correction_layer = iface.addVectorLayer(correction, '', 'ogr') # Selection correction_layer.selectByExpression('$area < 500') # Functions def get_key(dict, val): for key, value in dict.items(): if val == value: return key def eliminateselectedpolygon(layer, param): if isinstance(param, types.BuiltinFunctionType): features = layer.getFeatures() n=0 index = QgsSpatialIndex() allfeatures = {} selectedfeatures = {} for f in features: value=[] n = n+1 geom = f.geometry() aire = geom.area() aire = '%.5f' % aire aire = float(aire) value.append(f) value.append(aire) allfeatures[f.id()]=value index.addFeature(f) for f in layer.selectedFeatures(): selectedfeatures[f.id()]=f.id() suppression = [] while len(selectedfeatures) != 0: f_id = min(selectedfeatures.values()) f = allfeatures[f_id] f_geom = f[0] ids = index.intersects(f_geom.geometry().boundingBox()) dict_aire = {} for a_id in ids: if a_id != f_id and allfeatures[a_id][0].geometry().touches(f_geom.geometry()) and QgsWkbTypes.displayString(int(allfeatures[a_id][0].geometry().intersection(f_geom.geometry()).wkbType())) != "Point" : dict_aire[a_id]=allfeatures[a_id][1] a_id = get_key(dict_aire, param(dict_aire.values())) a = allfeatures[a_id] a_geom = a[0] attrs = layer.getFeature(a_id).attributes() suppression.append(f_id) suppression.append(a_id) if a_id in selectedfeatures: del selectedfeatures[a_id] del allfeatures[a_id] index.deleteFeature(a_geom) layer.startEditing() geom = None geom = QgsGeometry.fromWkt('GEOMETRYCOLLECTION()') geom = geom.combine(f_geom.geometry()) geom = geom.combine(a_geom.geometry()) feat = QgsFeature(layer.fields()) feat.setGeometry(geom) feat.setAttributes(attrs) layer.addFeature(feat) feat.setId(abs(n)) layer.commitChanges() layer.triggerRepaint() value_feat = [] geom = feat.geometry() aire = geom.area() aire = '%.5f' % aire aire = float(aire) value_feat.append(feat) value_feat.append(aire) allfeatures[feat.id()]=value_feat index.addFeature(feat) del selectedfeatures[f_id] del allfeatures[f_id] index.deleteFeature(f_geom) n = n + 1 layer.startEditing() for feature in suppression: res = layer.deleteFeature(feature) layer.commitChanges() layer.triggerRepaint() return layer print("Param should be min or max") return None eliminateselectedpolygon(correction_layer, max)
[ "stackoverflow", "0012377046.txt" ]
Q: Scala 2.10 reflection: ClassSymbol.isCaseClass works in scala console but not in script/app I am playing around with reflection in Scala 2.10.0-M7 and stumbled upon the ClassSymbol.isCaseClass method which behaves like expected in the scala console but not when executed as a java application or as a scala script. I've defined TestScript.scala like this: import reflect.runtime.currentMirror case class TestCase(foo: String) object Test { def main(args: Array[String]) { val classSymbol = currentMirror.reflect(new TestCase("foo")).symbol val isCaseClass = classSymbol.isCaseClass println(s"isCaseClass: $isCaseClass") } } Test.main(Array()) If I execute it on the command line calling $ scala TestScript.scala I get this output: isCaseClass: false If I instead input the code into the interactive scala shell or load it like this: scala> :load TestScript.scala I get the following correct output: Loading TestScript.scala... import reflect.runtime.currentMirror defined class TestCase defined module Test isCaseClass: true If I compile it and execute it as a standard Java app I get false as result for ClassSymbol.isCase again. What am I missing? What are the differences between the scala console environment and the java runtime environment? How can I get the correct result in a real application? A: https://issues.scala-lang.org/browse/SI-6277 val classSymbol = cm.reflect(new TestCase("foo")).symbol { classSymbol.typeSignature } val isCaseClass = classSymbol.isCaseClass println(s"isCaseClass: $isCaseClass") Edit: to answer your last question, you wouldn't be using a milestone in a real application. :) Upd. Fixed since Scala 2.10.0-RC1.
[ "stackoverflow", "0040622232.txt" ]
Q: GHC claims module only available as a boot module when it shouldn't be I have this dependency graph (ignoring dependencies on third-party modules): Main: GSI.Util GSI.Value GSI.Result GSI.Eval GSI.ByteCode GSI.Thread GSI.Main: GSI.Value GSI.ByteCode GSI.Thread: GSI.Util GSI.RTS GSI.Value GSI.Result GSI.Eval GSI.Eval: GSI.Util GSI.RTS GSI.Value GSI.Result ACE GSI.Eval (.hs-boot): GSI.Value ACE: GSI.RTS GSI.Value GSI.ByteCode GSI.Result {-# SOURCE #-} GSI.Eval GSI.ByteCode: GSI.Util GSI.Value {-# SOURCE #-} GSI.Thread GSI.ByteCode (.hs-boot): {-# SOURCE #-} GSI.Value {-# SOURCE #-} GSI.Thread GSI.Result: GSI.Util GSI.RTS GSI.Value GSI.Value: GSI.Util GSI.RTS {-# SOURCE #-} GSI.ByteCode (I'd like to cut that graph down further, but I honestly am lost as to which pieces are relevant. .hs-boot files not listed have no dependencies on my code). When I do ghc --make Main.hs I get this message: [10 of 13] Compiling ACE ( ACE.hs, ACE.o ) [GSI.ByteCode changed] module GSI.Thread cannot be linked; it is only available as a boot module What on earth? I'm importing GSI.Thread not as a boot module from Main, so how can GHC claim it's only available as a boot module? (And, for that matter, why can't GHC just detect this situation and include the non-boot module automatically?) A: The actual problem was that ACE and GSI.Value had a circular dependency: ACE -> GSI.Value -> GSI.Thread -> GSI.Eval -> ACE This is an irresolvable problem because ACE uses a function from GSI.Value in a Template Haskell splice. That requires GHC to dynamically load GSI.Value in order to compile ACE; but that is clearly impossible. The solution was to move the Thread type out of GSI.Thread, and to a separate module that could avoid any dependency on GSI.Eval or GSI.Value.
[ "stackoverflow", "0001375531.txt" ]
Q: Breaking up a Rails app into two We have a very lage Rails app that has two distinct sections: the front end and the CMS/Admin. We would like to break up the app into two pieces (for maintenance, as we have distinct teams that work on the front end vs. back end and they could have different release cycles). One thought was to start a new Admin 2.0 app that has access to the models/schema from the original application, but has its own controllers/views and its own models that extend the original models until it is safe to fully decouple. Is this advisable? If not, what would be an appropriate plan to migrate away from one monolithic codebase? A: warning, this is a bit ranty, and does not go anywhere. Having worked on a very large app that operates in the manor you describe (for scalability reasons), I still have mixed opinions (an no conclusive answers). Currently we operate 3 major apps (+ one or two smaller ones that use a fragment of the schema). RVW (our admin app): This is the only app that writes, runs on a single server, and is responsible for maintaining the schema. reevoo.com: ecommerce, price comparison, stuff like that. This (for historic reasons runs on a slightly different schema, run on a read only slave of RVW, with database views to map the schemas. All writes are done by sticking things on queues that RVW picks up and acts on. This works very well, although the number of random db related issues (mostly related to the views) is an issue. The main problem with this app is the difficulty sharing code (gems work well, I've often dreamed of bringing the schemas into line and sharing the core models in a gem!). We share code between apps using ruby gems. And test using lots of integration tests that cross app boundaries (using drunit (presentation on this available)). reevoomark: very high load b2b app. This has many servers each with a full stack (db server, app server one per node). These have their databases populated with a db export - import batch job. This works very well in the short term, the shear flexibility of it is just ace, but integration testing between apps is very hard. My advice would be to avoid splitting the apps at all costs, keeping things DRY quickly becomes a major challenge. My advice would be to stick with one app, two sets of routes (selected at startup by environment variables). This gives you all the advantages of the other solutions, while making code sharing implicit. Splitting your test packs out would make your test cycles shorter and make things more manageable for the two teams. I would avoid working on different code bases, as doing this promotes the apps drifting apart and making code sharing tricky (as in .com). If you decide do split, have a good set of high level cross app tests. Custom (per app) extensions to a core set of models sounds like a good plan, although with distinct code bases and teams you may still end up with duplicate code. Rails engines should be a good way of sharing the models, but be prepared for model reloading to become a little schizophrenic. Good luck!
[ "stackoverflow", "0060544369.txt" ]
Q: How to convert rpivotTable result in to dataframe How to convert rpivotTable result in to dataframe. I want to create new datafrmae with the result of rpivotTable, Is it possible do in R? Data Set Like User Order_Bin a PPL b CCD c CCD d OLP a OLP c PPL b OLP a PPL a OLP b PPL c CCD d CCD d OLP c OLP b OLP b CCD How to get result of below code as data.frame library(rpivotTable) rpivotTable( inventory, aggregatorName = "Count", cols = "Order_Bin", rows = "User", rendererName = "Heatmap", width = "100%", height = "1000px") A: According to the documention of rpivotTable, there is no export facility. So, you have to aggregate on your own. One possibility is reshape2::dcast(inventory, User ~ Order_Bin, length, margins = TRUE) which returns User CCD OLP PPL (all) 1 a 0 2 2 4 2 b 2 2 1 5 3 c 2 1 1 4 4 d 1 2 0 3 5 (all) 5 7 4 16 For comparison, here is the output of the pivotTable() call: Please, note the Totals row and column.
[ "stackoverflow", "0059130470.txt" ]
Q: How to trigger search button to go to a web page from user inputs? I am making my first search bar/engine. I want to make the search bar respond to user inputs so that it could send them to a specific website. The issue I have is that my search button is not sending the user to a webpage when the user inputs certain keywords from texts inside <li><a> </a></li> into the <input></input> and presses the search button. How do I fix this? Edit: Website: http://techteach.us/Web2020/ZWeiJian/WCP/Labs/Lab_01/Lab_1.html //Search engine functionality var sForm = document.getElementById("srchFrm"); document.addEventListener("click", function(event) { var clickedInside = sForm.contains(event.target); if (clickedInside) { //Displaying the search suggestions document.getElementById("srchRslts").style.display = "block"; } else { //Hiding the search suggestions document.getElementById("srchRslts").style.display = "none"; } }); //Credit to W3Schools function searchingResults() { // Declaring variables let input, filter, ul, li, a, i, txtValue; input = document.getElementById('srchBar'); filter = input.value; ul = document.getElementById("srchRslts"); li = ul.getElementsByTagName('li'); // Loop through all list items, and hide those who don't match the search query for (i = 0; i < li.length; i++) { a = li[i].getElementsByTagName("a")[0]; txtValue = a.textContent || a.innerText; if (txtValue.indexOf(filter) > -1) { li[i].style.display = ""; } else { li[i].style.display = "none"; } } //Credit to Textfixer.com and https://stackoverflow.com/questions/155188/trigger-a-button-click-with-javascript-on-the-enter-key-in-a-text-box for the search button code. //Get the Search Button var submitButton = document.getElementById("sbmtBtn"); //Add event listener to the submit button input.addEventListener("keyup", function(e) { e.preventDefault(); //Press enter to activate the search engine if (event.keyCode === 13) { submitButton.click(); } }); function cSbmtBtn() { a = li[i].getElementsByTagName("a")[0]; txtValue = a.textContent || a.innerText; if (filter == txtValue) { submitButton.value = txtValue; } } } <!--Basic Search Bar.--> <form id="srchFrm"> <input id="srchBar" type="text" onKeyUp="searchingResults();" placeholder="Search..."> <button type="submit" id="sbmtBtn" value="" onClick="cSbmtBtn"><i class="fa fa-search"></i></button> <ul id="srchRslts"> <li><a href="Lab_1.html">Home</a></li> <li><a href="Lb1Labs.html">Labs</a></li> <li><a href="Lb1Projects.html">Projects</a></li> <li><a href="https://qwfepfp.blogspot.com/2019/09/blog-intromy-bio-2.html">Blogger</a></li> <li><a href="http://techteach.us/index.html">Techteach.us</a></li> <li><a href="http://techteach.us/Web2020/">Parent Directory</a></li> <li><a href="http://techteach.us/index.html">Mrs. Ramirez's Site</a></li> <li><a href="https://www.infotechhs.net/">Information Technology High School Website</a></li> <li><a href="Lab_1Redirectory.html">Lab 1</a></li> <li><a href="../Lab_02/Lab_2.html">Lab 2</a></li> <li><a href="../Lab_03/Lab_3.html">Lab 3</a></li> <li><a href="../Lab_04/Lab_4.html">Lab 4</a></li> <li><a href="../Lab_05/Lab_5.html">Lab 5</a></li> <li><a href="../Lab_06/Lab_6.html">Lab 6</a></li> <li><a href="Lb1ErrorPage.html">Lab 7</a></li> <li><a href="Lb1ErrorPage.html">Lab 8</a></li> <li><a href="Lb1ErrorPage.html">Lab 9</a></li> <li><a href="Lb1ErrorPage.html">Lab 10</a></li> <li><a href="Lb1ErrorPage.html">Lab 11</a></li> <li><a href="Lb1ErrorPage.html">Lab 12</a></li> <li><a href="Lb1ErrorPage.html">Lab 13</a></li> <li><a href="Lb1ErrorPage.html">Lab 14</a></li> <li><a href="Lb1ErrorPage.html">Lab 15</a></li> <li><a href="Lb1ErrorPage.html">Lab 16</a></li> <li><a href="Lb1ErrorPage.html">Lab 17</a></li> <li><a href="Lb1ErrorPage.html">Lab 18</a></li> <li><a href="Lb1ErrorPage.html">Lab 19</a></li> <li><a href="Lb1ErrorPage.html">Lab 20</a></li> <li><a href="../../Projects/Pr1/index.html">Project 1</a></li> <li><a href="../../Projects/ECONO/ECONO.html">Project 2</a></li> <li><a href="Lb1ErrorPage.html">Project 3</a></li> <li><a href="Lb1ErrorPage.html">Project 4</a></li> <li><a href="Lb1About.html">About</a></li> <li><a href="Lb1PD.html">Privacy & Disclaimer</a></li> <li><a href="Lb1TS.html">Terms of Service</a></li> <li><a href="Lb1Citations.html">Citation</a></li> </ul> </form> A: html <form id="srchFrm"> <input id="srchBar" type="text" placeholder="Search..."> <button type="submit" id="sbmtBtn" value="">Search</button> <!-- Rest of form --> </form> script.js // Search engine functionality var sForm = document.getElementById("srchFrm"); var input = document.getElementById('srchBar'); var anchors = document.querySelectorAll("form ul li a"); var anchorTexts = anchors.map (anchor => anchor.textContent); var matchedAnchors = []; // Document click listener to detect clicks inside sForm document.addEventListener("click", function(event) { // Document click handler logic }); // Submit handler to prevent default form submission. // Form submission is also triggered when the submit button is clicked // So the logic of the submit button can be moved here sForm.addEventListener("submit", function(event) { event.preventDefault(); // Necessary to prevent form submission which will redirect the page to the URL in the `action` attribute of the form // Form submission logic goes here // There can be multiple anchors matching the text, so I'll assume you want the first match if (matchedAnchors.length === 0) return; // Change the window location to the href of the first matched anchor window.location.href = matchedAnchors[0].getAttribute("href") }); // Input key up handler. Logic for what happens on key up goes here input.addEventListener("keyup", function(event) { var inputValue = event.target.value; // or input.value matchedAnchors.splice(0); // Clear the matchedAnchors array before starting a new search // Make all anchors visible before starting a new search for (const anchor of anchors) anchor.style.display = "inline-block" // Find anchors that match the input for (const i = 0; i < anchorTexts.length; i++) { const anchorText = anchorTexts[i]; if (anchorText.startsWith(inputValue)) { // Or 'indexOf' if you want a partial match starting from anywhere in the string matchedAnchors.push (anchors[i]); } } // Find anchors that match the input for (const anchor of anchors) { if (matchedAnchors.includes(anchor)) { anchor.style.display = "inline-block"; } else anchor.style.display = "none"; } }) Something of this sort should help you out...
[ "stackoverflow", "0004578575.txt" ]
Q: I want to design a web page containing multiple output areas which will hold data generated from a JDBC Resultset I want to design a web page containing multiple output areas which will hold data generated from a JDBC Resultset I am a JAVA newbie with over 20 years of software development experience in the mainframe world. I do a ton of ISPF development. now, what I am looking for is a list of tools necessary to create my webpage and display JDBC output in multiple frames. I currently use eclipse as my IDE for JAVA. I wrote a piece of JAVA code a few years ago that I use to get the Resultsets and display the data in the console. Now I want to move into the 19th Century and display my data in a web page. I am really unsure as where to start. Tutorials, Books, etc. any guidance would be greatly appreciated. thanks RSJRNY A: A ResultSet should never get within 100 yards of a user interface. Here's the way your layered application ought to look: HTML page in browser ----> servlet listening for HTTP requests ----> interface to database "interface" in this case ought to be taken literally: it's a POJO interface for CRUD operations. Don't return a ResultSet; map the results of a query into a data structure or object and close the ResultSet in method scope. It's a scarce resource; you shouldn't be passing that out of the persistence layer. Once the servlet gets the object or collection back from the database, it's free to add it to the response so the user interface can get at it. I'm assuming that your HTML page is generated dynamically using a templating technology like JSP or Velocity. They'll make it easy to add the object or collection from the database into the page. It's not "easy", but I think this is the right way to do it without framework fuss.
[ "stackoverflow", "0015488714.txt" ]
Q: How to create drop shadow for Rectangle on QtQuick 2.0 How can i draw a drop shadow for a Rectangle visual item on QtQuick 2.0? I like to draw a drop shadow for my main window (I have a transparent and no-decorated window) A: As a workaround for the clipped shadow issue, you can put your Rectangle in an Item, with additionnal margin to take blur radius in account, and apply shadow on that container: import QtQuick 2.0 import QtGraphicalEffects 1.0 Item { width: 320 height: 240 Item { id: container anchors.centerIn: parent width: rect.width + (2 * rectShadow.radius) height: rect.height + (2 * rectShadow.radius) visible: false Rectangle { id: rect width: 100 height: 50 color: "orange" radius: 7 antialiasing: true border { width: 2 color: "red" } anchors.centerIn: parent } } DropShadow { id: rectShadow anchors.fill: source cached: true horizontalOffset: 3 verticalOffset: 3 radius: 8.0 samples: 16 color: "#80000000" smooth: true source: container } } A: Just use DropShadow from the QtGraphicalEffects module. A complete, working example: import QtQuick 2.0 import QtGraphicalEffects 1.0 Rectangle { width: 640 height: 480 color: "blue" Rectangle { id: rect anchors.centerIn: parent width: 100 height: 100 color: "red" } DropShadow { anchors.fill: rect cached: true horizontalOffset: 3 verticalOffset: 3 radius: 8.0 samples: 16 color: "#80000000" source: rect } } Note that you will see a number of warnings like this: file:///opt/Qt5.0.1/5.0.1/gcc_64/qml/QtGraphicalEffects/DropShadow.qml:391:5: QML SourceProxy: Binding loop detected for property "output" file:///opt/Qt5.0.1/5.0.1/gcc_64/qml/QtGraphicalEffects/private/GaussianDirectionalBlur.qml:66:5: QML SourceProxy: Binding loop detected for property "output" file:///opt/Qt5.0.1/5.0.1/gcc_64/qml/QtGraphicalEffects/private/GaussianDirectionalBlur.qml:61:5: QML SourceProxy: Binding loop detected for property "output" file:///opt/Qt5.0.1/5.0.1/gcc_64/qml/QtGraphicalEffects/private/GaussianDirectionalBlur.qml:66:5: QML SourceProxy: Binding loop detected for property "output" file:///opt/Qt5.0.1/5.0.1/gcc_64/qml/QtGraphicalEffects/private/GaussianDirectionalBlur.qml:61:5: QML SourceProxy: Binding loop detected for property "output" file:///opt/Qt5.0.1/5.0.1/gcc_64/qml/QtGraphicalEffects/private/GaussianGlow.qml:53:5: QML SourceProxy: Binding loop detected for property "output" Those warnings are QTBUG-28521, which has been fixed in Qt 5.0.2 (which at the time of this writing has not yet been released). Fortunately, there's no actual problem, aside from the annoying console output. A: Interesting question... I've been searching for a better way to do this. This is my quick and dirty way of accomplishing a drop shadow effect for a QML Rectangle for the time being. Rectangle{ width: 500 height: 500 color: "dark grey" Rectangle { id: backgroundRect width: 200 height: 150 radius: 5 anchors.centerIn: parent color: "red" Rectangle { id: dropShadowRect property real offset: Math.min(parent.width*0.025, parent.height*0.025) color: "purple" width: parent.width height: parent.height z: -1 opacity: 0.75 radius: backgroundRect.radius + 2 anchors.left: parent.left anchors.leftMargin: -offset anchors.top: parent.top anchors.topMargin: offset } } }
[ "math.stackexchange", "0003384613.txt" ]
Q: Show that the function $g: \mathbb{R}^{2} → \mathbb{R}$ defined by $g (x, y) = f (αx + βy)$ is uniformly continuous in $\mathbb{R}^2$ Let $\alpha, \beta \in \mathbb{R}$ and $f: \mathbb{R} → \mathbb{R}$ be uniformly continuous. Show that the function $g: \mathbb{R}^{2} → \mathbb{R}$ defined by $g (x, y) = f (αx + βy)$ is uniformly continuous in $\mathbb{R}^2$ I made a demonstration by absurdity, but I don't know if it is easier to demonstrate this directly using only the definition of uniform continuity. A: Let $\varepsilon>0$. Then, according to the assumptions of the question, there exists a $\delta>0$, such that $$ |x-y|<\delta\quad\Longrightarrow\quad |f(x)-f(y)|<\varepsilon $$ Now suppose that $$ |(x_1,x_2)-(y_1,y_2)|=\big((x_1-y_1)^2+(x_2-y_2)^2\big)^{½}<\delta' $$ then $$ |(ax_1+bx_2)-(ay_1+by_2)|= |a(x_1-y_1)+b(x_2-y_2)|\le (a^2+b^2)^{1/2}\big((x_1-y_1)^2+(x_2-y_2)^2\big)^{½}<(a^2+b^2)^{1/2}\delta' $$ Hence, $$ |(x_1,x_2)-(y_1,y_2)|<\frac{\delta}{(a^2+b^2)^{1/2}} \quad\Longrightarrow\quad |(ax_1+bx_2)-(ay_1+by_2)|<\delta \\ \quad\Longrightarrow\quad |f(ax_1+bx_2)-f(ay_1+by_2)|<\varepsilon. $$ Note. We have assumed that $a^2+b^2\ne 0$. If this is not given, then we could define $$ \delta'=\frac{\delta}{(a^2+b^2)^{1/2}+1} $$ to avoid vanishing denominators.
[ "3dprinting.stackexchange", "0000006495.txt" ]
Q: Anet A6 Z-axis min endstop not triggering I had a Z probe installed but the wires came out of the header so I am trying to use software endstops, but any time I G28 the nozzle will always ram into the bed. I am using Marlin Firmware. Which I am relatively new with. I'm used to having hardware endstops, but, I don't have a hardware endstop currently (no probe/no switch). Is it possible to do this with software? I took out G28/G29 in my G-code and it shows that it is going to z0.2 and working upward (but it still hits the bed). If the bed is level do I need a G28? Should Z probe offset be 0? #define USE_XMIN_PLUG #define USE_YMIN_PLUG #define USE_ZMIN_PLUG //#define USE_XMAX_PLUG //#define USE_YMAX_PLUG //#define USE_ZMAX_PLUG #if DISABLED(ENDSTOPPULLUPS) // fine endstop settings: Individual pullups. will be ignored if ENDSTOPPULLUPS is defined //#define ENDSTOPPULLUP_XMAX //#define ENDSTOPPULLUP_YMAX //#define ENDSTOPPULLUP_ZMAX //#define ENDSTOPPULLUP_XMIN //#define ENDSTOPPULLUP_YMIN //#define ENDSTOPPULLUP_ZMIN //#define ENDSTOPPULLUP_ZMIN_PROBE #endif #define X_MIN_ENDSTOP_INVERTING true // set to true to invert the logic of the endstop. #define Y_MIN_ENDSTOP_INVERTING true // set to true to invert the logic of the endstop. #define Z_MIN_ENDSTOP_INVERTING true // set to true to invert the logic of the endstop. #define X_MAX_ENDSTOP_INVERTING false // set to true to invert the logic of the endstop. #define Y_MAX_ENDSTOP_INVERTING false // set to true to invert the logic of the endstop. #define Z_MAX_ENDSTOP_INVERTING false // set to true to invert the logic of the endstop. #define Z_MIN_PROBE_ENDSTOP_INVERTING true // set to true to invert the logic of the probe. // Enable this feature if all enabled endstop pins are interrupt-capable. // This will remove the need to poll the interrupt pins, saving many CPU cycles. #define ENDSTOP_INTERRUPTS_FEATURE #define PROBE_MANUALLY #define X_PROBE_OFFSET_FROM_EXTRUDER 1 // X offset: -left +right [of the nozzle] #define Y_PROBE_OFFSET_FROM_EXTRUDER -55 // Y offset: -front +behind [the nozzle] #define Z_PROBE_OFFSET_FROM_EXTRUDER -3.4 #define MULTIPLE_PROBING 2 #define Z_CLEARANCE_DEPLOY_PROBE 0 // Z Clearance for Deploy/Stow #define Z_CLEARANCE_BETWEEN_PROBES 3 // Z Clearance between probe points // For M851 give a range for adjusting the Z probe offset #define Z_PROBE_OFFSET_RANGE_MIN -20 #define Z_PROBE_OFFSET_RANGE_MAX 20 #define INVERT_Z_DIR true #define Z_MIN_POS 0 #if ENABLED(MIN_SOFTWARE_ENDSTOPS) //#define MIN_SOFTWARE_ENDSTOP_X //#define MIN_SOFTWARE_ENDSTOP_Y #define MIN_SOFTWARE_ENDSTOP_Z #endif #define AUTO_BED_LEVELING_BILINEAR #define MANUAL_Z_HOME_POS 0 #define Z_SAFE_HOMING #if ENABLED(Z_SAFE_HOMING) #define Z_SAFE_HOMING_X_POINT ((X_BED_SIZE) / 2) // X point for Z homing when homing all axes (G28). #define Z_SAFE_HOMING_Y_POINT ((Y_BED_SIZE) / 2) // Y point for Z homing when homing all axes (G28). #endif A: There is no such thing as a software endstop for the 3D printer. When you power a printer the print head can be located at every X, Y, Z position (usually, Z is at the print height of your last print, X is at the minimum X, and Y is at an arbitrary location determined by the last print). This is exactly why we need endstops, either mechanical, optical or electronic (inductive or capacitive) end stop switches or sensors. You instruct the printer to home by using a known fixed location of the printer; this is the hitting of all endstops. The origin of the printer may have offsets, as the origin of the printer may not coincide with the endstop location. For the Anet A6 this is a few millimeters, e.g. for Marlin firmware this is defined in the configuration by: #define X_MIN_POS -3 #define Y_MIN_POS -5 The answer to your question: "Is it possible to do this with software?" is therefore, no, you cannot do this solely with software.
[ "stackoverflow", "0029596163.txt" ]
Q: Should the Reverse DNS for an EC2 point to the Public DNS or the domain name? In trying to set up a mail server (for fun!), I requested a Reverse DNS from Amazon, specifying my Elastic IP and my mail server subdomain (e.g. mail.mydomain.com). A Reverse DNS Lookup now returns my EC2 Public DNS. e.g. $ dig -x 5.4.3.2 +short ec2-5-4-3-2.us-west-2.compute.amazonaws.com. I expected that the reverse lookup would instead point to my domain name ('mail.mydomain.com'). 1) Is my expectation wrong? Should a Reverse Lookup point the EC2 public DNS or to the requested domain name? 2) Is the dig result because I missed something? Such as additionally making a PTR record in Route53 and/or configuring something in apache (such as a proxy or alias)? System: I have a t2-micro (using an EIP and Route53) running ubuntu 14.04 and apache2 with a few sites. And I'm following this mail server tutorial. Thanks! There's a lot to this mail server stuff! A: The Reverse DNS for an EC2 will point to the public DNS. $ dig -x 5.4.3.2 +short would return ec2-5-4-3-2.us-west-2.compute.amazonaws.com. and not mail.mydomain.com
[ "stackoverflow", "0020706331.txt" ]
Q: Referential integrity constraint violation occurred I am getting the following error when calling context.Set<Person>().Attach(person); on EF 5.0 A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship. Is there some way to figure out which exact property is generating this error? I know what the cause is, that a foreign key which is directly a property of an object is different from the related object's primary key, so for example: Person --> Address ID PersonID Person and Address.PersonID isn't the same as Address.Person.PersonID, but no matter where I look at my real life object I am not getting which property is causing this. So is there some way to get to the root of the problem, maybe stepping through the ObjectStateManager or some ChangeTracking routine? I have already written a t4 template file (to autogenerate it based on my entitymodel) that checks every ForeignKey/PrimaryKey, and I just cannot find a difference. A: Multi ForeignKey ruined my day... So to complete my sample above it was like; Person --> Address ID PersonID ID2 PersonID2 Person And I didnt check the ID2 of my objects, which was loaded incorrectly.
[ "math.stackexchange", "0003692192.txt" ]
Q: Optics problem: Simplifying the expression $ {r_v ^2 + r^2-2rr_v\cos\delta} \over {1+(rr_v)^2-2rr_v \cos \delta} $ I was doing an optics problem and I ended up with the following expression for a reflexion factor: $$ {r_v ^2 + r^2-2rr_v\cos\delta} \over {1+(rr_v)^2-2rr_v \cos \delta} $$ Now, I could just plug my numbers here, but I couldn't help noticing that the numerator is the opposite side of a triangle with sides $r_v$ and $r$, and an angle $\delta$ between them. Similarly, the denominator is the opposite side of a triangle with sides $1$ and $ { r r_v} $, and an equal angle $\delta$ between them. Taking into account that $1>r>r_v$, I made the following drawing: This is a really nice geometrical interpretation of the above formula, which makes me suspect that there is a way to simplify it. However I haven't been able to. Completing squares and using $1-\cos\delta=2\sin^2\delta/2$ yields the following: $$ {(r_v-r)^2+4rr_v\sin^2\delta/2} \over {(rr_v-1)^2+4rr_v\sin^2\delta/2} $$ ...which isn't really that simplified. Is there something else I can do? A: For example: $$\begin{cases} r_v^2+r^2-2rr_v\cos\delta=(r-r_v\cos\delta)^2+r_v^2\sin^2\delta=\left|r-r_v\,e^{\pm i\delta}\right|^2\\{}\\ 1+(rr_v)^2-2rr_v\cos\delta=(rr_v-\cos\delta)^2+\sin^2\delta=\left|rr_v-e^{\pm i\delta}\right|^2\end{cases}\;\;\;\;,\,\delta\in\Bbb R$$ So your expression is, using complex numbers, simple the fractions formed with the above, namely $$\frac{\left|r-r_v\,e^{\pm i\delta}\right|^2}{\left|rr_v-e^{\pm i\delta}\right|^2}=\left|\frac{r-r_v\,e^{\pm i\delta}}{rr_v-e^{\pm i\delta}}\right|^2$$ I don't know if the above simplifies your expression the way you want, but it is at least a shorter one...BTW, as $\;\delta\;$ is a geometrical angle, we can assume it is a positive one (I suppose), so the above can be put a little more succintly as $$\frac{\left|r-r_v\,e^{i\delta}\right|^2}{\left|rr_v-e^{i\delta}\right|^2}=\left|\frac{r-r_v\,e^{i\delta}}{rr_v-e^{i\delta}}\right|^2$$
[ "stackoverflow", "0062589511.txt" ]
Q: How to change enable/disable a and an when a is checked or not, using primefaces? I have this part of code: <!-- /row --> <div class="row" style="margin-top: 15px"> <div class="span8"> <div class="control-group"> <label class="hcg-control-label span5">Ημερομηνία Ανάκλησης Ποινής</label> <div class="controls span7"> <p:calendar id="recallDate" styleClass="hcg-full-width cursor-pointer" pattern="dd/MM/yyyy" value="#{penaltiesView.penalty.recallDate}" disabled="true"/> <i class="fa fa-calendar hcg-input-icon"></i> </div> </div> </div> <!-- /span --> </div> <!-- /row --> <div class="row" style="margin-top: 15px"> <div class="span8"> <div class="control-group"> <label class="hcg-control-label span5">Σχόλια Ανάκλησης Ποινής</label> <div class="controls span7"> <p:inputTextarea rows="6" id="recallComments" styleClass="hcg-full-width" value="#{penaltiesView.penalty.recallComments}" disabled="true"/> </div> </div> </div> <!-- /span --> </div> <!-- /row --> <div class="row"> <div class="span8"> <div class="control-group"> <label class="hcg-control-label span5">Ανάκληση - Ολοκλήρωση Πειθαρχικής Ποινής</label> <div class="controls span7"> <p:selectBooleanCheckbox id="RevocationOrCompletion" styleClass="hcg-checkbox margin-bottom-10" value="#{penaltiesView.penalty.revocationOrCompletion}" disabled="#{!penaltiesView.canEdit()}" > <p:ajax event="change" update="recallDate,recallComments"/> </p:selectBooleanCheckbox> </div> </div> </div> <!-- /span --> </div> which produces the following components: Now, what I want to do, is to make the calendar component and the Textarea to get enabled when I check the checkBox and if I uncheck it, they must be disabled again. The use of javascript due to requirements is not a valid way. I am having some difficulties on how to make this happen. Any suggestions are appreciated. Thank you in advance. A: Your elements can't be updated because you have in your code disabled=true for calendar and textArea. If you want to change disable parameter depending on boolean checkbox than disabled value needs to be a value of boolean checkbox. Your boolean field also needs to have geters and setters. <p:calendar id="recallDate" styleClass="hcg-full-width cursor-pointer" pattern="dd/MM/yyyy" value="#{penaltiesView.penalty.recallDate}" disabled="#{penaltiesView.penalty.revocationOrCompletion}"/> <p:inputTextarea rows="6" id="recallComments" styleClass="hcg-full-width" value="#{penaltiesView.penalty.recallComments}" disabled="#{penaltiesView.penalty.revocationOrCompletion}"/> <p:selectBooleanCheckbox id="RevocationOrCompletion" styleClass="hcg-checkbox margin-bottom-10" value="#{penaltiesView.penalty.revocationOrCompletion}" disabled="#{!penaltiesView.canEdit()}" > <p:ajax update="recallDate recallComments" process="@this"/> </p:selectBooleanCheckbox>
[ "apple.stackexchange", "0000113977.txt" ]
Q: Can I download 3rd party songs on the iPad and add them to iTunes Match? I wonder if i can buy and download songs e.g. via Bandcamp in Safari, and then add them to my iTunes match right on my iPad? I know how to do that with iTunes on the Mac, but it would be neat to have this also on the iPad. A: Nope. You won't be able to add the in iTunes and thus you won't be able to add them to iTunes match.
[ "bicycles.stackexchange", "0000012948.txt" ]
Q: What are the alternatives to SwissStop Blue v-brake pads We've got a tandem with Rigida Andara CSS tungsten carbide rims and Swisstop Blue v-brake pads. We're happy with the performance and life of both of these over the last 1000 miles. The problem is that only Swisstop Blue blocks are recommended. I've been led to believe that other blocks will wear out too quickly on tungsten carbide rims, possibly leaving a rubbery deposit on the rims. I'd like to know of more than one manufacturer or supplier (preferably in the UK) who can provide suitable replacement v-brake block cartridges, so that I have options if the Swisstop ones are unavailable or become expensive. I don't like being tied to a single brand for what should hopefully be quite long-lived rims. Are there any reasonable alternatives? A: Kool stop R9 Magura HS33 Pads are made to work with Rigida CSS rims. Also V-Brake inserts by kool stop for Rigida CSS rims.
[ "stackoverflow", "0015248635.txt" ]
Q: How to change file extension when saving selected file in a FileUpload to the server string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName); FileUpload1.PostedFile.SaveAs(Server.MapPath("~/ProcessedFiles/" + fileName)); The file am grabbing from FileUpload1 to save on the server is a .xls file (Excel 97-2003) What i want is to save it with a .xlsx extension (Excel 2007 and above) on the server. A: Use Path.ChangeExtension string path = "C:\\SomePath\\Somefile.xls"; string newPath = Path.ChangeExtension(path, ".xlsx"); In your case, probably something like this (not tested): string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName); fileName = Server.MapPath(Path.Combine("~/ProcessedFiles/", fileName)); FileUpload1.PostedFile.SaveAs(Path.ChangeExtension(fileName, ".xlsx"));
[ "stackoverflow", "0047256437.txt" ]
Q: Android - Receiving image from another ImageView with "startActivityonResultFor" I am trying to make it where when someone clicks on the default avatar picture it will send them to a separate activity which will contain a selection of avatars to choose from. The user will select one of these avatars and then I want to send the user back to the Main activity, with the avatar ImageView set as the one they selected. I have done this with text, but not with images, and I've reached a point of confusion. Can anyone help me make this possible? // First View public class MainActivity extends AppCompatActivity { ImageView imageViewSelectAvatarLocal; int requestCodeImageBrownHairedFemale = 100; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageViewSelectAvatarLocal = findViewById(R.id.imageViewdefaultAvatar); imageViewSelectAvatarLocal.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, SelectAvatarActivity.class); intent.putExtra("Brown Haired Woman", 001); startActivityForResult(intent, 100); } }); } @SuppressLint("ResourceType") @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == SelectAvatarActivity.RESULT_OK && data != null){ if(requestCode == requestCodeImageBrownHairedFemale) { //... } } } } // Second View public class SelectAvatarActivity extends AppCompatActivity { ImageView imageViewBrownHairedWoman @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_avatar); imageViewBrownHairedWoman = findViewById(R.id.imageViewBrownHairFemale); imageViewBrownHairedWoman.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.getExtras(); setResult(MainActivity.RESULT_OK, intent); finish(); } }); } } A: How about using array? You have some avatar images. So you can do int[] avatars = {R.drawable.avatar0, ... }; In second view, click one of avatar images(each image have position), send position to MainActivity and get value using onActivityResult method. For example, public class MainActivity extends AppCompatActivity { int[] avatars = {R.drawable.avatar0, ... }; ImageView imageViewSelectAvatarLocal; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageViewSelectAvatarLocal = findViewById(R.id.imageViewdefaultAvatar); imageViewSelectAvatarLocal.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, SelectAvatarActivity.class); startActivityForResult(intent, 100); } }); } @SuppressLint("ResourceType") @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == SelectAvatarActivity.RESULT_OK && data != null){ if(requestCode == 100) { int pos = data.getIntExtra("avatar", 0); imageViewSelectAvatarLocal.setImageResource(avatars[pos]); //... } } } } // Second View public class SelectAvatarActivity extends AppCompatActivity { ImageView avatar0, avatar1, ...; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_avatar); avatar0 = findViewById(R.id.avatar1); avatar0.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.putExtra("avatar", 0); setResult(MainActivity.RESULT_OK, intent); finish(); } }); //... } }
[ "travel.stackexchange", "0000104736.txt" ]
Q: Is my grandfather eligible for an EEA Family Permit? The Schengen visa for my grandfather was approved last week. We plan to travel to the UK during his stay in order to visit friends and family there. According to my signed German "formal obligation letter" I am fully responsible for my grandfather during his stay. Does this count as "dependancy", which is needed to get an EEA family permit? Who are an EEA National’s Family Members? > dependent direct relatives in the ascending line, for example parents and grandparents of the EEA national or their spouse / civil partner. Thank you so much for your help. Regards. A: Likely not. Different countries operate with slightly different guidelines and documentation requirements for determining dependency, but the UK authorities guidelines state that your grandfather must be 'wholly or mainly financially dependent on the EEA principal (you) to meet his or her essential needs in order to qualify'. Your obligation letter only establishes a dependency for the costs directly related to your grandfathers visit in Germany and not any permanent dependency, as rather required for a family permit.
[ "stackoverflow", "0003502481.txt" ]
Q: vim: combine :g with command which uses range I have a text which is made of lines and some of them look like that: A test1 test test test test A test2 test test test test The line starts with A (arbitrary but unique string) and ends with an empty line. I like to remove all redundant newline symbols from the real lines (without affecting other lines, not matching the /^A/) and make the lines look like that: A test1 test test test test A test2 test test test test Once I'm at /^A/, I can use the command :.,/^$/-2s/\n/ / (range .,/^$/-2 applied to :s///). Going over the whole file and doing it manually is rather mundane thus I have attempted to combine that with :g/^A/: :g/^A/.,/^$/-2s/\n/ / But that produced error since in command after :g//, the range wasn't recognized. I have tried to use normal too - :g/^A/normal .,/^$/-2s/\n/ / and :g/^A/exe 'normal .,/^$/-2s/\n/ /' - with no luck. Is there any way to run from under :g// a command with range? Or is there any other easy (== without scripting) way to accomplish the same formatting task? A: Try this. To enter the ^M, use ctrl-v enter. :g/^A/normal V/^$/^MkJ
[ "workplace.stackexchange", "0000066837.txt" ]
Q: I forked a coworkers code without asking and made it my own. Should I have asked first? I'm an electrical engineer working for a small startup. The company has its own software department (which I'm not part of). Writing software is not part of my job description. However, I do write my own unit-level tests. My codebase is separate from that of the software team one and is relatively primitive. A coworker in software who is a veteran developer wrote a very useful utility which we both use for debugging any issues. Without talking to him about it, I forked it to my repository (with full version control). I have made significant changes to this code over time. I changed and added some functionality but also changed the code to make it suit my coding style. The majority of the changes I made were purely to allow me to better understand the functionality and extend it. I would like to share this code with my coworker who wrote the initial version so he can use it, however I'm not sure how I should go about it. I don't intend to merge my code with his, just tell him that my fork exists. I wonder if I should have asked first. He is a veteran in the industry (and about 20 years older than me) and I don't want to come across as disrespectful because I changed his code so significantly without asking. Should I have asked first? A: If there is a reason for sharing it, then I see no reason not to. Unless he is a very uptight sort of person he knows code evolves to meet needs and shouldn't be insulted. A: Just nicely ask him in the following way: "I added some features for myself, and I wonder if it makes sense to merge them with your version. I want to avoid keeping my own duplicate version of the code around forever, and I also have doubts about my code at some points; maybe we can discuss how difficult it would be to merge these features". I am a senior developer, and usually I would decide if it makes sense to do a reintegration of the features, as a merge or as a rewrite. But if somebody shows me working code extending mine with a functionality he needs, I usually listen to him/her (as long as he does not insist on literally copying his code). A: If he is a decent person, that veteran will look at it as what it is: An attempt by an amateur (and amateur is meant in the best possible way) to improve his understanding of an interesting and complex subject. You are not changing his code. You copied his code and modified your own copy. That would be absolutely fine with me, and no reasonable person should have a problem with that. If you are lucky he will look at it, give you a critique, and help you improving your skills. Modifying his code on the other hand would get someone very, very annoyed. And you wouldn't have to tell them, they would know.
[ "cooking.stackexchange", "0000083005.txt" ]
Q: Will a metal dough scraper damage a granite countertop? I have a brand new granite countertop, and a lovely metal dough scraper that a friend gave me. Am I likely to damage the counter if I use the scraper regularly directly on the granite surface? I have kneaded dough twice on it, and very tentatively used the metal scraper with no ill-effect. I don't want to try again and scrape more strongly only to find out that actually the two are not a good combination. A: Don't worry, it won't scratch. You can look at where both objects are on Mohs scale of mineral hardness. From the Strength and Hardness Ratings of Granite and Marble: Granite has a Mohs hardness rating of seven. From Mohs Hardness Test: The steel blade of the average knife usually has a hardness of about 5.5. (I assume the scraper and a knife have equal hardness). A: Granite is extremely tough, using a scraper on it won't damage it provided you use it properly. If you repeatedly brought the corner of the blade of the scraper down on it then it might conceivably chip but that would take a great deal of energy. I've had granite for years and use scrapers often with no issues.
[ "stackoverflow", "0006245102.txt" ]
Q: Optional AND in WHERE statement MySQL I'm trying to figure out how to allow optional AND statements where there is a LEFT OUTER JOIN since the table is optional when viewing records. However, I have a problem where there is no files, and in the WHERE statement, like this: SELECT rec.record_id, rec.record_name, f.file_name, f.file_id FROM ( records rec LEFT OUTER JOIN files f ON f.record_id = rec.record_id ) WHERE rec.record_id = 4928 AND f.file_approved = 1 <-- this is what returns a zero results When I remove AND f.file_approved = 1 it returns a record, but when I leave it, it returns no record. If a record contains no file records, it will not return anything. I need it to check it and if there are no files, it should still be able to return the record (without the files). A: try moving the condition into the join statement, that way it will only join on the lines if they meet the condition SELECT rec.record_id, rec.record_name, f.file_name, f.file_id FROM ( records rec LEFT OUTER JOIN files f ON f.record_id = rec.record_id AND f.file_approved = 1 ) WHERE rec.record_id = 4928;
[ "stackoverflow", "0023944770.txt" ]
Q: uWSGI can not load libssl.1.0.0.dylib When I call uwsgi, it always shows the following: dyld: Library not loaded: libssl.1.0.0.dylib Referenced from: /Users/xingshi/anaconda/bin/uwsgi Reason: image not found Trace/BPT trap: 5 Here is all the libssl.1.0.0.dylib on my Mac: $ locate libssl.1.0.0.dylib /Library/PostgreSQL/9.2/lib/libssl.1.0.0.dylib /Library/PostgreSQL/9.2/pgAdmin3.app/Contents/Frameworks/libssl.1.0.0.dylib /Users/xingshi/anaconda/lib/libssl.1.0.0.dylib /Users/xingshi/anaconda/pkgs/openssl-1.0.1c-0/lib/libssl.1.0.0.dylib /opt/local/lib/libssl.1.0.0.dylib And my uwsgi is in anaconda $which uwsgi /Users/xingshi/anaconda/bin/uwsgi Any ideas ? A: MacPorts usually install softwares into /opt/local/, but brew will install softwares into /usr/local/. It seems that my uwsgi is looking for the libssl.1.0.0.dylib in /usr/local/lib, so I use brew to install openssl and relink it: brew install --upgrade openssl brew unlink openssl && brew link openssl --force A: I performed this: I have been having this error for a long time and performing brew uninstall openssl brew install openssl did not work for me even including "--force" However, I found this link to this blog and it did work for me. http://mithun.co/hacks/library-not-loaded-libcrypto-1-0-0-dylib-issue-in-mac/ Step 1: Install openssl using brew brew install openssl Step 2: Copy copy libssl.1.0.0.dylib and libcrypto.1.0.0.dylib cd /usr/local/Cellar/openssl/1.0.1f/lib sudo cp libssl.1.0.0.dylib libcrypto.1.0.0.dylib /usr/lib/ Note the bold folder name. There will be change in that depending on your openssl version Step 3: Remove the existing links sudo rm libssl.dylib libcrypto.dylib sudo ln -s libssl.1.0.0.dylib libssl.dylib sudo ln -s libcrypto.1.0.0.dylib libcrypto.dylib I hope this helps!
[ "stackoverflow", "0049154145.txt" ]
Q: Center div inside parent bootstrap row Within the following example https://codepen.io/centem/pen/GQVGmw I'm trying to center the divs that have numbers inside them with a .centered class but it does not center. How do I center these so they sit in the middle of the row instead of to the left? CSS: .centered { margin: 0 auto; } DIVs: <div class="row"> <div id="83" class="square centerd">83</div> <div id="84" class="square centered">84</div> <div id="85" class="square centered">85</div> </div> A: Simple: <div class="row justify-content-center"> <div id="83" class="square centerd">83</div> <div id="84" class="square centered">84</div> <div id="85" class="square centered">85</div> </div>
[ "stackoverflow", "0051082276.txt" ]
Q: How to execute RFC function on explicit destination using JCo? I would like to execute RFC function on explicit destination using JCo. I've modified existing JCo StepByStepClient.java and I'm able to execute RFC function exactly the same way like using Sap GUI "se37" when the "RFC target sys" field is empty. For my demo purposes I was invoking "TH_USER_LIST" function. Then I registered my own JCo server with Program Id "MY_PROG_ID", then added tcpip destination "MY_DEST" using "sm59" with "Registered Server Program"="MY_PROG_ID". I'm now able to invoke TH_USER_LIST on my JCo server using "se37" with RFC target sys = "MY_DEST" I would like to be able to execute the same implementation of TH_USER_LIST on my JCo server using JCo client but I'm still invoking the default implementation and not mine registered program. I presumed I just need to assign the destionation as a new property like the ones bellow but it did not help connectProperties.setProperty(DestinationDataProvider.JCO_ASHOST, "appserver"); connectProperties.setProperty(DestinationDataProvider.JCO_SYSNR, "00"); connectProperties.setProperty(DestinationDataProvider.JCO_CLIENT, "000"); connectProperties.setProperty(DestinationDataProvider.JCO_USER, "JCOTESTER"); connectProperties.setProperty(DestinationDataProvider.JCO_PASSWD, "JCOTESTERSPASSWORD"); connectProperties.setProperty(DestinationDataProvider.JCO_LANG, "en"); Please advise A: For calling a registered external RFC server program please read SAP Note 1877907 - Support of extern-to-extern RFC communication with JCo 3.0 for the required destination configuration parameters. Instead of jco.client.ashost and jco.client.sysnr you need to specify jco.client.tpname, jco.client.gwhost and jco.client.gwserv. In addition, you probably need another destination to an ABAP system for querying the required RFC meta data. This destination needs to be specified as property jco.destination.repository_destination.
[ "es.stackoverflow", "0000344001.txt" ]
Q: Saber si un array es consecutivo ascendente o descendente Estoy intentando recorrer un array de [N] posiciones pero debo decir si es consecutivo ascendente (1, 2, 3, ...) o descendente (..., 4, 3, 2, 1) o en tal caso decir que no cumple las condiciones (1, 2, 3, 9, 7), hasta el momento tengo el siguiente código, int[] arreglo = { 5, 6, 7, 74 }; int contador = 1; for (int i = 0; i < arreglo.length; i++) { for (int j = contador; j < arreglo.length; j++) { if (arreglo[j] == arreglo[i] + 1) { //System.out.println("Ascendente"); contador = contador + 1; break; } if (arreglo[j] == arreglo[i] - 1) { //System.out.println("Descendente"); break; }else { //System.out.println("No cumple con las condiciones"); System.exit(0); } } } Les agradezco la ayuda, llevo dándole vuelta a este ejercicio pero aun no logro resolverlo. A: Para arreglos con más de un elemento: // variables de estado boolean esAscendente = true; boolean esDescendente = true; int[] arreglo = { 4,3,2,1 }; //ciclo para recorrer ascendente for(int i = 1; i < arreglo.length; i++){ // si elemento en i no es igual al elemento en posicion [i - 1] + 1 // no es ascendente if(!(arreglo[i] == arreglo[i -1] + 1)){ esAscendente = false; } // si elemento en i no es igual al elemento en posicion [i - 1] + 1 // no es descendente if(!(arreglo[i] == arreglo[i -1] - 1)){ esDescendente = false; } } if(esAscendente) System.out.println("Ascendente"); else if(esDescendente) System.out.println("Descendente"); else System.out.println("No cumple ninguna");
[ "stackoverflow", "0029975754.txt" ]
Q: inner join VS union all, when the result is not found I have two tables with the same column name. I want to search in them.I've research and realized that using UNION ALL is better that INNER JOIN (in terms of speed and performance). Now i want to know if the result is not found, UNION ALL is better yet ? I think the algorithm of JOIN Keyword is: if the result is not found in the first table, operation stops (in the second table, the search will not be). But UNION ALL search all the tables in any case.my thought is right ? If my thought is right then INNER JOIN is better when the result is not found ? point: col is indexed (phpmyadmin). Now which one have better performance if the result is not found ? SELECT col FROM table1 WHERE col='test' UNION ALL SELECT col FROM table2 WHERE col='test'; VS SELECT col FROM table1 INNER JOIN table2 ON table1.col=table2.col WHERE col='test'; A: UNION ALL is generally faster. It doesn't require any complex lookups. It just concatinates two query results. Whether data is queried from both tables in case of INNER JOIN greatly depends on the database, let alone specific details (indexes used, etc). That said, your queries are not the same at all. The version with UNION ALL will return two rows if both tables contain such a record and will still return one row if either table contains a match. The version with INNER JOIN will only return a row if both tables contain a matching record, and will not return a row if only one of them (or none) contains a matching record. NB, the one with INNER JOIN uses the unaliased column col, which will probably result in an error. On a general note, don't start optimizing based on theory. Write clear and readable queries that apply as good as possible to the situation (semantically correct). Only optimize when you need to. Also, be careful that you don't optimize the wrong thing. Even if the INNER JOIN version would be slightly faster when no data is found, the UNION ALL version will still be lightning fast anyway, so it's better to choose the more optimal one for situations where you do have a match.
[ "math.stackexchange", "0001604977.txt" ]
Q: Prove that $1-\sum_{i=1}^n a_i < \prod_{i=1}^n(1-a_i) $ Let $a_1, a_2, a_3,\ldots a_n$ be positive real numbers where $n > 1$. Prove that $$1-\displaystyle \sum_{i=1}^n a_i < \prod_{i=1}^n(1-a_i) $$ Can this be proved using the binomial theorem ? A: For some of the steps in the following proof by induction to be true, there needs to be some restrictions on the $a_i$. Try to find what is needed in order to make the proof valid. If $\prod_{i=1}^n(1-a_i) \gt 1-\sum_{i=1}^n a_i $ then $\begin{array}\\ \prod_{i=1}^{n+1}(1-a_i) &=(1-a_{n+1})\prod_{i=1}^{n}(1-a_i)\\ &\gt (1-a_{n+1})(1-\sum_{i=1}^n a_i)\\ &=1-a_{n+1}-\sum_{i=1}^n a_i+a_{n+1}\sum_{i=1}^n a_i\\ &=1-\sum_{i=1}^{n+1} a_i+a_{n+1}\sum_{i=1}^n a_i\\ &>1-\sum_{i=1}^{n+1} a_i\\ \end{array} $
[ "stackoverflow", "0051485721.txt" ]
Q: Identifying and computing statistics for top x objects in a dataframe Hi I have a dataframe as follows: product ID fees % fees quantity % quantity avg. price/item 0 ABB 4000 6% 651 5% 100 1 AXX 2500 5% 425 4% 110 2 ACC 2000 5% 538 4% 90 3 ADD 1500 4% 217 3% 80 4 AEE 1300 4% 192 3% 120 The dataframe is ordered by the fees for each product (highest to lowest) and I have 4000 products in the dataframe. What I would like to do is create 3 buckets: for products 1-10, 11-1000, 1001+. For each bucket I would like to calculate total % fees, total % quantity and a quantity weighted mean of avg. price for that bucket. I know how to do this using groupby if I had labelled the rows as to what bucket they belong to (then I could groupby the column containing the bucket label and compute the statistic). Any ideas on how to best label each row with a bucket identifier? If there is a less pedestrian way of doing this without labelling rows please let me know! A: I took the liberty to change your data a bit to let it span across all possible ranges and labels. df: product ID fees % fees quantity % quantity avg. price/item label 0 ABB 40 6% 651 5% 100 2 1 AXX 2 5% 425 4% 110 1 2 ACC 2000 5% 538 4% 90 3 3 ADD 150 4% 217 3% 80 2 4 AEE 1300 4% 192 3% 120 3 To label the data, you need to use pandas.cut df['label'] = pd.cut(df['fees'], [1, 10, 1000, np.inf], labels=[1,2,3]) Output: product ID fees % fees quantity % quantity avg. price/item label 0 ABB 40 6% 651 5% 100 2 1 AXX 2 5% 425 4% 110 1 2 ACC 2000 5% 538 4% 90 3 3 ADD 150 4% 217 3% 80 2 4 AEE 1300 4% 192 3% 120 3 Then, as you have mentioned, you can simply groupby data with labels and perform the statistic with groupby. Note that [1, 10, 1000, np.inf] defines the bins while, [1,2,3] are labels for the bins.
[ "stackoverflow", "0049256922.txt" ]
Q: Differences in arrow function and no arrow function in ReactJS? I am currently very confused about when should we use arrow function and when we should not. I did the search about this but still I'm not clear. For example, I create a button to count clicks, the code is like below: class Counter extends React.Component { constructor(props) { super(props); this.state = {counter: 0}; } buttonPressedIncrease = () => { this.setState((prevState) => { return {counter: prevState.counter + 1} }); } render() { return ( <div> <div>Counter: {this.state.counter}</div> <button onClick={this.buttonPressedIncrease}>+</button> </div> ); } } When I use arrow function on the button like this: onClick={() => this.buttonPressedIncrease}, the function does not work like I use in the code above. Anyone can explain for me this problem? When will arrow function work and when will it not? Many thanks in advance. A: In short, event listeners such as onClick expect to be given a reference to the function you want to invoke. With this in mind: onClick={this.buttonPressedIncrease} is correct because this.buttonPressedIncrease is a reference to a function and it is the one you want to run. However, onClick={() => this.buttonPressedIncrease} is incorrect because while () => this.buttonPressedIncrease is a function reference, it is not the function you want to execute. You don't want to execute the anonymous function () => this.buttonPressedIncrease, you want to execute this.buttonPressedIncrease. Remember that functions are only invoked with (). Ignoring the parenthesis only returns their reference. That's why this won't work - the anonymous function doesn't invoke the wanted function. Though, if you want, you could do: onClick={() => this.buttonPressedIncrease()} because the anonymous function will invoke the wanted function. Though I'd stick to the former solution.
[ "pt.stackoverflow", "0000197631.txt" ]
Q: Usar múltiplos loops javascript Existe alguma forma de rodar mais de um setInterval() ao mesmo tempo? Nesse meu código, se eu rodar duas vezes a função "interval" o programa entra em loop infinito e no console fica tenho: [1,2,3,4,5] [1,2,3,4,5,6] [1,2,3,4,5,6,7] [1,2,3,4,5,6,7,8......] infinitamente arraya = [] arrayb = [] function interval(array, length, count) { a = setInterval(function () { count++; array.push(count); if (array.length > length) { console.log(array.join(' ')); clearInterval(a); } }, 150);; } interval(arraya, 4, 0); // interval(arrayb, 9, 0) A: O problema no seu código é que a é uma variável global.Se você trocar por uma variável local tudo funciona direitinho. arraya = [] arrayb = [] function interval(array, length, count) { var a = setInterval(function () { count++; array.push(count); if (array.length > length) { console.log(array.join(' ')); clearInterval(a); } }, 150);; } interval(arraya, 4, 0); interval(arrayb, 9, 0)
[ "stackoverflow", "0046664885.txt" ]
Q: Why am I obtaining this error trying to set a JSON field with a value? Uncaught TypeError: Cannot set property 'today_avg_price' of undefined I am not so into JavaScript and I am going crazy trying to perform this script that, starting from a JSON document creates another JSON document: (I put my example into an html file and debugged it on Chrome, you can do the same to test it): <!DOCTYPE HTML> <html> <body> <p>Before the script...</p> <script> function checkForNull(value) { if (value instanceof Object && "@nil" in value) { return null; } return value; } console.log("START") var payload = JSON.parse(` { "Markets": { "Market": { "market_name": "Tambacounda Market N1", "market_description": "Tambacounda Market N1", "localization_id": 2, "long": 13.776796, "lat": -13.672198, "country": "Senegal", "regione": { "@nil": "true" }, "province": { "@nil": "true" }, "city": { "@nil": "true" }, "district": { "@nil": "true" }, "town": { "@nil": "true" }, "village": { "@nil": "true" }, "commodity": { "el": [{ "commodity_details_id": 4, "commodity_name_en": "Red onion", "commodity_name": "Red onion", "image_link": "Red_onion.jpg", "today_avg_price": 20.1500, "yesterday_avg_price": 33.3300, "currency": "XOF", "measure_unit": "kilogram", "price_series_id": 1 }, { "commodity_details_id": 6, "commodity_name_en": "Green Beans", "commodity_name": "Green Beans", "image_link": "Green_Beans.jpg", "today_avg_price": { "@nil": "true" }, "yesterday_avg_price": 778.0000, "currency": "RWF", "measure_unit": "kilogram", "price_series_id": 17 } ] } } } } `); // create new response var response = payload.Markets.Market; console.log("RESPONSE: " + JSON.stringify(response)); // convert null values response.regione = checkForNull(response.regione); response.province = checkForNull(response.province); response.city = checkForNull(response.city); response.district = checkForNull(response.district); response.town = checkForNull(response.town); response.village = checkForNull(response.village); // convert array of commodities into required HATEOS format var commodity = new Array(); for (i = 0; i < response.commodity.el.length; ++i) { var el = response.commodity.el[i]; var newEl = new Object(); newEl.commodity_name = el.commodity_name; newEl.commodity.today_avg_price = el.today_avg_price; newEl.commodity.yesterday_avg_price = el.yesterday_avg_price; newEl.rel = "commodity_details"; newEl.href = "http://5.249.148.180:8280/commodity_details/" + el.commodity_details_id; newEl.type = "GET"; commodity.push(newEl); } response.commodity = commodity; console.log("END"); </script> <p>...After the script.</p> </body> </html> As you can see the original document is into the payload object. The problem occur on this line of the first iteration in the for cycle: newEl.commodity.today_avg_price = el.today_avg_price; and give this error message: parse_json_market.html:97 Uncaught TypeError: Cannot set property 'today_avg_price' of undefined at parse_json_market.html:97 As you can see this JSON fields contains the 20.1500 value "today_avg_price": 20.1500, Why? What is the problem? What am I missing? How can I fix this issue? A: You have to just add this code before newEl.commodity.today_avg_price newEl.commodity = new Object(); The reason is because newEl is object but newEl.commodity is undefined. so you have to set newEl.commodity as object before calling newEl.commodity.today_avg_price. FIDDLE
[ "stackoverflow", "0031754098.txt" ]
Q: if statement with text not working I want to use a if statement to open different modals. Unfortunately, it do not work. It always open the '#flowSettingsDomain'. What´s going wrong? Thank you for your tips. HTML <ol class="targetjQEdit ui-sortable flowControllers"> <li class="f1"> <span class="step">Language Flow</span> <a href="#" id="lF" class="dismiss"> <i class="glyphicon glyphicon-remove-circle"></i> </a> <a href="#" onclick="fSetting(this); return false;" class="flowSettings"> <i class="glyphicon glyphicon-cog"></i> </a> <span class="badge badgeFilter" id="de">German</span> <span class="badge badgeFilter" id="en">English</span> </li> <li class="f1"> <span class="step">Domain Flow</span> <a href="#" id="dF" class="dismiss"> <i class="glyphicon glyphicon-remove-circle"></i> </a> <a href="#" onclick="fSetting(this); return false;" class="flowSettings"> <i class="glyphicon glyphicon-cog"></i> </a> <span class="badge badgeFilter" id="med">Medicine</span> </li> </ol> JS function fSetting (obj) { var t = $(obj).closest('span').text(); tx = $.trim(t); if (tx == 'Language Flow') { $('#flowSettingsLanguage').modal('show'); } if (tx.contains = 'Domain Flow') { $('#flowSettingsDomain').modal('show'); } }; A: I think the main problem is the selector in following line : var t = $(obj).closest('span').text(); it's not return the expected span element (because the span is a sibling, not a parent), but replacing it by the following selector work fine : var t = $(obj).parents('li').find('.step').text(); Removing also the contains function in condition because you don't need it, just compare the tx string directly, and you can trim your string in same line. Full js : fSetting = function (obj) { var tx = $.trim($(obj).parents('li').find('.step').text()); if (tx == 'Language Flow') { $('#flowSettingsLanguage').modal('show'); } if (tx.contains = 'Domain Flow') { $('#flowSettingsDomain').modal('show'); } }; Take a look at Working fiddle.
[ "stackoverflow", "0010988447.txt" ]
Q: MEF GetExports returning nothing with AllowMultiple = True I don't understand MEF very well, so hopefully this is a simple fix of how I think it works. I'm trying to use MEF to get some information about a class and how it should be used. I'm using the Metadata options to try to achieve this. My interfaces and attribute looks like this: public interface IMyInterface { } public interface IMyInterfaceInfo { Type SomeProperty1 { get; } double SomeProperty2 { get; } string SomeProperty3 { get; } } [MetadataAttribute] [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class ExportMyInterfaceAttribute : ExportAttribute, IMyInterfaceInfo { public ExportMyInterfaceAttribute(Type someProperty1, double someProperty2, string someProperty3) : base(typeof(IMyInterface)) { SomeProperty1 = someProperty1; SomeProperty2 = someProperty2; SomeProperty3 = someProperty3; } public Type SomeProperty1 { get; set; } public double SomeProperty2 { get; set; } public string SomeProperty3 { get; set; } } The class that is decorated with the attribute looks like this: [ExportMyInterface(typeof(string), 0.1, "whoo data!")] [ExportMyInterface(typeof(int), 0.4, "asdfasdf!!")] public class DecoratedClass : IMyInterface { } The method that is trying to use the import looks like this: private void SomeFunction() { // CompositionContainer is an instance of CompositionContainer var myExports = CompositionContainer.GetExports<IMyInterface, IMyInterfaceInfo>(); } In my case myExports is always empty. In my CompositionContainer, I have a Part in my catalog that has two ExportDefinitions, both with the following ContractName: "MyNamespace.IMyInterface". The Metadata is also loaded correctly per my exports. If I remove the AllowMultiple setter and only include one exported attribute, the myExports variable now has the single export with its loaded metadata. What am I doing wrong? EDIT: If I use weakly typed Metadata, my export is suddenly satisfied: var myExports = CompositionContainer.GetExports<IMyInterface, IDictionary<string, object>>(); Any ideas why? A: It is known that MEF has some problems when dealing with AllowMultiple = true. For a complete explanation you could for instance look here, anyway it derives from the fact that the metadata are saved in a Dictionary where the values are arrays when AllowMultiple is true, and such a thing can't be mapped on your IMyInterfaceInfo. This is the workaround I use. First of all your attribute should derive from Attribute, not from ExportAttribute: [MetadataAttribute] [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class ExportMyInterfaceAttribute : Attribute, IMyInterfaceInfo { public ExportMyInterfaceAttribute(Type someProperty1, double someProperty2, string someProperty3) { SomeProperty1 = someProperty1; SomeProperty2 = someProperty2; SomeProperty3 = someProperty3; } public Type SomeProperty1 { get; set; } public double SomeProperty2 { get; set; } public string SomeProperty3 { get; set; } } This means that the exported class should have 3 attributes, a standard export and your custom attributes: [Export(typeof(IMyInterface))] [ExportMyInterface(typeof(string), 0.1, "whoo data!")] [ExportMyInterface(typeof(int), 0.4, "asdfasdf!!")] public class DecoratedClass : IMyInterface Then you have to define a view for the metadata which will be imported. This has to have a constructor that takes the IDictionary as parameter. Something like this: public class MyInterfaceInfoView { public IMyInterfaceInfo[] Infos { get; set; } public MyInterfaceInfoView(IDictionary<string, object> aDict) { Type[] p1 = aDict["SomeProperty1"] as Type[]; double[] p2 = aDict["SomeProperty2"] as double[]; string[] p3 = aDict["SomeProperty3"] as string[]; Infos = new ExportMyInterfaceAttribute[p1.Length]; for (int i = 0; i < Infos.Length; i++) Infos[i] = new ExportMyInterfaceAttribute(p1[i], p2[i], p3[i]); } } Now you should be able to successfully call var myExports = CompositionContainer.GetExports<IMyInterface, MyInterfaceInfoView>();
[ "stackoverflow", "0029474204.txt" ]
Q: using classes to work with multiple ranges in excel vba There are a couple of very good ansewers on the mechanics of using smple classes in VBA: When to use a Class in VBA? and What are the benefits of using Classes in VBA? As someone relativley new to OOP and classes, it's hard to know how to implement them, or what is even really possible. For example, I have to deal with large ranges in multiple sheets and I need to get at many different subsets of the data. "agents who does x" and "clients who have y"...etc. Here's a sub i put together to get at the number of agents who have more than 2 clients: Sub agent_subset(output_sheet As String, _ Input_sheet_name As String, _ email_col As Integer, _ vendor_count_col As Integer, _ client_count_col As Integer, _ modified_col As Integer, _ num_of_clients As Integer) ' get a list of all agents with 2 or more clients and put them into a sheet Application.DisplayStatusBar = True Dim sheet_rows As Long sheet_rows = Worksheets(Input_sheet_name).Cells(rows.Count, 1).End(xlUp).Row Dim email_range As Range ' range of agent emails Dim client_count_range As Range ' range of client count Dim vendor_count_range As Range ' range of vendor count Dim modified_range As Range ' range of modified at With Worksheets(Input_sheet_name) Set email_range = .Range(.Cells(2, email_col), .Cells(sheet_rows, email_col)) Set client_count_range = .Range(.Cells(2, client_count_col), .Cells(sheet_rows, client_count_col)) Set vendor_count_range = .Range(.Cells(2, vendor_count_col), .Cells(sheet_rows, vendor_count_col)) Set modified_range = .Range(.Cells(2, modified_col), .Cells(sheet_rows, modified_col)) End With Dim n As Long Dim counter As Long counter = 0 Dim modified_array() As String For n = 2 To sheet_rows If client_count_range(n, 1).Value > num_of_clients Then counter = counter + 1 Worksheets(output_sheet).Cells(counter + 1, 1).Value = email_range(n, 1).Value Worksheets(output_sheet).Cells(counter + 1, 2).Value = client_count_range(n, 1).Value Worksheets(output_sheet).Cells(counter + 1, 3).Value = vendor_count_range(n, 1).Value modified_array() = Split(modified_range(n, 1).Value, "T") Worksheets(output_sheet).Cells(counter + 1, 4).Value = modified_array(0) End If Application.StatusBar = "Loop status: " & n & "of " & sheet_rows Next n Worksheets(output_sheet).Cells(counter + 3, 1).Value = "Last run was " & Now() Application.StatusBar = False End Sub It works great, but now I want to get a an even smaller subset of agents and clients based on other criteria. So, I'm going to write a similar function, manipulating similar data. My gut tells me using classes will make my life easier, but I don't know how to chop up the tasks. Should there be an Agent class that has all the info about agents? and/or a client class? Or, should the classes be for looking at entire ranges or sheets? I'm not looking for specific code, but a methodology on how to break things down. A: I have to deal with large ranges in multiple sheets If you think in terms of computers, you're code will be very functional. Those ranges represent something real (an agent, a customer, an invoice, a transaction), so think in those terms. I would have an Agent class that held all the properties of an agent. I would have an Agents collection class that held all my Agent classes. Then, in my Agents class, I would have Filter methods that return subsets of the Agents class. Here's an example: I have customers. Customers can be Active or not. Customers also have a template that I use when I email them certain information. When I want to email active customers who use the Table1 template, it looks like this Set clsCustomersToEmail = clsCustomers.FilterOnActive(True).FilterOnTemplate("Table1") For Each clsCustomer in clsCustomersToEmail 'Do stuff Next clsCustomer` In my CCustomers collection class, I have a couple of properties that return a CCustomers class with few customers than the big CCustomers class (called clsCustomers) Public Property Get FilterOnActive() As CCustomers Dim clsReturn As CCustomers Dim clsCustomer As CCustomer Set clsReturn = New CCustomers For Each clsCustomer In Me If clsCustomer.Active Then clsReturn.Add clsCustomer End If Next clsCustomer Set FilterOnActive = clsReturn End Property Public Property Get FilterOnTemplate(ByVal sTemplate As String) As CCustomers Dim clsReturn As CCustomers Dim clsCustomer As CCustomer Set clsReturn = New CCustomers For Each clsCustomer In Me If clsCustomer.Template.TemplateName = sTemplate Then clsReturn.Add clsCustomer End If Next clsCustomer Set FilterOnTemplate = clsReturn End Property When I want to do stuff like write a bunch of customer data to a range, I make a property that returns an array, and write the array to the range. Set clsCustomersPastDue = clsCustomers.FilterOnActive(True).FilterOnPastDue(True) vaWrite = clsCsutomerPastDue.AgingReport rCell.Resize(UBound(vaWrite,1),UBound(vaWrite,2)).Value = vaWrite I tend to think of what physical things am I coding. They don't have to be tangible things, but if you can take it back to something that's tangible, that can be helpful. A transaction is a thing. But if that transaction is an invoice, now determine the properties of that object become easy. For one, you can just look at a paper invoice and see what the properties are. The next level is relationships. Every Agent class has customers. So your Agent object should have a Customers property that returns a CCustomers class. Or if it's not structured that tightly in real life, maybe your CCustomers class has a FilterOnAgent property that returns the subset of customers you're looking for.
[ "stackoverflow", "0012519987.txt" ]
Q: Actionscript 3: How do I get date from server (not client) I am working on a Christmas calendar for my school, when I noticed that, the Date-class is not what I though it was. It gets the time from the client CPU, and that won't do. So, I been looking around on the web, but there have been no good answers (at least that I could make any sense of). So here it is: How do i get the time and date (*) in UTC +1, from the server my flash-program are hosted, or some external time-server? *In UNIX-time, or somehow else actionscript 3 can understand My search for answers had suggestions for some php-scripts, but i don't understand how to use that (there where a few examples, but they where in AS2). A: A more secure way of doing this (eg not using flash vars which can be tampered with), would be to create a very simple server page (outputs plain text instead of html) that outputs the date, then load that into flash with a loader and parse it into a native Date object. The flash side would look like this: var loader:URLLoader = new URLLoader() loader.load(new URLRequest("your server page")) loader.addEventListener(Event.COMPLETE, onLoaded) function onLoaded(evt:Event){ var date:Date; try{ date = new Date(Number(loader.data)); //need to cast the loader data as a number }catch(e:Error){ } if(!date){ //your output from the server isn't formatted in a way flash can convert it date = new Date(); //use local time } } The reason for using try/catch, is because if output from the server isn't a valid date it will throw an error when trying to convert it. If an error is thrown anywhere inside of a try block, it will exit at the line of the error (skip the rest of the code) and run what is in the catch block. If there is no error in the try block, the code in the catch block will never run. With PHP (though I don't have php anywhere handy to check so this may need to be corrected by someone, and it's been about 10 years since I've programmed with it) <?php header("Content-Type: text/plain"); print time() * 1000; ?>
[ "stackoverflow", "0026085403.txt" ]
Q: why cant I bind to single actor instance (akka router) with scaldi? I´m currently struggeling with implementing my Akka router logic using scaldi for dependency injection. Why cant I bind to a single actor instance with scaldi, since my actor is a router and I only want to have one single instance of it? The way I came to ask this question was another stackoverflow entry. My scaldi Module: class DAOModule extends Module { bind toProvider new UserDaoWorker binding to new UserDaoRouter } This way only one instance is created and as soon as I inject my router multiple times it gets a dead letter actor as sender from the sender() method. When I change the binding to... binding toProvider new UserDaoRouter ... it works perfectly fine, but every injection means a new instance of my router. Am I right? So how can I achieve having only a single instance of my router which is injectable? Thanks in advance A: This is what worked for me: class DAOModule extends Module { binding toProvider new UserDaoWorker binding toProvider new UserDaoRouter binding identifiedBy 'singletonUserRouter to { implicit val system = inject[ActorSystem] AkkaInjectable.injectActorRef[UserDaoRouter] } } And then in my controller: val userDaoRouter = inject[ActorRef] ('singletonUserRouter) I hope this will help someone else ;)
[ "stackoverflow", "0016307696.txt" ]
Q: Why is memory profiling in ruby so hard? Or rather, why aren't there better tools for profiling memory in ruby, specifically rails apps? Recently our rails app (hosted on heroku) has started seeing lots of R14 errors in the worker dynos. This means we're running out of memory. Bumping the dynos to 2x (512mb -> 1GB) only alleviated the problem temporarily, leading me to believe there is a memory leak somewhere. Naturally, my next step was to find a good profiling gem that can help me discover the source of the leak. Maybe I'm just ignorant of the tools available, or maybe I just don't know how to use the ones I have. My wish is that I could install a gem and then run reports on the memory usage statistics. Hitting an endpoint to get a report is not really viable as my memory issues are isolated to worker dynos running delayed jobs. I've looked at memprof, but it's 1.8 only. I've looked at ruby-prof (awesome), but the memory profiling requires a patched ruby intepreter. I've looked at GC::Profiler, but I don't understand how to find memory leaks with it. So, is it just plain difficult to find memory leaks in ruby? Or am I missing the point somehow? A: Depending on your "type" of leak, You can run valgrind against ruby. Might require recompilation again though. In general it's hard because ruby does method allocation without firing any events, by default, so it's tricky to track. See also perftools.rb project, which somewhat works around this limitation.
[ "electronics.stackexchange", "0000232642.txt" ]
Q: Moisture adsorption on FR4 PCB Although the adsorption of moisture by FR4 is quite low, what is the best way to minimize it or eliminate it completely? A: If there are any fixing holes, it will be impossible to eliminate completely; using Parylene can (depending on how it is applied) provide a complete barrier. although moisture can still penetrate (very slowly). This is very expensive solution (not least because there are very few suppliers who can perform this operation). The other downside is it cannot be effectively removed without causing major damage to the PCB. I have some products where the use of this sealant is mandated (they are in ship-board aircraft). I only mention this to show there are solutions, if there is a requirement for complete sealing. I would note that different PCB materials have different moisture absorbtion rates. 'Ordinary' conformal coat comes in a wide array of types, each with their own pros and cons: Acrylic, Urethanes, Silicones, Synthetic Rubber, Water based(!), some are UV Curable. There are numerous manufacturers of these products and which one to use depends on the specific application. As Sphero notes, there are system level considerations with ancillary materials to consider as well. A: Simply covering most of the PCB with solder mask will reduce the absorption of moisture. As will using a better (and more expensive) laminate such as Rogers 4350B- perhaps an order of magnitude better. Adsorption is a chemical process that occurs on the surface and can affect surface resistivity. Since you are talking about PCB mass, it sounds like you are actually talking about moisture absorption which is diffusion into the bulk of the material. Controlling Moisture in Printed Circuit Boards is a useful paper. From a system point of view, other than the bare PCB, it would be important to avoid components that absorb moisture- which would include plastic-packaged parts, but especially polyamide (Nylon) fasteners etc. which can absorb an enormous amount of moisture (as much as 10%)- enough to cause large dimensional changes as well as mass changes.
[ "gis.stackexchange", "0000353368.txt" ]
Q: Correlating mol/m^2 with ton and lb? How do I compare tropospheric_NO2_column_number_density(mol/m^2) of Sentinel-5p with EPA statewide emission data which unit is Ton or lb? Goal: My goal is to compare remote sensing no2 emission to bottom-up no2 emission for electricity generation. Current progress: I have calculated the total yearly emission of no2 for California. The data used for this is Sentinel-5p OFFL NO2 stored in Google Earth Engine. I first take the yearly sum of no2 (tropospheric_NO2_column_number_density) and use gee reduceRegion function to get a sum of yearly no2 of California. I want to compare that value with EPA emission data which contain yearly statewide emission data. But the problem is tropospheric_NO2_column_number_density unit is mol/m^2 and EPA emission data in ton or lb. Question: So how to compare these two value of the different units? After searching I found this post in sentinel-5p forum which discusses converting mol/m^2 to ppb. But this doesn't solve my problem. EDIT: After seeing @xunilk detailed answer, I came to know we can convert mol/m^2 to lb/m^2 and my question needs some clarification. If we convert and sum entire year no2 of a state then our final value's unit will be lb/m^2. For example, California yearly total no2 emission from s5p satellite is 104 lb/m^2. On the other hand, our bottom-up emission data describes that California yearly emission is 30000 ton. So how can we convert this lb/m^2 value to only ton ( not ton/m^2 ) and also how to convert lb/m^2 to lb (not lb/m^2)? Could we just multiply the entire California area in m^2 or is there any way to do that in satellite imagery? A: One mol of NO2 is 46.0055 g (reference here) and 1 pound is 453.592 g so, conversion factor from mol to lbs is 0.1014 lbs/mol. For converting mol/m2 to lbs/m2 in snippet code of this link Sentinel-5p OFFL NO2, you only have to map over collection by using this conversion factor (0.1014 lbs/mol); as in modified following script: var collection = ee.ImageCollection('COPERNICUS/S5P/OFFL/L3_NO2') .select('tropospheric_NO2_column_number_density') .filterDate('2019-06-01', '2019-06-06'); var mol_to_lb = collection.map(function (image) { return image.multiply(0.1014); }); var band_viz1 = { min: 0, max: 0.0002, palette: ['black', 'blue', 'purple', 'cyan', 'green', 'yellow', 'red'] }; var band_viz2 = { min: 0, max: 0.00002, palette: ['black', 'blue', 'purple', 'cyan', 'green', 'yellow', 'red'] }; Map.addLayer(collection.mean(), band_viz1, 'S5P N02_mol'); Map.addLayer(mol_to_lb.mean(), band_viz2, 'S5P N02_lbs'); Map.setCenter(65.27, 24.11, 4); After running above script in GEE code editor, result was as follows. It can be observed in Inspector Tab, after clicking in an arbitrary point on map area, that this conversion was realized as expected. Editing Note: Based in your commentary and editing note, I load in my assets a Feature Collection for California state and modified my previous script for calculating emissions in Tm/m2 instead of lbs/m2. So, following script can calculate total emissions for California area in Tm (435.6976265829383 Tm) with a mean reducer. var area = ee.FeatureCollection("users/joseguerreroa/california"); var collection = ee.ImageCollection('COPERNICUS/S5P/OFFL/L3_NO2') .select('tropospheric_NO2_column_number_density') .filterDate('2019-06-01', '2019-06-06'); var scale = collection.first() .projection().nominalScale(); print("pixel area", scale); var mol_to_ton = collection.map(function (image) { return image.multiply(0.000046); }); var calif_clip = mol_to_ton.mean().clip(area); var band_viz2 = { min: 0, max: 0.000000002, palette: ['black', 'blue', 'purple', 'cyan', 'green', 'yellow', 'red'] }; Map.addLayer(calif_clip, band_viz2, 'S5P N02_lbs'); Map.centerObject(area, 5); //calculating whole emission area in California m2 var emission_area = ee.Image.pixelArea().reduceRegion({ reducer: ee.Reducer.sum(), geometry: area, scale: 1113, maxPixels: 1e13 }); var california_area = emission_area.values().getInfo()[0]; print("California area", california_area); // Reduce the region. The region parameter is the Feature geometry. var mean_NO2_emission = calif_clip.reduceRegion({ reducer: ee.Reducer.mean(), geometry: area, scale: 1113, maxPixels: 1e9 }); // The result is an emision in ton/m2. var tot_emission = mean_NO2_emission.values().getInfo()[0]; print ("ton/m2", tot_emission); var tot = ee.Number(tot_emission).multiply(california_area); print("total emission(ton) of NO2 for California", tot); After running above script, result can be visualized as follows: A: These are units measuring different things, so to compare them you need to make some assumptions. Mol is a unit that is proportional to mass, so it is comparable to the tons. When it is divided by m2, the number describes the distribution, not the release. What you could.do is e.g. to divide the releases in each state with the area of the state. If all the atmospheric NO2 is from the power production releases in the same state, you should get a constant number. (btw 1 mol of NO2 is 46grams)
[ "sports.stackexchange", "0000017556.txt" ]
Q: Can bowler bowl with two hands (left & right) in international cricket Recently I've seen in domestic match there was one bowler (spinner) who used his both hands while delivering the ball? I've doubt can it be possible in International Cricket. Does ICC has any rule about this? A: This is perfectly legal, so long as the bowler informs the umpire before changing from bowling left-handed to right-handed or vice versa. Quoting Law 21.1.1, Mode of delivery: The umpire shall ascertain whether the bowler intends to bowl right handed or left handed, over or round the wicket, and shall so inform the striker. It is unfair if the bowler fails to notify the umpire of a change in his/her mode of delivery. In this case the umpire shall call and signal No ball. There is nothing in any of the ICC Playing Conditions for Test Matches, One Day Internationals or T20 Internationals which overrides this.
[ "stackoverflow", "0006780060.txt" ]
Q: Java EE transactions methods marked as not supported I have a method that transfers data from one database to another and in the process creates new tables in the target database. The method is part of a stateless EJB (Java EE 6, GF 3.1) so the container, by default, starts a distributed transaction when the method is called. The data transfer process essentially runs as two separate steps 1. read from the source database 2. write to the target database. If the read step fails then I don't want the write step to happen but if the write step fails and the read has been committed already I don't really care - I'll just throw the data away. Initially I hit the problem that my data sources weren't XADataSource's so the container complained about that. I then converted them to XADataSource's but it still failed because the write process (which is into a MySQL database) contains create table statements which cause an implicit commit and you can't do that in a distributed transaction. The solution I've finally come to is to mark transfer method as TransactionAttributeType.NOT_SUPPORTED and then place the read and write process into their own methods which are called by the parent transfer method. My question though is this: do the read and write methods run inside their own transactions or does the NOT_SUPPORTED propagate to them? My guess is that they have an implicit TransactionAttributeType.REQUIRED and so will start their own transaction but I'm not sure and I think it's important they are running inside a transaction. Is this the best solution to this problem? A: The bigger question for separating the read and write steps is whether or not the write step should still be performed if some other thread/process is mutating the data that was obtained from the read step. In other words, are you sure that the read and write should not be in the same transaction? Perhaps you have some external guarantee that there won't be problems writing the data separately. How are the read and write methods called? If they're called as local methods, then the NOT_SUPPORTED will propagate. If they're called through a session bean proxy object, then the default REQUIRED will apply: @Stateless @Local(MyIntf.class) public class MyBean { @EJB private MyIntf ivMyBean; // Self-injection @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public void method() { // Use the injected proxy rather than "this.read()" to ensure that the // default REQUIRED transaction attribute is used for the DB operations. MyResults results = ivMyBean.read(); ivMyBean.write(results); } public MyResults read() { ... } public void write(MyResults results) { ... } } It seems somewhat questionable that you have to create tables based on the read data. Is there really no way to do that as a separate operation? I would suggest an outer REQUIRED method that does the read operation, then calls a NOT_SUPPORTED method to create tables, and finally does the write operation in the same transaction as the read, which was temporarily suspended while the NOT_SUPPORTED method was running.
[ "stackoverflow", "0023792550.txt" ]
Q: Deleting records from two seperate entity in core data What I Know 1: During a transaction or a view I am able to delete records from a single entity(table) --Success :) What I am trying to do Entity(table) 1 : Inventory (Name type Purchase date ........ Category name ) Entity(table) 2 : Category (Category name, Category Type) In the code for a category view When I delete a category I want the corresponding Inventory Item to be deleted ; I know I can set some relationship for this delete , but I was unable to find a good link or a example which does that , I am unable to apply that rule Here's my code (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { PIMCategoryListCellTableViewCell *cell = (PIMCategoryListCellTableViewCell*) [tableView cellForRowAtIndexPath:indexPath]; if (editingStyle == UITableViewCellEditingStyleDelete) { // [self.tblView beginUpdates]; NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext]; //Records from Category entity(table) deleted -- Success So far [context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]]; NSError *error = nil; if (![context save:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } // Use the fetch result controller to get the corresponding item of same category self.fetchedResultsControllerCategory = nil; [self fetchedResultsControllerItem:cell.categoryName.text]; NSUInteger count = [self.fetchedResultsControllerCategory.fetchedObjects count]; //this way I know if any item are present for the category if (count> 0) { NSManagedObjectContext *contextN = [self.fetchedResultsControllerCategory managedObjectContext]; NSIndexPath *i; for ( i.row =0 ; i==1;i++ ) { [contextN deleteObject:[self.fetchedResultsControllerCategory ob ]; } // @property (strong, nonatomic) id detailItem; // [contextN deleteObject:[self.fetchedResultsControllerCategory ob ]; //[contextN reset] NSError *error = nil; if (![contextN save:&error]) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); // [self.tblView endUpdates]; } }} Now I have tried to change the context but still unable to delete the second entity(table) records Any suggestion , ; Let me know if you need more explanation A: You need to set up the relationship in the core data editor. Get rid of the 'category name' attribute from Inventory, and instead create a relationship to Category. (And an inverse relationship from Category to Inventory) Then you can set the delete rule on the category relationship to "Cascade" which will then delete any related Inventory, as soon as you delete a category.
[ "chinese.stackexchange", "0000031498.txt" ]
Q: Chinese Speaking Gps Tracker For My Dog, please help to translate I bought a new Chinese GPS tracker for my dog online on eBay I have some problem to configure it because I can't track it, I followed all the instruction in English but I can't figure out what is wrong When I press on the only button it has and it speaks Chinese so I recorded it and want your help to translate it I have two videos with different sentences: https://youtu.be/xxJvdyaGVfA https://youtu.be/9hmWyLZU-0o the product link on ebay: https://www.ebay.com/itm/Pet-Dogs-Cats-Sheep-Finder-Realtime-GPS-GSM-Tracker-Waterproof-For-Android-iOS/392097084010?ssPageName=STRK%3AMEBIDX%3AIT&var=661043181839&_trksid=p2057872.m2749.l2649 Thank you, Or Hirshfeld Israel A: The first video is quite clear: she says, 3874成功 3874 succeeded The second video is harder to decipher. It’s not Chinese; after listening a few times, I believe she says, Number not set. Not sure if that tells you very much, but that appears to be the extent of it.
[ "stackoverflow", "0014624132.txt" ]
Q: Scripts and white spaces I have a simple bash find and replace script 'script.sh' : #!/bin/bash find . -type f -name '.' -exec sed -i '' "s/$1/$2/" {} + When I run my command ./script.sh foo bar, it works. Suppose now my two inputs strings $1 and $2 are sentences (with white spaces), how can I make the script to recognize each of them as whole strings ? A: Add each sentence in quotes " #!/bin/bash echo $1 echo $2 output $ ./tmp.sh "first sentence" "second sentence" first sentence second sentence Edit: Try this: #!/bin/bash find . -type f -exec sed -i "s/$1/$2/" {} + Ouput: $ cat test1.txt ola sdfd $ ./tmp.sh "ola sdfd" "hello world" $ cat test1.txt hello world $ ./tmp.sh "hello world" "ols asdf" $ cat test1.txt ols asdf
[ "stackoverflow", "0057195995.txt" ]
Q: I am not able to get required output out of max_element() I am giving input 1 2 3 4 5 to this code snippet and keep getting O as an output. I want 5(the maximum element) as the required output. int main() { int inp; std::vector<int> A; for (int i = 0; i < 5; ++i) { cin >> inp; A.push_back(inp); } int i1 = *max_element(A.begin(), A.end()); cout << A[i1]; } A: *max_element returns the element, not the index, so it should be: int i1 = *std::max_element(A.begin(), A.end()); std::cout << i1;
[ "judaism.stackexchange", "0000047692.txt" ]
Q: What are the most active and educational religious podcasts and blogs? I’m looking for more Jewish blogs and podcasts to subscribe to, and not wishy washy “Jewish life” ones full of dubious recipes and pop culture tie-ins. I’m looking for intermediate-level, English-language (with Hebrew in the teachings, of course) drashot, shiurim, sermons, and scholarly essays. Topics like Torah study, Halakha, liturgy and holidays, ideally published on a timely schedule. Media to help me keep learning while I’m walking, washing dishes or sitting on the bus. Any suggestions? Podcasts are the higher priority for me. I’m currently subscribed to the Ziegler Torah podcast feed (that’s where my partner is in rabbinical school) and the Park Avenue Synagogue lecture series, and I love their teachings, but they’re too infrequent for my huge appetite. I’ve perused a related thread from two years ago, What are the most essential Jewish websites?, and there are a few good blogs listed there, but many of the sites are no longer maintained, and many also lack the RSS feeds I’d need for subscribing, especially the audio resources. Thank you, and Shabbat shalom! A: Here are three Torah podasts that I have found valuable, and that I think could fit your needs. All of them are ongoing, updated at least weekly. Torah Tidbits Audio is a weekly radio show by Phil Chernofsky. His main focus is the weekly parsha along with any upcoming holidays. He also likes to talk about the Jewish calendar, the land of Israel, and the Hebrew language. He plays Jewish songs to break up the show. I have enjoyed this show a great deal and learned a lot from it, partly because I happen to be very interested in a lot of the same things that Chernofsky is into. He does a great job of making his show accessible to people with a wide range of backgrounds. There's an RSS feed available via Arutz Sheva. The associated print publication, Torah Tidbits, is also great. I don't think there's an RSS feed for it, but you can sign up to receive an email when he puts up a new issue, which is available in PDF and plain text. Ki Mitzion Teitze Torah (KMTT) is a [supposedly] daily Torah Podcast, from Yeshivat Har Etzion. (I say "supposedly" because it looks like they've lately been putting up two or three classes each week.) The podcast consists of up to five weekly classes on different topics, which are switched up each semester. I have particuarly enjoyed classes on philosophical topics by R' Ezra Bick, in which he delivers deep insights from medieval thinkers with a conversational delivery that I find engaging. OU Torah Podcasts from the Orthodox Union offers a whole bunch of podcasts, updated on various frequencies from daily to sporadic. I haven't listened to most of them, but I listen to Nach Yomi, which teaches one chapter of the post-Pentateuch books of the Bible per day, completing the whole set every ~2.5 years. They switch lecturers at the beginning of each book. The classes tend to stick pretty close to the text of the chapter at hand, explaining what's going on according to the various commentaries. I'm using this series (plus actually reading the chapter on paper before listening) as a way of becoming familiar with the parts (read: large swaths) of the Bible that I've had little experience with. These lectures were recorded two cycles ago and a re-run each cycle, and I believe similar is true of other of the daily podcasts (e.g. Daf Yomi), so the content's not necessarily new, but it is realeased daily anew via RSS. I wish you great success in making good use of your downtimes! A: Really, it should be Danny Schoemann giving this answer, but i'll do him a favor and recommend his Halocho a Day blog. It has English language, intermediate level halachot, and can be quite informative. In fact, i'm adding it to my reading list right now. :)
[ "softwareengineering.stackexchange", "0000181729.txt" ]
Q: How to implement classes that should be loaded once? I'm building a little framework, currently it is just for fun. I'm wondering how should I implement classes that should be instantiated by the framework and be passed to the controller to use? For instance: I have an "input" class that houses functions which take POST and GET data and filter it. The class is also used by the framework for routing and similar things. Should I make these methods static? Should I use the singleton pattern? Or maybe should I make something like Codeigniter has - a loader that stores instances of all instantiated classes? A: what you looking for "A SINGLE instance of a class" the way to go is with a Singleton pattern. basic implementation of a singleton pattern. Class Test { $private $testInstance; private function __construct() { }; public static function getInstance(); { if ($this->testInstance === null) { $this->testInstance = new self(); } return $this->testInstance; } } and from other place you get that class instanciated with $test = Test::getInstance(); every time you'll need the object you call the getInstance static method and it will return the object, or create it and return it. hope it helps. A: Most of these answers are suggesting using the Singleton pattern or using static, but I disagree with this. Yes, this will get the job done, but IMHO, it's a bad practice. It's harder to test and isolate code that uses your Singleton/static code so it's not ideal. I'd use the Inversion of Control pattern/Dependency Injection pattern. Basically it works like this (Note that I come from a Java background): class INeedOneInstanceOfAClass { OneInstanceOfAClass oneInstanceOfAClass; public void setOneInstanceOfAClass(OneInstanceOfAClass oneInstanceOfAClass) { this.oneInstanceOfAClass = oneInstanceOfAClass; } // ... } Some other code is responsible for calling that setter. The code that calls the setter makes sure it only creates one instance of OneInstanceOfAClass and it passes that same instance into all the other classes you have with a setOneInstanceOfAClass method. As a result, there's only one instance of OneInstanceOfAClass but, OneInstanceOfAClass is not a Singleton and it doesn't need to use static anywhere. It's just a regular class that you only instantiate once. Now it's really easy to isolate INeedOneInstanceOfAClass in a unit test. Your unit test creates INeedOneInstanceOfAClass and passes in a fake OneInstanceOfAClass that does whatever it needs to do to get out of the unit test's way.
[ "stackoverflow", "0026751113.txt" ]
Q: Fragment inside Drawer I want to add a fragment for a sliding drawer in DrawerLayout. Means the last child of DrawerLayout is to be a fragment. And When I click on Drawer ico, the fragment to be visible in Drawer. But When i try, I couldn't get the view of the fragment in Activity. Please help me for doing it. Thanks Jomia A: I got the solution. In layout, <fragment android:name="com.example.fragments.MyFragment " android:id="@+id/left_drawer" android:layout_weight="1" android:layout_width="240dp" android:layout_gravity="right" android:layout_height="match_parent"/> In activity, MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentById(R.id.left_drawer); View fragmentView = myFragment .getView(); Then I just use this view in onPrepareOptionsMenu for drawer. @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean isDrawerOpen= dLayout.isDrawerOpen(fragmentView ); if(isDrawerOpen) menu.findItem(R.id.drawer).setVisible(false); else menu.findItem(R.id.drawer).setVisible(true); return super.onPrepareOptionsMenu(menu); } Thats all...
[ "stackoverflow", "0051504462.txt" ]
Q: Speech recognition provide an unknown error after listening I have a templates / index.html file. When you click on the first button, btn_query, you should callstartDictation(), a javascript function for speech recognition. But there is a problem, which only appears on StackOverflow and with Chrome, with recognition.onresult = function (e) {...}.   1. I do not get the pop-up window.alert (5 + 6); at the beginning of the function.   2. The StackOverflow console recognizes that there is an error and writes: Recognition had an error. But I do not know which one. It acts like this: it asks for the permission to use the microphone and then there is a red light on the tab on the top and finally the error message. <!DOCTYPE html> <html style="margin: auto; display:table;"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"> </script> <script>var synth = window.speechSynthesis;</script> <!-- HTML5 Speech Recognition API --> <script> function startDictation() { document.getElementById('transcript').value = ''; document.getElementById('output').value = ''; if (window.hasOwnProperty('webkitSpeechRecognition')) { var recognition = new webkitSpeechRecognition(); recognition.continuous = false; recognition.interimResults = false; recognition.lang = "en-US"; recognition.start(); recognition.onresult = function (e) { window.alert(5 + 6); document.getElementById('loader').hidden = false; document.getElementById('transcript').value = e.results[0][0].transcript; recognition.stop(); var data = e.results[0][0].transcript; $.post("http://localhost:5000/news_urls", { "data": data }, function (response) { document.getElementById('loader').hidden = true; data = response; document.getElementById("output").value = data["urls"]; }).error(function (response) { document.getElementById('loader').hidden = true; if (response.status == 400) text = jQuery.parseJSON(response.responseText)["original_exception"]; else text = "I'm sorry. I did not get that."; document.getElementById("output").value = text; }); }; recognition.onerror = function (e) { recognition.stop(); console.log("Recognition had an error"); window.alert(10 + 6); } } } function btnClick() { synth.cancel(); var utterThis = new SpeechSynthesisUtterance(document.getElementById("output").value); utterThis.voice = synth.getVoices()[0]; utterThis.pitch = 1.0; utterThis.rate = 0.8; utterThis.onerror = function(e) { console.log("Something went wrong with utterance."); }; synth.speak(utterThis); } </script> <style> .speech { border: 0px solid #DDD; width: 600px; padding: 0; margin: 0; font-family: "Calibri"; } .speech input { border: 1; width: 240px; display: inline-block; height: 30px; } .speech img { float: right; width: 40px; } </style> </head> <body bgcolor="#e2e2e2"> <h1 style="font-family: Calibri;">Delbot</h1> <div class="speech" ><i>It understands your voice commands, searches news and knowledge sources, and summarizes and reads out content to you.</i></div> <br /><i class="speech"><font color="gray">Only tested on Windows PCs. Not tested on other PCs or mobile devices.</font></i> <div class="speech"> <textarea style="width: 600px;font-family: Calibri;font-size:x-large" name="q" id="transcript" placeholder="Your query will appear here after you speak." rows="2" readonly="True"></textarea> <br> <input id="btn_query" type="button" onclick="startDictation()" value="Query" style="font-family: Calibri;" /> <img src="static/loader.gif" width="100px" align="left" style="float: left" hidden="True" id="loader" /> <br><br> <h2 class="speech">Results</h2> <textarea style="width: 600px;font-family: Calibri;font-size:x-large" id="output" rows="2" placeholder="Results will appear here." readonly="True"></textarea> <input id="btn_speak" type="button" value="Speak" onclick="btnClick()" style="font-family: Calibri;" /> </div> </body> </html> A: It seems you are running into the browser with a local file path. For e.g. file://xyz/ss/ss/test.html Try to host this HTML file on the server and check you will get the appropriate result. Check this and this. As chrome does not support to allow microphone with a local file path. You can forcefully do it but it is not recommended. With the really dangerous --disable-web-security (strongly not recommended, especially if you use this instance of Chrome for normal browsing as well, which can put your device in danger) and --allow-file-access-from-files (also not recommended). Debug: I am getting the same error by accessing the local file. But while host the index.html file and access http://localhost:1111 it's working perfectly. Note:- Some editors load plain HTML into the browser. Try below editors where they host your file and run perfectly. Just C+V your code to an editor and run. Try with below editors. https://www.tutorialspoint.com/online_javascript_editor.php https://www.w3schools.com/tryit/tryit.asp?filename=tryhtml_default Update=============
[ "stackoverflow", "0052716224.txt" ]
Q: combining columns in pandas dataframe I have the following dataframe: df = pd.DataFrame({ 'user_a':['A','B','C',np.nan], 'user_b':['A','B',np.nan,'D'] }) I would like to create a new column called user and have the resulting dataframe: What's the best way to do this for many users? A: Use forward filling missing values and then select last column by iloc: df = pd.DataFrame({ 'user_a':['A','B','C',np.nan,np.nan], 'user_b':['A','B',np.nan,'D',np.nan] }) df['user'] = df.ffill(axis=1).iloc[:, -1] print (df) user_a user_b user 0 A A A 1 B B B 2 C NaN C 3 NaN D D 4 NaN NaN NaN
[ "superuser", "0000727636.txt" ]
Q: What is wrong with this Windows shutdown command? I am using Windows 7 and XP. I want to run a script to run this command: shutdown /p /f /t 120 On Windows 7, it shows that an error occurred, but I think I am using it correctly. A: You are using conflicting switches. /p – Turn off the local computer with no time-out or warning. Can be used with the /f option. /t – Set the time-out period before shutdown to xxx seconds. You are telling it to shutdown now with /p and shutdown in 120 seconds with /t. A: You should use shutdown /f /t 120 Parameters /p and /t are incompatible. Check Windows 7 shutdown command syntax for other parameters and more info.
[ "stackoverflow", "0015945267.txt" ]
Q: How to fire select onchange event with jQuery? I have a dropdown list: <select size="1" name="filter"id="priority_filter" onchange="filter_user_trainings();"> <option value="all">All</option> <option value="optional">Optional</option> <option value="mandatory">Mandatory</option> <option value="essential">Essential</option> <option value="custom">Custom</option> </select> In a function I call these: if(db==0 || db==1 ||db==2) { $("#priority_filter").val('custom'); } I want to fire the select onchange function when the jQuery switches the value. How can I do this? The code above does not work. A: You can call change() on select to first or .trigger("change"); if(db==0 || db==1 ||db==2) { $("#priority_filter").val('custom'); $("#priority_filter").change(); } OR if(db==0 || db==1 ||db==2) { $("#priority_filter").val('custom').change(); } A: $(document).ready(function(){ ..code.. $('#priority_filter').on('change', function(){ ..do your stuff.. } ..code.. });
[ "stackoverflow", "0034444875.txt" ]
Q: creating reactive array session storage I'm trying to exclude documents to show on client based on user event. this is my attempt which failed: Template.documents.events({ 'click #dontShowThisDocument': function () { Session.set('excludedDocument', this._id); } }); Template.documents.helpers({ lists: function () { var excludedDocuments = []; excludedDocuments.push(Session.get('excludedDocument')); return Coll.find({_id:{$nin:excludedDocuments}); } }); how to create array session storage with meteor so then the user able to exclude certain document on a list reactively ? Thank You so much. A: A Session variable can hold an array (or any object really) which means you could do this: Template.documents.events({ 'click #dontShowThisDocument': function () { var excluded = Session.get('excludedDocument'); if ( excluded ) excluded.push(this._id); else excluded = [ this.id ]; Session.set('excludedDocument',excluded); } }); Template.documents.helpers({ lists: function () { return Coll.find({ _id: { $nin: Session.get('excludedDocument') }); } });
[ "stackoverflow", "0048637347.txt" ]
Q: ImportError: cannot import name 'gutenburg' I have downloaded NLTK package already.I have gutenburg module in nltk_data also from nltk.corpus import gutenburg sample=gutenburg.raw("bible.kjv.txt") print(sample[0:10]) A: Probably the name is gutenberg instead of gutenburg.
[ "stackoverflow", "0059861195.txt" ]
Q: Is there a native function to generate an array index based on column value? I would like to know if there is a native function in PHP for generating an array index based on one of it's column value. For example this: Array ( [0] => Array ( [id] => 5 [title] => Product 1 ) [1] => Array ( [id] => 12 [title] => Product 2 ) ) Would become this: Array ( [5] => Array ( [id] => 5 [title] => Product 1 ) [12] => Array ( [id] => 12 [title] => Product 2 ) ) A: Yes, it's possible. You can use array_column() function to achieve this by passing the index parameter which is the 3rd parameter, which is id in your case. Snippet: <?php $arr = array ( array ( 'id' => 5, 'title' => 'Product 1' ), array ( 'id' => 12, 'title' => 'Product 2' ) ); print_r(array_column($arr,NULL,'id')); Demo: https://3v4l.org/MU2SK
[ "stackoverflow", "0059859862.txt" ]
Q: Restrict insecure web socket protocol connections in PCF We are hosting an application in the preprod azure PCF environment which exposes websocket endpoints for client devices to connect to. Is there a prescribed methodology to secure the said websocket endpoint using TLS/SSL when hosted on PCF and running behind the PCF HAProxy? I am having trouble interpreting this information, as in, are we supposed to expose port 4443 on the server and PCF shall by default pick it up to be a secure port that ensures unsecured connections cannot be established? Or does it require some configuration to be done on HAProxy? A: Is there a prescribed methodology to secure the said websocket endpoint using TLS/SSL when hosted on PCF and running behind the PCF HAProxy? A few things: You don't need to configure certs or anything like that when deploying your app to PCF. The platform takes care of all that. In your case, it'll likely be handled by HAProxy, but it could be some other load balancer or even Gorouter depending on your platform operations team installed PCF. The net result is that TLS is first terminated before it hits your app, so you don't need to worry about it. Your app should always force users to HTTPS. How you do this depends on the language/framework you're using, but most have some functionality for this. This process generally works by checking to see if the incoming request was over HTTP or HTTPS. If it's HTTP, then you issue a redirect to the same URL, but over HTTPS. This is important for all apps, not just ones using WebSockets. Encrypt all the things. Do keep in mind that you are behind one or more reverse proxies, so if you are doing this manually, you'll need to consider what's in x-forwarded-proto or x-forwarded-port, not just the upstream connection which would be Gorouter, not your client's browser. https://docs.pivotal.io/platform/application-service/2-7/concepts/http-routing.html#http-headers If you are forcing your user's to HTTPS (#1 above), then your users will be unable to initiate an insecure WebSocket connection to your app. Browsers like Chrome & Firefox have restrictions to prevent an insecure WebSocket connection from being made when the site was loaded over HTTPS. You'll get a message like The operation is insecure in Firefox or Cannot connect: SecurityError: Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS. in Chrome. I am having trouble interpreting this information, as in, are we supposed to expose port 4443 on the server and PCF shall by default pick it up to be a secure port that ensures unsecured connections cannot be established? Or does it require some configuration to be done on HAProxy? From the application perspective, you don't do anything different. Your app is supposed to start and listen on the assigned port, i.e. what's in $PORT. This is the same for HTTP, HTTP, WS & WSS traffic. In short, as an app developer you don't need to think about this when deploying to PCF. The only exception would be if your platform operations team uses a load balancer that does not natively support WebSockets. In this case, to work around the issue they need to separate traffic. HTTP and HTTPS go on the traditional ports 80 and 443, and they will route WebSockets on a different port. The PCF docs recommend 4443, which is where you're probably seeing that port. I can't tell you if your platform is set up this way, but if you know that you're using HAproxy, it is probably not. https://docs.pivotal.io/platform/application-service/2-8/adminguide/supporting-websockets.html At any rate, if you don't know just push an app and try to initiate a secure WebSocket connection over port 443 and see if it works. If it fails, try 4443 and see if that works. That or ask your platform operations team. For what it's worth, even if your need to use port 4443 there is no difference to your application that runs on PCF. The only difference would be in your Javascript code that initiates the WebSocket connection. It would need to know to use port 4443 instead of the default 443. Hope that helps!
[ "stackoverflow", "0004185061.txt" ]
Q: Android Python Programming Can I program for Android using Python? I seem to have stumbled upon many links while searching... however neither of them is concrete. Any suggestions? I want to write apps for Android but really don't want to get into Java for all this. PS: My question is whether I can write proper, full fledged apps for Android. A: Checkout Kivy. They have done a really great job so far, and I am a big fan of their work. It is still lacking some providers, but they keep adding new stuff to it everyday. First thing you need to do is to check your requirement against what they can offer based on their documentation. They have create an amazing framework for input such as multi-touch or pen handling. They use OpenGL ES internally, as a result complex graphics and visualizations can run very fast when interacting with the the application. Their process for creating an apk is also very straight forward. A: Check the new Python for Android project. Edit: This is not Kivy, this is a seperate project, intended to be a toolchain usable for other toolkit. The architecture is modular, and you can include new recipe for including new python extensions (as brew, macports, cygwin etc.). Edit: This is not Py4A, but python-for-android. A: This is great for starters: Embed Python 2.7 interpreter and your scripts into an Android APK
[ "stackoverflow", "0004186015.txt" ]
Q: Xerces2-j XML Schema Attribute / Element Declaration data type I'm using Apache's Xerces2-j to parse my XSD. I am trying to get the datatype information for the element / attribute declarations in the XSD. Here's an example XSD: <xs:element name="Pretzel"> ... <xs:attribute name="Flavor" type="xs:string"/> <xs:attribute name="ProductID" type="xs:nonNegativeInteger"/> ... </xs:element> In this case, I'd want to get the datatypes of the Flavor and ProductID attributes. According to the W3C Schema API and its Xerces2-j implementation, XSAttributeDeclaration's getActualVCType() will get me what I want. But for me that method always returns 45, which is UNAVAILABLE_DT. Is this a bug in Xerces2-j, or am I just understanding the API wrong? If I am, I'd appreciate if someone could point me to the right direction here. A: You are looking to use the method XSAttributeDeclaration.getTypeDefinition(); // returns XSSimpleTypeDefinition for simple types and/or possibly XSAttributeDeclaration.getEnclosingCTDefinition(); // returns XSComplexTypeDefinition for complex types. The method getActualVCType() is deprecated, and its alternative call getValueConstraintValue().getActualValueType() looks into a so-called value constraint which is not what you are looking for. This argument is also supported by the code in XSAttributeDecl.java: // variable definition 48 // value constraint type: default, fixed or !specified 49 short fConstraintType = XSConstants.VC_NONE; and 183 public short getActualVCType() { 184 return getConstraintType() == XSConstants.VC_NONE ? 185 XSConstants.UNAVAILABLE_DT : 186 fDefault.actualValueType; 187 } with 136 137 public short getConstraintType() { 138 return fConstraintType; 139 } suggests that you are indeed getting UNAVAILABLE_DT because it is not set. I suggest looking into the XSSimpleTypeDefinition's methods, it looks promising to me.
[ "stackoverflow", "0051259462.txt" ]
Q: Constructing chrono::time_point Given two split values, seconds since epoch and µs, is one of the following preferable? auto timestamp = system_clock::time_point(seconds(time_seconds) + microseconds(time_us)); or auto timestamp = system_clock::time_point(seconds(time_seconds)) + microseconds(time_us); A: It does not matter at all which one of those two you choose. It does however pay to have time_seconds and time_us as 64-bit integers--this cuts the whole operation from 5 instructions to 3 on x86_64. See: https://godbolt.org/g/8u1pYn