_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d5501
train
homePhone = a01.PID.GetPhoneNumberHome(0).TelecommunicationUseCode.Value; businessPhone = a01.PID.GetPhoneNumberBusiness(0).TelecommunicationUseCode.Value;
unknown
d5502
train
You can do following things to gather some more information, * *Your report must include operating system. *Version and screen size. *DPI information, most users set high font size, this probably will change dpi to little bit causing controls to render little differently. *WPF version, and also check default dependency property values. You may assume that you have set ticks to false but it may be true by default, or if your xaml is running within some other app and resources might set it to true. *Users may only use keyboard, and check how keyboard behaves for these controls. *Users may double click, lots of users have habit of double clicking everything (buttons, links) *In smaller screen sizes, your controls may be out of views, this is very unlikely as you are receiving max values. Or even on big screens, changing text size may cause layout to hide your controls. A: It's hard to know for sure if the classic theme is the issue, but I've had a LOT of issues with various themes and WPF. For example, projecting (to an external display) with the Aero theme almost always will eventually cause some quirky behavior with WPF. I've also had similar issues that seemed to manifest more on certain video cards than others. And don't get me started on LiveMeeting and WPF :-) Definitely test classic theme, and make sure you test on XP too.
unknown
d5503
train
As mentioned in the comments, case_when is a helpful alternative to many nested ifelse calls: library(dplyr) # Create sample dataset df <- data.frame(cough = c(1, 0, 0, 0, 0, 0, 0, 1), fever = c(0, 1, 0, 0, 0, 0, 0, 1), diarrhea = c(0, 0, 1, 0, 0, 0, 0, 1), dyspnea = c(0, 0, 0, 1, 0, 0, 0, 1), neurologic = c(0, 0, 0, 0, 1, 0, 0, 0), otherSymp = c(0, 0, 0, 0, 0, 1, 0, 0)) # Create categorical variable df |> mutate(symptom = case_when(cough == 1 ~ "cough", fever == 1 ~ "fever", diarrhea == 1 ~ "diarrhea", dyspnea == 1 ~ "dyspnea", neurologic == 1 ~ "neurologic", otherSymp == 1 ~ "other", TRUE ~ "none")) Output #> cough fever diarrhea dyspnea neurologic otherSymp symptom #> 1 1 0 0 0 0 0 cough #> 2 0 1 0 0 0 0 fever #> 3 0 0 1 0 0 0 diarrhea #> 4 0 0 0 1 0 0 dyspnea #> 5 0 0 0 0 1 0 neurologic #> 6 0 0 0 0 0 1 other #> 7 0 0 0 0 0 0 none #> 8 1 1 1 1 0 0 cough Created on 2022-07-11 by the reprex package (v2.0.1) However, this is a very basic solution, which assumes that you can't have more than one symptom (unreasonable) - if you have more than one, symptom will only mention the first.
unknown
d5504
train
If in doubt check the manual That will tell you that define('DB_Name', 'wp'); define('DB_User', 'root'); Should be define('DB_NAME', 'wp'); define('DB_USER', 'root');
unknown
d5505
train
You're probably adding the event listener each time you send the request. If you do, you should remove the listener when it finally runs, or just add it once.
unknown
d5506
train
First of all you should use debugElement of your fixture which will give you some useful methods for testing. One is triggerEventHandler which will help you with your issue (and just to mention: query would be another method that you will probably want to use often since it's way more powerful than querySelector and will return again a debugElement). let button: DebugElement = fixture.debugElement.query(By.css('.tl-slidenav-next .tl-slidenav-content-container')); button.triggerEventHandler('click', null); // where null is the event being passed if it's used in the listener Hope it helps.
unknown
d5507
train
I add the import, but get the same problem. I'm testing with the Expectations package 2.0.9, trying to import deftype Node and interface INode. In core.clj: (ns linked-list.core) (definterface INode (getCar []) (getCdr []) (setCar [x]) (setCdr [x])) (deftype Node [^:volatile-mutable car ^:volatile-mutable cdr] INode (getCar[_] car) (getCdr[_] cdr) (setCar[_ x] (set! car x) _) (setCdr[_ x] (set! cdr x) _)) In core_test.clj: (ns linked-list.core-test (:require [expectations :refer :all] [linked-list.core :refer :all]) (:import [linked-list.core INode] [linked-list.core Node])) and the output from lein autoexpect: *************** Running tests *************** Error refreshing environment: java.lang.ClassNotFoundException: linked-list.core.INode, compiling:(linked_list/core_test.clj:1:1) Tests completed at 07:29:36.252 The suggestion to use a factory method, however, is a viable work-around. A: Because deftype generates a class, you will probably need to import that Java class in techne.scrub-test with (:import [techne.scrub Scrub]) in your ns definition. I actually wrote up this same thing with respect to defrecord here: * *http://tech.puredanger.com/2010/06/30/using-records-from-a-different-namespace-in-clojure/ Another thing you could do would be to define a constructor function in scrub: (defn new-scrub [state] (Scrub. state)) and then you would not need to import Scrub in test-scrub.
unknown
d5508
train
OnNavigatedTo happens to early in the page lifetime for setting the focus to work. You should call your code in the Loaded event: private void MainPage_OnLoaded(object sender, RoutedEventArgs e) { if (string.IsNullOrWhiteSpace(textBoxGroupName.Text)) { textBoxGroupName.Focus(FocusState.Programmatic); } } Of course you need to setup the handler in your .xaml file (I've omitted the other attributes in the Page element: <Page Loaded="MainPage_OnLoaded"> A: Only controls that are contained within the GroupBox control can be selected or receive focus. Seems like you are not using GroupBox correctly. From MSDN The complete GroupBox itself cannot be selected or receive focus. For more information about how this control responds to the Focus and Select methods, see the following Control members: CanFocus, CanSelect, Focused, ContainsFocus, Focus, Select. Hint: You maybe want to use the Controls property to access the child controls: if (string.IsNullOrWhiteSpace(textBoxGroupName.Text)) { var child_TextBox = textBoxGroupName.Controls["myTextBox"] if(child_TextBox.CanFocus) child_TextBox.Focus(FocusState.Programmatic); }
unknown
d5509
train
I would imagine there are a number of different thoughts about this, but here is one simple approach if it helps. fit_0_obj <- ggsurvplot(fit_0) ggplot(survival_ext,aes(x=time, y=value, color=variable)) + geom_line() + labs(x="Time", y="Survival probability", color="") + geom_step(data = fit_0_obj$data.survplot, aes(x=time, y=surv, color=group)) Edit (9/20/21): With a bug in the survminer package, the "group" in the bc data needs to be character and not a factor. Until fixed, you can do the following to reproduce the plot: bc$group <- as.character(bc$group)
unknown
d5510
train
There are several ways to solve your problem: * *try to use more common parameters for your methods that requires string's, int's or custom classes instead. Is it really necessary to add a framework specific class or function or is there a better option? *You can use a multi-target configuration for your library which then requires #if NET45 and #elif NETSTANDARD2_0 code everywhere you have to use different logic for different frameworks. This could lead to not very well readable code. *Use two libraries, one for .NET Core apps (e.g. based on .NET Standard 2.1) and the other for .NET Framework (e.g. .NET FW 4.8). The .cs files from the .NET Standard library can then also be used in the .NET 4.8 library (if compatible features have been used). The .cs files can be selected e.g. in VS via "context menu > add existing element". When confirming the selected file(s), expand the dropdown option under "Add" and select "Add as Link". This way the file only needs to be maintained once (changes are applied in both libraries). Framework-specific files can then be added individually in the respective library, not as a link. Here's a good article about it. These are just some examples, there might be of course other or better solutions to it. Personally I would try to use independent arguments for my methods, if this is not possible I prefer the custom library solution for each framework version.
unknown
d5511
train
This warning comes up when you are using a Set without type specifier. So new HashSet(); instead of new HashSet<String>(); It shows up because the compiler can't check that you are using the Set in a type-safe way. If you specify the type of the objects you are storing the warning will go away: Replace HashSet<String> conjuntos = new HashSet(); with HashSet<String> conjuntos = new HashSet<>(); More details can be found here: https://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html
unknown
d5512
train
I've found the issues. (1) The vectors were defined from the wrong origin (top left corner of the page instead of the shape center). (2) Math.acos returns results in the range range [0,pi] instead of [0,2*pi]. It should be fixed by (360 - degrees) when the mouse moves to the left and passes the shape center. The codepen with fixed version: https://codepen.io/1rosehip/pen/JjWwaYE const $box = document.getElementById('box'); const shapeRect = $box.getBoundingClientRect(); const shapeCenterX = shapeRect.x + shapeRect.width / 2; const shapeCenterY = shapeRect.y + shapeRect.height / 2; /** * get vector magnitude * @param {Array.<number>} v * @return {number} */ const length = v => { return Math.sqrt(v[0] ** 2 + v[1] ** 2); }; /** * dot product * @param {Array.<number>} v1 * @param {Array.<number>} v2 * @return {number} */ const dot = (v1, v2) => { return v1[0] * v2[0] + v1[1] * v2[1]; }; /** * handle rotation */ document.addEventListener('mousemove', (evt) => { // vector #1 - shape center const centerVector = [evt.pageX - shapeCenterX, 0 - shapeCenterY]; const centerVectorLength = length(centerVector); // vector #2 - mouse position const mouseVector = [evt.pageX - shapeCenterX, evt.pageY - shapeCenterY]; const mouseVectorLength = length(mouseVector); // cos(angle) = dot(a, b) / (length(a) * length(b)) const radians = Math.acos(dot(centerVector, mouseVector) / (centerVectorLength * mouseVectorLength)); let degrees = radians * (180 / Math.PI); // const angle = (degrees + 360) % 360; if(evt.pageX < shapeCenterX){ degrees = 360 - degrees; } $box.style.transform = `rotate(${degrees}deg)`; }); #box{ position: absolute; background: #111; left: 100px; top: 100px; width: 100px; height: 100px; } <div id="box"></div>
unknown
d5513
train
I couldn't found any major issue on your code. I've tried to run your code inside one of my Android project. To avoid NetworkOnMainThreadException I've run the code snippet inside a thread. Then run it and found the expected response header in the log. Possible Solutions (What can you do now?) * *Try run my callApi() method inside your project. *Change your url to https://pagalworld.com.se/siteuploads/files/sfd14/6934/Har%20Har%20Shambhu%20Ringtone_320(PagalWorld.com.se).mp3 (replaced SPACE with %20). There is a chance for BAD request with white space URL. Here is the significant output I/System.out: ConnHeadRes: null HTTP/1.1 200 OK I/System.out: ConnHeadRes: Accept-Ranges bytes I/System.out: ConnHeadRes: Age 693 I/System.out: ConnHeadRes: CF-Cache-Status HIT I/System.out: ConnHeadRes: CF-RAY 73f0ccbd1a5169b1-DAC I/System.out: ConnHeadRes: Connection keep-alive I/System.out: ConnHeadRes: content-disposition attachment I/System.out: ConnHeadRes: Content-Length 1221768 I/System.out: ConnHeadRes: Content-Type application/octet-stream I/System.out: ConnHeadRes: Date Tue, 23 Aug 2022 03:35:42 GMT I/System.out: ConnHeadRes: Expect-CT max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" I/System.out: ConnHeadRes: last-modified Thu, 11 Aug 2022 14:41:49 GMT I/System.out: ConnHeadRes: NEL {"success_fraction":0,"report_to":"cf-nel","max_age":604800} I/System.out: ConnHeadRes: Report-To {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=nywwKM746VO8KiwrIJAIq6hoJ1D8eJphddRHtpP%2BkXxWPQCJayYi23um4V7mlUXd4kdWOXN%2FrXrTN6NA7sZWa%2BzU4L6tCx2v28VAkH51TPNfDVbeHGTHgwY8PCuulIdN3ek%2FloEn"}],"group":"cf-nel","max_age":604800} I/System.out: ConnHeadRes: Server cloudflare I/System.out: ConnHeadRes: Strict-Transport-Security max-age=15552000; includeSubDomains; preload I/System.out: ConnHeadRes: Vary Accept-Encoding I/System.out: ConnHeadRes: X-Android-Received-Millis 1661225741490 I/System.out: ConnHeadRes: X-Android-Response-Source NETWORK 200 I/System.out: ConnHeadRes: X-Android-Selected-Protocol http/1.1 I/System.out: ConnHeadRes: X-Android-Sent-Millis 1661225741442 I/System.out: ConnHeadRes: x-content-type-options nosniff I/System.out: ConnHeadRes: x-nginx-upstream-cache-status MISS What I've changed in the code? * *Run the code inside a thread *Update USER_AGENT_REQUEST_HEADER field and value. *Get response headers in a Map object. *Iterate the Map object and print key-value in log. Here is the code sample: void callApi() { Thread thread = new Thread(() -> { try { String url2 = "https://pagalworld.com.se/siteuploads/files/sfd14/6934/Har Har Shambhu Ringtone_320(PagalWorld.com.se).mp3"; String req_method = "HEAD"; HttpsURLConnection conn = null; try { System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); URL UrlConnection = new URL(url2); conn = (HttpsURLConnection) UrlConnection.openConnection(); String host = UrlConnection.getHost() + ":80"; conn.setRequestMethod(req_method); conn.setRequestProperty("Host", host); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Connection", "keep-alive"); conn.setRequestProperty("user-agent", "android"); System.out.println("Host:Port = " + host); Map<String, List<String>> data = conn.getRequestProperties(); System.out.println("Connection code : " + conn.getResponseCode()); System.out.println("Connection Msg : " + conn.getResponseMessage()); for (String key : data.keySet()) { System.out.println(key + " " + data.get(key)); } Map<String, List<String>> responseHeader = conn.getHeaderFields(); for (Map.Entry<String, List<String>> entry : responseHeader.entrySet()) { for (String value: entry.getValue()) { System.out.println("ConnHeadRes: " + entry.getKey() + " " + value); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { conn.disconnect(); } } catch (Exception e) { e.printStackTrace(); } }); thread.start(); } So, as far I understand I can say, there is no issue in your code.
unknown
d5514
train
As Daniel indicated, you are instantiating a new object to the obj reference instead of the array element. Instead, access the array by ordinal: var array:Array = [{}, {}, {}]; for (var i:uint = 0; i < array.length; i++) { array[i] = {}; }
unknown
d5515
train
$('#myElement').animate({ backgroundColor: 'red'}).animate({ backgroundColor: 'white'}, 4000); play_multi_sound('tone-myElement'); is the same as: var toneId2nd = 'myElement'; $('#'+toneId2nd).animate({ backgroundColor: 'red'}).animate({ backgroundColor: 'white'}, 4000); play_multi_sound('tone-'+toneId2nd); toneId2nd is just a supplied variable. jQuery uses CSS selectors to grab elements. I suggest you start here if you need more help with jQuery. A: it is the Id of the Element $('#ElementId') toneId2nd is some kind of element ID Ex: $('#mydiv') A: See the answer on this question : using variables within a jquery selector And maybe try to do some research before asking? ;)
unknown
d5516
train
You could try setting the enabled property on the other gesture recogniser to NO. I don't have my dev environment up at the moment but I recall having done something similar before. Like so: - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizershouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{ otherGestureRecognizer.enabled = NO; return YES; } A: You can also try this, and it solved my problem. - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{ if ([otherGestureRecognizer isKindOfClass:[UIScreenEdgePanGestureRecognizer class]]) { // replace `UIScreenEdgePanGestureRecognizer` with any class you don't need. return NO; } return YES; } Good luck. :)
unknown
d5517
train
What is your server? Is it apache or Ngnix? Rewrite engine won't work with ngnix, you may have to update the ngnix conf files for this to work.
unknown
d5518
train
You can make a Customer Group. Stores > Other Setting and select Customer Group. Add new customer group. Go To Cart Rule please follow. Marketing > Select Cart Price Rule > Add New Rule. now without using coupon and select free shipping in magento for that customer group . Thanks A: Easiest thing comes to my mind is Coupon code that he'll use everytime, with 1-year validity.
unknown
d5519
train
The improvement that I recommend is removal of unnecessary tasks being performed, notably how your code updates the pane being drawn on, even when there aren't changes. The following update reduced CPU usage from 12% to 0% (static frame): Timer time = new Timer(1000 / 20, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean refresh = false; switch (verticalMovement) { case UP: s2.changeY(UP); refresh = true; break; case DOWN: s2.changeY(DOWN); refresh = true; break; default: break; } switch (horizontalMovement) { case RIGHT: s2.changeX(RIGHT); refresh = true; break; case LEFT: s2.changeX(LEFT); refresh = true; break; default: break; } if (refresh == true) { pane.repaint(); } } });
unknown
d5520
train
In your controller you get all of the comments, but in an actual todo item you just want the comments for that item. This can be done with: todo.project_todo_comments The easiest way to solve: - <% @comments.each do |comment| %> - <%= comment.comment %> - <% end %> + <% todo.project_todo_comments.each do |comment| %> + <%= comment.comment %> + <% end %> You can remove the line from your controller: - @comments = @project.project_todo_comments However in your form (where you create a comment) you use the wrong ID for the todo item: - <%= f.hidden_field :project_todo_id, :value => @project_todo.id %> + <%= f.hidden_field :project_todo_id, :value => todo.id %> By the way, I would just name those models: Todo and Comment, there is no point using that long modelnames. You define those associations in the start of your model, so if someone would read it, he/she would see it instantly. For example see myself, I knew what was the purpose of your models still misused the namings, cause of too long classnames.
unknown
d5521
train
.offset returns pixel values relative to the document. It is entirely possible for this method to return float values as not all sizes are pixel integers, for example: Consider this HTML: <div style="position: absolute; left: 33%;"></div> The following command for me (for me): console.log($("div").offset().left); // Outputs 276.203125 jsFiddle of the above. However, it is important to note the yellow box on the linked page: jQuery does not support getting the offset coordinates of hidden elements or accounting for borders, margins, or padding set on the body element. While it is possible to get the coordinates of elements with visibility:hidden set, display:none is excluded from the rendering tree and thus has a position that is undefined A: It gets you the offsets of the element relative to the document! You can learn more here: http://api.jquery.com/offset/ A: You can get the css values via $("#11a").css("top").replace("px", ""); // You have to remove the 'px' it returns
unknown
d5522
train
Try stripping out the whitespaces before doing the palindrome check >>> x = "nurses run" >>> x.replace(" ", "") 'nursesrun' A: You can use reversed: def palindrome(word): if ' ' in word: word = word.replace(' ', '') palindrome = reversed(word) for letter, rev_letter in zip(word, palindrome): if letter != rev_letter: return 'Not Palindrome' return 'Palindrome' A: Your code is still incorrect in the elif statement. You've added return True when you should actually be returning the response from your recursive call as previously mentioned. def is_palindrome(word): if len(word) <= 2 and word[0] == word[-1]: return True elif word[0] == word[-1]: return is_palindrome(word[1:-1]) else: return False A: Here's a simpler solution of your problem: import sys sys.argv = [" nurses ", " run "] word = "".join([s.strip() for s in sys.argv]) print("{} {} palindrome".format(word, "is" if word == word[::-1] else "is not")) or you can just create the word out of sys.argv like this: word = "".join(sys.argv).replace(" ","")
unknown
d5523
train
To HIDE the button, remove the $("#") and just do button_canton.toggle(); To TOGGLE the map try this - it only makes the map once const $myMap = $("#myMap"); $("#Limite_cantonales").click(function() { if ($myMap.children()) $myMap.toggle() else { $.getJSON("canton.geojson", function(data) { $myMap.show() var limite_canton = L.geoJSON(data, { onEachFeature: function onEachFeature(feature, layer) { layer.bindPopup('<strong>' + feature.properties.NAME); } }).addTo($myMap); }); } }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <div id="info" class="info"> <button id="Limite_CH">Frontières nationales</button> </div> <div id="myMap" hidden></div>
unknown
d5524
train
As with all actions you need the correct permissions, in this case user_actions.fitness So the data returned from /me/fitness.runs for Nike will look like { "data": [ { "id": "10101118696330517", "from": { "name": "Philippe Harewood", "id": "13608786" }, "start_time": "2013-03-22T23:15:56+0000", "end_time": "2013-03-22T23:26:36+0000", "publish_time": "2013-03-24T15:50:00+0000", "application": { "name": "Nike", "namespace": "nikeapp", "id": "84697719333" }, "data": { "course": { "id": "476811255725972", "url": "http://nikeplus.nike.com/plus/activity/running/detail/2118587303?external_share_id=CE32E1C4-93D8-48A7-A08F-6D5B4C13EE6A&is_new_meta=true", "type": "fitness.course", "title": "1.12 miles" } }, "type": "fitness.runs", "no_feed_story": false, "likes": { "count": 0, "can_like": true, "user_likes": false }, "comments": { "count": 0, "can_comment": true, "comment_order": "chronological" } }, { "id": "10101118696155867", "from": { "name": "Philippe Harewood", "id": "13608786" }, "start_time": "2013-03-19T22:03:32+0000", "end_time": "2013-03-19T22:18:37+0000", "publish_time": "2013-03-24T15:49:46+0000", "application": { "name": "Nike", "namespace": "nikeapp", "id": "84697719333" }, "data": { "course": { "id": "502469216483599", "url": "http://nikeplus.nike.com/plus/activity/running/detail/2118587302?external_share_id=EBF6BC1D-BDEA-4EE5-B18D-FBC576610F13&is_new_meta=true", "type": "fitness.course", "title": "1.49 miles" } }, "type": "fitness.runs", "no_feed_story": false, "likes": { "count": 0, "can_like": true, "user_likes": false }, "comments": { "count": 0, "can_comment": true, "comment_order": "chronological" } } ], "paging": { "next": "https://graph.facebook.com/13608786/fitness.runs?limit=25&offset=25&__after_id=10101118696155867" } }
unknown
d5525
train
Like @AKX mentioned, newest version of clean-webpack-plugin doesn't accept array argument anymore. The path which should be clearing is reading from webpack's output.path. In your example code it's here: output: { path: path.join(__dirname, 'dist'), // rest of code }, You should be very carefull, because someones still use pattern like this: output: { path: __dirname, filename: './dist/bundle.js' }, Above configuration will cause removing all files in your project! If you need to clear only some files from webpack's output.path you should set cleanOnceBeforeBuildPatterns field in object passed into CleanWebpackPlugin constructor. A: As you can see from the page the error message links, CleanWebpackPlugin does not accept two arguments as you're passing in: new CleanWebpackPlugin(['dist'], {}), Instead, just try new CleanWebpackPlugin(), if you don't need to pass in any options. You may be seeing this problem if you're, say, following an older tutorial or such which uses a different version of the plugin, and the interface has changed meanwhile.
unknown
d5526
train
That's typically called a portable application.
unknown
d5527
train
The issue is in your getCardType() function. You wrote: getCardType(card) { return card.getElementsByClassName('match-value')[0].src; } It should be: getCardType(card){ return document.getElementsByClassName('match-value')[0].src; // ^--- you wrote 'card' here }
unknown
d5528
train
You can use multi indexing in panda, first you need to get header row index for each sheet. header_indexes = get_header_indexes(excel_filepath, sheet_index) #returns list of header indexes You need to write get_header_indexes function which scans sheet and return header indexes. you can use panda to get JSON from dataframe. import pandas as pd df = pd.read_excel(excel_filepath, header=header_indexes, sheet_name=sheet_index) data = df.to_dict(orient="records") for multiple headers data containts list of dict and each dict has tuple as key, you can reformat it to final JSON as per your requirement. Note: Use chunksize for reading large files.
unknown
d5529
train
If you tell the NSPredicateEditor that it cannot remove all the rows in the editor, then the editor will automatically remove the (-) button when necessary. You can do this by unchecking the "Can Remove All Rows" checkbox when editing the predicate editor in a xib, or by doing it programmatically with the -setCanRemoveAllRows: method.
unknown
d5530
train
If you don't mind installing another MySQL server via Homebrew, I have posted the complete solution in another thread: Installing RMySQL in mavericks But in your case, I do find those directories in XAMPP that contain the same necessary MySQL header and library files as those installed via Homebrew. So you can set the environment variables and build in the Terminal way: % export PKG_CPPFALGS="-I/Applications/XAMPP/xamppfiles/include" % export PKG_LIBS="-L/Applications/XAMPP/xamppfiles/lib -lmysqlclient" ## RMySQL_x.x-x.tar is the source package you have manually downloaded % R CMD INSTALL RMySQL_x.x-x.tar or in the RStudio way: > Sys.setenv(PKG_CPPFLAGS = "-I/Applications/XAMPP/xamppfiles/include") > Sys.setenv(PKG_LIBS = "-L/Applications/XAMPP/xamppfiles/lib -lmysqlclient") ## It will automatically download the source package in the remote repo > install.packages("RMySQL", type = "source")
unknown
d5531
train
* *It should be fine. Realm Objects are live links to their parent Realm object, not static copies, so their addresses do periodically change. This is normal, and the objects aren't getting re-allocated so you shouldn't see any memory issues here. As far as I'm aware, NSData itself is lazy, so the data won't actually be read until you explicitly request it. *Your architecture looks good! You're right in that it's usually not the best form to store file data directly inside a Realm file, but you've done a good job at making the Realm Object manage the external file data as if it was. :)
unknown
d5532
train
From @camickr's comment in my question: You should be able to write your own layout manager. Just copy the FlowLayout and replace the logic that centers the component within the row, to position the component at the top. In FlowLayout, in moveComponents method, there is this line: cy = y + (height - m.height) / 2; Changing the line to: cy = y; achieves what I want. It probably breaks the flowLayout.setAlignOnBaseline functionality. But I don't use it anyway. Layout code (WrapLayout and custom FlowLayout combined): public class WrapAndAlignHorizontallyTopLayout implements LayoutManager, java.io.Serializable { /** * This value indicates that each row of components should be left-justified. */ public static final int LEFT = 0; /** * This value indicates that each row of components should be centered. */ public static final int CENTER = 1; /** * This value indicates that each row of components should be right-justified. */ public static final int RIGHT = 2; /** * This value indicates that each row of components should be justified to the * leading edge of the container's orientation, for example, to the left in * left-to-right orientations. * * @see java.awt.Component#getComponentOrientation * @see java.awt.ComponentOrientation * @since 1.2 */ public static final int LEADING = 3; /** * This value indicates that each row of components should be justified to the * trailing edge of the container's orientation, for example, to the right in * left-to-right orientations. * * @see java.awt.Component#getComponentOrientation * @see java.awt.ComponentOrientation * @since 1.2 */ public static final int TRAILING = 4; /** * <code>align</code> is the property that determines how each row distributes * empty space. It can be one of the following values: * <ul> * <li><code>LEFT</code> * <li><code>RIGHT</code> * <li><code>CENTER</code> * </ul> * * @serial * @see #getAlignment * @see #setAlignment */ int align; // This is for 1.1 serialization compatibility /** * <code>newAlign</code> is the property that determines how each row * distributes empty space for the Java 2 platform, v1.2 and greater. It can be * one of the following three values: * <ul> * <li><code>LEFT</code> * <li><code>RIGHT</code> * <li><code>CENTER</code> * <li><code>LEADING</code> * <li><code>TRAILING</code> * </ul> * * @serial * @since 1.2 * @see #getAlignment * @see #setAlignment */ int newAlign; // This is the one we actually use /** * The flow layout manager allows a seperation of components with gaps. The * horizontal gap will specify the space between components and between the * components and the borders of the <code>Container</code>. * * @serial * @see #getHgap() * @see #setHgap(int) */ int hgap; /** * The flow layout manager allows a seperation of components with gaps. The * vertical gap will specify the space between rows and between the the rows and * the borders of the <code>Container</code>. * * @serial * @see #getHgap() * @see #setHgap(int) */ int vgap; /** * If true, components will be aligned on their baseline. */ private boolean alignOnBaseline; /* * JDK 1.1 serialVersionUID */ private static final long serialVersionUID = -7262534875583282631L; /** * Constructs a new <code>FlowLayout</code> with a centered alignment and a * default 5-unit horizontal and vertical gap. */ public WrapAndAlignHorizontallyTopLayout() { this(CENTER, 5, 5); } /** * Constructs a new <code>FlowLayout</code> with the specified alignment and a * default 5-unit horizontal and vertical gap. The value of the alignment * argument must be one of <code>FlowLayout.LEFT</code>, * <code>FlowLayout.RIGHT</code>, <code>FlowLayout.CENTER</code>, * <code>FlowLayout.LEADING</code>, or <code>FlowLayout.TRAILING</code>. * * @param align the alignment value */ public WrapAndAlignHorizontallyTopLayout(int align) { this(align, 5, 5); } /** * Creates a new flow layout manager with the indicated alignment and the * indicated horizontal and vertical gaps. * <p> * The value of the alignment argument must be one of * <code>FlowLayout.LEFT</code>, <code>FlowLayout.RIGHT</code>, * <code>FlowLayout.CENTER</code>, <code>FlowLayout.LEADING</code>, or * <code>FlowLayout.TRAILING</code>. * * @param align the alignment value * @param hgap the horizontal gap between components and between the components * and the borders of the <code>Container</code> * @param vgap the vertical gap between components and between the components * and the borders of the <code>Container</code> */ public WrapAndAlignHorizontallyTopLayout(int align, int hgap, int vgap) { this.hgap = hgap; this.vgap = vgap; setAlignment(align); } /** * Gets the alignment for this layout. Possible values are * <code>FlowLayout.LEFT</code>, <code>FlowLayout.RIGHT</code>, * <code>FlowLayout.CENTER</code>, <code>FlowLayout.LEADING</code>, or * <code>FlowLayout.TRAILING</code>. * * @return the alignment value for this layout * @see java.awt.FlowLayout#setAlignment * @since JDK1.1 */ public int getAlignment() { return newAlign; } /** * Sets the alignment for this layout. Possible values are * <ul> * <li><code>FlowLayout.LEFT</code> * <li><code>FlowLayout.RIGHT</code> * <li><code>FlowLayout.CENTER</code> * <li><code>FlowLayout.LEADING</code> * <li><code>FlowLayout.TRAILING</code> * </ul> * * @param align one of the alignment values shown above * @see #getAlignment() * @since JDK1.1 */ public void setAlignment(int align) { this.newAlign = align; // this.align is used only for serialization compatibility, // so set it to a value compatible with the 1.1 version // of the class switch (align) { case LEADING: this.align = LEFT; break; case TRAILING: this.align = RIGHT; break; default: this.align = align; break; } } /** * Gets the horizontal gap between components and between the components and the * borders of the <code>Container</code> * * @return the horizontal gap between components and between the components and * the borders of the <code>Container</code> * @see java.awt.FlowLayout#setHgap * @since JDK1.1 */ public int getHgap() { return hgap; } /** * Sets the horizontal gap between components and between the components and the * borders of the <code>Container</code>. * * @param hgap the horizontal gap between components and between the components * and the borders of the <code>Container</code> * @see java.awt.FlowLayout#getHgap * @since JDK1.1 */ public void setHgap(int hgap) { this.hgap = hgap; } /** * Gets the vertical gap between components and between the components and the * borders of the <code>Container</code>. * * @return the vertical gap between components and between the components and * the borders of the <code>Container</code> * @see java.awt.FlowLayout#setVgap * @since JDK1.1 */ public int getVgap() { return vgap; } /** * Sets the vertical gap between components and between the components and the * borders of the <code>Container</code>. * * @param vgap the vertical gap between components and between the components * and the borders of the <code>Container</code> * @see java.awt.FlowLayout#getVgap * @since JDK1.1 */ public void setVgap(int vgap) { this.vgap = vgap; } /** * Sets whether or not components should be vertically aligned along their * baseline. Components that do not have a baseline will be centered. The * default is false. * * @param alignOnBaseline whether or not components should be vertically aligned * on their baseline * @since 1.6 */ public void setAlignOnBaseline(boolean alignOnBaseline) { this.alignOnBaseline = alignOnBaseline; } /** * Returns true if components are to be vertically aligned along their baseline. * The default is false. * * @return true if components are to be vertically aligned along their baseline * @since 1.6 */ public boolean getAlignOnBaseline() { return alignOnBaseline; } /** * Adds the specified component to the layout. Not used by this class. * * @param name the name of the component * @param comp the component to be added */ @Override public void addLayoutComponent(String name, Component comp) { } /** * Removes the specified component from the layout. Not used by this class. * * @param comp the component to remove * @see java.awt.Container#removeAll */ @Override public void removeLayoutComponent(Component comp) { } /** * Returns the preferred dimensions for this layout given the <i>visible</i> * components in the specified target container. * * @param target the component which needs to be laid out * @return the preferred dimensions to lay out the subcomponents of the * specified container */ @Override public Dimension preferredLayoutSize(Container target) { return layoutSize(target, true); } /** * Returns the minimum dimensions needed to layout the <i>visible</i> components * contained in the specified target container. * * @param target the component which needs to be laid out * @return the minimum dimensions to lay out the subcomponents of the specified * container */ @Override public Dimension minimumLayoutSize(Container target) { Dimension minimum = layoutSize(target, false); minimum.width -= (getHgap() + 1); return minimum; } /** * Returns the minimum or preferred dimension needed to layout the target * container. * * @param target target to get layout size for * @param preferred should preferred size be calculated * @return the dimension to layout the target container */ private Dimension layoutSize(Container target, boolean preferred) { synchronized (target.getTreeLock()) { // Each row must fit with the width allocated to the containter. // When the container width = 0, the preferred width of the container // has not yet been calculated so lets ask for the maximum. int targetWidth = target.getSize().width; Container container = target; while (container.getSize().width == 0 && container.getParent() != null) { container = container.getParent(); } targetWidth = container.getSize().width; if (targetWidth == 0) targetWidth = Integer.MAX_VALUE; int hgap = getHgap(); int vgap = getVgap(); Insets insets = target.getInsets(); int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2); int maxWidth = targetWidth - horizontalInsetsAndGap; // Fit components into the allowed width Dimension dim = new Dimension(0, 0); int rowWidth = 0; int rowHeight = 0; int nmembers = target.getComponentCount(); for (int i = 0; i < nmembers; i++) { Component m = target.getComponent(i); if (m.isVisible()) { Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize(); // Can't add the component to current row. Start a new row. if (rowWidth + d.width > maxWidth) { addRow(dim, rowWidth, rowHeight); rowWidth = 0; rowHeight = 0; } // Add a horizontal gap for all components after the first if (rowWidth != 0) { rowWidth += hgap; } rowWidth += d.width; rowHeight = Math.max(rowHeight, d.height); } } addRow(dim, rowWidth, rowHeight); dim.width += horizontalInsetsAndGap; dim.height += insets.top + insets.bottom + vgap * 2; // When using a scroll pane or the DecoratedLookAndFeel we need to // make sure the preferred size is less than the size of the // target containter so shrinking the container size works // correctly. Removing the horizontal gap is an easy way to do this. Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target); if (scrollPane != null && target.isValid()) { dim.width -= (hgap + 1); } return dim; } } /* * A new row has been completed. Use the dimensions of this row to update the * preferred size for the container. * * @param dim update the width and height when appropriate * * @param rowWidth the width of the row to add * * @param rowHeight the height of the row to add */ private void addRow(Dimension dim, int rowWidth, int rowHeight) { dim.width = Math.max(dim.width, rowWidth); if (dim.height > 0) { dim.height += getVgap(); } dim.height += rowHeight; } /** * Centers the elements in the specified row, if there is any slack. * * @param target the component which needs to be moved * @param x the x coordinate * @param y the y coordinate * @param width the width dimensions * @param height the height dimensions * @param rowStart the beginning of the row * @param rowEnd the the ending of the row * @param useBaseline Whether or not to align on baseline. * @param ascent Ascent for the components. This is only valid if * useBaseline is true. * @param descent Ascent for the components. This is only valid if * useBaseline is true. * @return actual row height */ private int moveComponents(Container target, int x, int y, int width, int height, int rowStart, int rowEnd, boolean ltr, boolean useBaseline, int[] ascent, int[] descent) { switch (newAlign) { case LEFT: x += ltr ? 0 : width; break; case CENTER: x += width / 2; break; case RIGHT: x += ltr ? width : 0; break; case LEADING: break; case TRAILING: x += width; break; } int maxAscent = 0; int nonbaselineHeight = 0; int baselineOffset = 0; if (useBaseline) { int maxDescent = 0; for (int i = rowStart; i < rowEnd; i++) { Component m = target.getComponent(i); if (m.isVisible()) { if (ascent[i] >= 0) { maxAscent = Math.max(maxAscent, ascent[i]); maxDescent = Math.max(maxDescent, descent[i]); } else { nonbaselineHeight = Math.max(m.getHeight(), nonbaselineHeight); } } } height = Math.max(maxAscent + maxDescent, nonbaselineHeight); baselineOffset = (height - maxAscent - maxDescent) / 2; } for (int i = rowStart; i < rowEnd; i++) { Component m = target.getComponent(i); if (m.isVisible()) { int cy; if (useBaseline && ascent[i] >= 0) { cy = y + baselineOffset + maxAscent - ascent[i]; } else { cy = y; } if (ltr) { m.setLocation(x, cy); } else { m.setLocation(target.getWidth() - x - m.getWidth(), cy); } x += m.getWidth() + hgap; } } return height; } /** * Lays out the container. This method lets each <i>visible</i> component take * its preferred size by reshaping the components in the target container in * order to satisfy the alignment of this <code>FlowLayout</code> object. * * @param target the specified component being laid out * @see Container * @see java.awt.Container#doLayout */ @Override public void layoutContainer(Container target) { synchronized (target.getTreeLock()) { Insets insets = target.getInsets(); int maxwidth = target.getWidth() - (insets.left + insets.right + hgap * 2); int nmembers = target.getComponentCount(); int x = 0, y = insets.top + vgap; int rowh = 0, start = 0; boolean ltr = target.getComponentOrientation().isLeftToRight(); boolean useBaseline = getAlignOnBaseline(); int[] ascent = null; int[] descent = null; if (useBaseline) { ascent = new int[nmembers]; descent = new int[nmembers]; } for (int i = 0; i < nmembers; i++) { Component m = target.getComponent(i); if (m.isVisible()) { Dimension d = m.getPreferredSize(); m.setSize(d.width, d.height); if (useBaseline) { int baseline = m.getBaseline(d.width, d.height); if (baseline >= 0) { ascent[i] = baseline; descent[i] = d.height - baseline; } else { ascent[i] = -1; } } if ((x == 0) || ((x + d.width) <= maxwidth)) { if (x > 0) { x += hgap; } x += d.width; rowh = Math.max(rowh, d.height); } else { rowh = moveComponents(target, insets.left + hgap, y, maxwidth - x, rowh, start, i, ltr, useBaseline, ascent, descent); x = d.width; y += vgap + rowh; rowh = d.height; start = i; } } } moveComponents(target, insets.left + hgap, y, maxwidth - x, rowh, start, nmembers, ltr, useBaseline, ascent, descent); } } // // the internal serial version which says which version was written // - 0 (default) for versions before the Java 2 platform, v1.2 // - 1 for version >= Java 2 platform v1.2, which includes "newAlign" field // private static final int currentSerialVersion = 1; /** * This represent the <code>currentSerialVersion</code> which is bein used. It * will be one of two values : <code>0</code> versions before Java 2 platform * v1.2.. <code>1</code> versions after Java 2 platform v1.2.. * * @serial * @since 1.2 */ private int serialVersionOnStream = currentSerialVersion; /** * Reads this object out of a serialization stream, handling objects written by * older versions of the class that didn't contain all of the fields we use * now.. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); if (serialVersionOnStream < 1) { // "newAlign" field wasn't present, so use the old "align" field. setAlignment(this.align); } serialVersionOnStream = currentSerialVersion; } /** * Returns a string representation of this <code>FlowLayout</code> object and * its values. * * @return a string representation of this layout */ @Override public String toString() { String str = ""; switch (align) { case LEFT: str = ",align=left"; break; case CENTER: str = ",align=center"; break; case RIGHT: str = ",align=right"; break; case LEADING: str = ",align=leading"; break; case TRAILING: str = ",align=trailing"; break; } return getClass().getName() + "[hgap=" + hgap + ",vgap=" + vgap + str + "]"; } } Example code: public class WrapLayoutExample { public static void main(String[] args) { SwingUtilities.invokeLater(WrapLayoutExample::runGui); } private static void runGui() { JFrame frame = new JFrame("A"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(new WrapAndAlignHorizontallyTopLayout()); JLabel l = new JLabel("CCC"); l.setBorder(BorderFactory.createLineBorder(Color.red, 10)); l.setVerticalAlignment(JLabel.TOP); panel.add(l); for (int i = 0; i < 44; i++) { l = new JLabel("BBBB"); l.setBorder(BorderFactory.createLineBorder(Color.red, (int) (Math.random() * 50))); panel.add(l); } frame.setSize(300, 300); frame.setLayout(new BorderLayout()); frame.add(new JScrollPane(panel)); frame.setVisible(true); } } Result:
unknown
d5533
train
The NSubstitute API does not currently support this exactly (but it's a nice idea!). There is a hacky-ish way of doing it using the unofficial .ReceivedCalls extension: var calls = myMock.ReceivedCalls() .Count(x => x.GetMethodInfo().Name == nameof(myMock.MyMethod)); Assert.InRange(calls, 1, 5); The better way to do this using a custom Quantity from the NSubstitute.ReceivedExtensions namespace: // DISCLAIMER: draft code only. Review and test before using. public class RangeQuantity : Quantity { private readonly int min; private readonly int maxInclusive; public RangeQuantity(int min, int maxInclusive) { // TODO: validate args, min < maxInclusive. this.min = min; this.maxInclusive = maxInclusive; } public override string Describe(string singularNoun, string pluralNoun) => $"between {min} and {maxInclusive} (inclusive) {((maxInclusive == 1) ? singularNoun : pluralNoun)}"; public override bool Matches<T>(IEnumerable<T> items) { var count = items.Count(); return count >= min && count <= maxInclusive; } public override bool RequiresMoreThan<T>(IEnumerable<T> items) => items.Count() < min; } Then: myMock.Received(new RangeQuantity(3,5)).MyMethod(); (Note you will need using NSubstitute.ReceivedExtensions; for this.)
unknown
d5534
train
Assuming you're using the common controls there is the BCN_HOTITEMCHANGE notification code for the WM_NOTIFY message. The message includes the NMBCHOTITEM structure, which includes information for whether the mouse is entering or leaving the hover area. Here's an example: LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_NOTIFY: { LPNMHDR header = *reinterpret_cast<LPNMHDR>(lParam); switch (header->code) { case BCN_HOTITEMCHANGE: { NMBCHOTITEM* hot_item = reinterpret_cast<NMBCHOTITEM*>(lParam); // Handle to the button HWND button_handle = header->hwndFrom; // ID of the button, if you're using resources UINT_PTR button_id = header->idFrom; // You can check if the mouse is entering or leaving the hover area bool entering = hot_item->dwFlags & HICF_ENTERING; return 0; } } return 0; } } return DefWindowProcW(hwnd, msg, wParam, lParam); } A: You can check the code of the WM_NOTIFY message to see if it is a NM_HOVER message. switch(msg) { case WM_NOTIFY: if(((LPNMHDR)lParam)->code == NM_HOVER) { // Process the hover message } else if (...) // any other WM_NOTIFY messages you care about {} } A: You can use simply SFML to do this. Code: RectangleShape button; button.setPosition(Vector2f(50, 50)); button.setSize(Vector2f(100, 40)); button.setFillColor(Color::Green); if(button.getGlobalBounds().contains(static_cast<Vector2f>(Mouse::getPosition(/*your window name*/window) { button.setFillColor(Color::Red); }
unknown
d5535
train
You can generate chart in div, which will have negative margin. Then use getSVG() function and paste it ot svg element. http://api.highcharts.com/highcharts#Chart.getSVG() A: Unfortunately it is not suppored, highcharts renders the chart in additional divs and adds elements like labels/datalabels as html objects. But you can copy the SVG of highstock in you SVG. But you will lose all attached events. Like drag and drop, click .... Here an Example of it. http://jsfiddle.net/L6SA4/10/ $.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function(data) { // Create a hidden and not attached div container. var div = $('<div>This is an hidden unatached container.</div>'); // Create the chart div.highcharts('StockChart', { chart: { width: 480, height: 400, events: { load: function () { // If hidden div was generated, take the svg content and put it into svg. var stockSvg = $('svg', this.container); var svgObj = $('#mySvg').svg(); // Force position of highstock stockSvg.attr('x', 20); stockSvg.attr('y', 30); // Replace ugly rect with highstock $('#container', svgObj).replaceWith(stockSvg); } } }, series : [{ name : 'AAPL', data : data, tooltip: { valueDecimals: 2 } }] }); });
unknown
d5536
train
After a day and a half, I managed to make it work. The working code: Import Class: namespace App\Imports; use Maatwebsite\Excel\Concerns\ToCollection; use Maatwebsite\Excel\Concerns\WithHeadingRow; use Maatwebsite\Excel\Facades\Excel; use App\User; class TimesheetsImport implements ToCollection, WithHeadingRow { public $data; public function collection($rows) { $this->data = $rows; } } Export class: namespace App\Exports; use Maatwebsite\Excel\Concerns\FromCollection; class TimesheetsExport implements FromCollection { protected $rows; public function __construct($rows) { $this->rows = $rows; } public function collection() { return $this->rows; } } My controller: public function importTimesheets(Request $request) { $import = new TimesheetsImport; $rows = Excel::toCollection($import, $request->file('file')); return Excel::download(new TimesheetsExport($rows), 'test.xlsx'); } With this code, I get the Windows 'Save File' as well. This was not fun, but it's done, I hope it will help someone else. A: use Maatwebsite\Excel\Concerns\ToModel; use Maatwebsite\Excel\Concerns\WithHeadingRow; use Excel; use Maatwebsite\Excel\Concerns\FromArray; use Maatwebsite\Excel\Excel as ExcelType; ... $array = [[1,2,3],[3,2,1]]; return \Excel::download(new class($array) implements FromArray{ public function __construct($array) { $this->array = $array; } public function array(): array { return $this->array; } },'db.xlsx', ExcelType::XLSX); decided so without additional frames. Laravel 7*, Maatwebsite 3*
unknown
d5537
train
Have you thought about using something like Dropbox to keep the folders synchronized? A: You would use DFS (Distributed File System) to accomplish this. http://technet.microsoft.com/en-us/library/cc753479(v=ws.10).aspx http://blogs.iis.net/rickbarber/archive/2012/12/05/keeping-multiple-iis-7-servers-in-sync-with-shared-configuration.aspx Thanks. -matt
unknown
d5538
train
@echo off set file=track12.mp3 ( echo Set Sound = CreateObject("WMPlayer.OCX.7"^) echo Sound.URL = "%file%" echo Sound.Controls.play echo do while Sound.currentmedia.duration = 0 echo wscript.sleep 100 echo loop echo wscript.sleep (int(Sound.currentmedia.duration^)+1^)*1000) >sound.vbs start /min sound.vbs just change track12.mp3 with the name of your audio file A: And here is a complete batch source for a batch Music Player ! So enjoy it ;) Batch Music Player.bat @echo off setlocal enabledelayedexpansion Set vbsfile=%temp%\Intro.vbs Set URL=http://hackoo.alwaysdata.net/Intro_DJ.mp3 Call:Play %URL% %vbsfile% Start %vbsfile% Set MyFile=%~f0 Set ShorcutName=DJ Batch Music Player ( echo Call Shortcut("%MyFile%","%ShorcutName%"^) echo ^'**********************************************************************************************^) echo Sub Shortcut(CheminApplication,Nom^) echo Dim objShell,DesktopPath,objShortCut,MyTab echo Set objShell = CreateObject("WScript.Shell"^) echo MyTab = Split(CheminApplication,"\"^) echo If Nom = "" Then echo Nom = MyTab(UBound(MyTab^)^) echo End if echo DesktopPath = objShell.SpecialFolders("Desktop"^) echo Set objShortCut = objShell.CreateShortcut(DesktopPath ^& "\" ^& Nom ^& ".lnk"^) echo objShortCut.TargetPath = Dblquote(CheminApplication^) echo ObjShortCut.IconLocation = "Winver.exe,0" echo objShortCut.Save echo End Sub echo ^'********************************************************************************************** echo ^'Fonction pour ajouter les doubles quotes dans une variable echo Function DblQuote(Str^) echo DblQuote = Chr(34^) ^& Str ^& Chr(34^) echo End Function echo ^'********************************************************************************************** ) > %temp%\Shortcutme.vbs Start /Wait %temp%\Shortcutme.vbs Del %temp%\Shortcutme.vbs ::**************************************************************************************************** Title DJ Batch Music Player by Hackoo 2015 :menuLOOP Color 0A & Mode con cols=78 lines=25 echo( echo =============================================================== echo "/ | / | / | "; echo "$$ | $$ | ______ _______ $$ | __ ______ ______ "; echo "$$ |__$$ | / \ / |$$ | / | / \ / \ "; echo "$$ $$ | $$$$$$ |/$$$$$$$/ $$ |_/$$/ /$$$$$$ |/$$$$$$ |"; echo "$$$$$$$$ | / $$ |$$ | $$ $$< $$ | $$ |$$ | $$ |"; echo "$$ | $$ |/$$$$$$$ |$$ \_____ $$$$$$ \ $$ \__$$ |$$ \__$$ |"; echo "$$ | $$ |$$ $$ |$$ |$$ | $$ |$$ $$/ $$ $$/ "; echo "$$/ $$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$/ $$$$$$/ "; echo " "; echo " "; echo( =============================Menu============================== echo( for /f "tokens=2* delims=_ " %%A in ('"findstr /b /c:":menu_" "%~f0""') do echo %%A %%B echo( echo( =============================================================== set choice= echo( & set /p choice=Make a choice or hit ENTER to quit: || GOTO :EOF echo( & call :menu_[%choice%] GOTO:menuLOOP ::******************************************************************************************** :menu_[1] Play DJ Buzz Radio cls & color 0A Call:SkipLine 10 Call:Tab 3 echo %x% Please Wait for a while .. Launching DJ Buzz Radio ... Taskkill /IM "wscript.exe" /F >nul 2>&1 Set vbsfile=%temp%\DJBuzzRadio.vbs Set URL=http://www.chocradios.ch/djbuzzradio_windows.mp3.asx Call:Play %URL% %vbsfile% Start %vbsfile% TimeOut /T 1 /NoBreak>nul GOTO:menuLOOP ::******************************************************************************************** :menu_[2] Play David Guetta Mix cls & color 0A Call:SkipLine 10 Call:Tab 3 echo %x% Please Wait for a while .. Launching David Guetta Mix ... Taskkill /IM "wscript.exe" /F >nul 2>&1 Set vbsfile=%temp%\David_Guetta_Miami.vbs Set URL=http://hackoo.alwaysdata.net/David_Guetta_Miami_2014.mp3 Call:Play %URL% %vbsfile% Start %vbsfile% TimeOut /T 1 /NoBreak>nul GOTO:menuLOOP ::******************************************************************************************** :menu_[3] Play Ibiza Mix cls & color 0A Call:SkipLine 10 Call:Tab 3 echo %x% Please Wait for a while .. Launching Ibiza Mix ... Taskkill /IM "wscript.exe" /F >nul 2>&1 Set vbsfile=%temp%\IbizaMix.vbs Set URL=http://hackoo.alwaysdata.net/IbizaMix.mp3 Call:Play %URL% %vbsfile% Start %vbsfile% TimeOut /T 1 /NoBreak>nul GOTO:menuLOOP ::******************************************************************************************** :menu_[4] Play Avicii Mega Mix cls & color 0A Call:SkipLine 10 Call:Tab 3 echo %x% Please Wait for a while .. Launching Avicii Megamix ... Taskkill /IM "wscript.exe" /F >nul 2>&1 Set vbsfile=%temp%\IbizaMix.vbs Set URL="http://hackoo.alwaysdata.net/Best of Avicii Megamix 2014.mp3" Call:Play %URL% %vbsfile% Start %vbsfile% TimeOut /T 1 /NoBreak>nul GOTO:menuLOOP ::******************************************************************************************** :menu_[5] Play Mega Mix 90 cls & color 0A Call:SkipLine 10 Call:Tab 3 echo %x% Please Wait for a while .. Launching Mega Mix 90 ... Taskkill /IM "wscript.exe" /F >nul 2>&1 Set vbsfile=%temp%\IbizaMix.vbs Set URL="http://hackoo.alwaysdata.net/Megamix 90.mp3" Call:Play %URL% %vbsfile% Start %vbsfile% TimeOut /T 1 /NoBreak>nul GOTO:menuLOOP ::******************************************************************************************** :menu_[6] Stop the music cls & color 0C Call:SkipLine 10 Call:Tab 3 echo %x% Please Wait for a while .. Stopping the music ... Taskkill /IM "wscript.exe" /F >nul 2>&1 TimeOut /T 1 /NoBreak>nul GOTO:menuLOOP ::******************************************************************************************** :Play ( echo Play "%~1" echo Sub Play(URL^) echo Dim Sound echo Set Sound = CreateObject("WMPlayer.OCX"^) echo Sound.URL = URL echo Sound.settings.volume = 100 echo Sound.Controls.play echo do while Sound.currentmedia.duration = 0 echo wscript.sleep 100 echo loop echo wscript.sleep (int(Sound.currentmedia.duration^)+1^)*1000 echo End Sub )>%~2 ::********************************************************************************************* :Tab set "x=" For /L %%I In (1,1,%1) Do Set "x=!x! " REM ^-- this is a TAB goto :eof ::********************************************************************************************* :SkipLine For /L %%I In (1,1,%1) Do Echo( Goto:Eof :EOF EXIT ::*********************************************************************************************
unknown
d5539
train
Aha! I looked at the readline source, and found out that you can do this: "\M-v": vi-editing-mode "\M-e": emacs-editing-mode There doesn't appear to be a toggle, but that's probably good enough! For posterity's sake, here's my original answer, which could be useful for people trying to do things for which there is no readline function. Here's a way you could set it up, clearing the current command line in the process. Not what you want, I know, but maybe it'll help someone else who finds this question. In ~/.inputrc: "\M-v": "\C-k\C-uset -o vi\C-j" # alt (meta)-v: set vi mode "\M-e": "\C-k\C-uset -o vi\C-j" # alt (meta)-e: set emacs mode or to toggle...this should work: "\M-t": "\C-k\C-u[[ \"$SHELLOPTS\" =~ '\\bemacs\\b' ]] && set -o vi || set -o emacs\C-j" These are essentially aliases, taken one step farther to map to keys in readline so that you don't have to type an alias name and hit enter. A: The following .inputrc lines allow Meta / Alt+E to switch between emacs and vi-insert modes. Mooshing both j and k simultaneously will take you to vi-command mode. Note: The only English word with "kj" is "blackjack", no words contain "jk") set keymap emacs "\ee": vi-editing-mode "jk": "\eejk" "kj": "\eejk" set keymap vi-insert "\ee": emacs-editing-mode "jk": vi-movement-mode "kj": vi-movement-mode set keymap vi-command "\ee": emacs-editing-mode Note: If you add a binding under keymap emacs to vi-movement-mode to try to switch straight to vi-command mode, the prompt doesn't update if you have show-mode-in-prompt on, hence the above work-around is needed. A: You can create a toggle since the key bindings are separate between vi mode and emacs mode. $ set -o emacs $ bind '"\ee": vi-editing-mode' $ set -o vi $ bind '"\ee": emacs-editing-mode' Now Alt-e (or Esc e) will toggle between modes. Add this somewhere in your definition for PS1 so you have an indicator in your prompt of which mode you're in. It won't show the change immediately when you toggle modes, but it will update when a new prompt is issued. $(set -o | grep emacs.*on >/dev/null 2>&1 && echo E || echo V) A: I finally found out how to toggle vi and emacs mode with a single key e.g. [alt]+[i] in zsh: # in the .zshrc # toggle vi and emacs mode vi-mode() { set -o vi; } emacs-mode() { set -o emacs; } zle -N vi-mode zle -N emacs-mode bindkey '\ei' vi-mode # switch to vi "insert" mode bindkey -M viins 'jk' vi-cmd-mode # (optionally) exit to vi "cmd" mode bindkey -M viins '\ei' emacs-mode # switch to emacs mode
unknown
d5540
train
This is my fix.. function GetSelectedRow(lnk) { var row = lnk.parentNode.parentNode; var rowIndex = row.rowIndex - 1; alert("RowIndex: " + rowIndex); return false; } I am calling this function in Onclientclick event of the link button. <asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="10%" Visible="true"> <ItemTemplate> <asp:LinkButton ID="lnkViewTimeSlots" runat="server" Text="Edit" ForeColor="Blue" OnClick="lnkViewTimeSlots_click" OnClientClick="return GetSelectedRow(this); javascript:shouldsubmit=true;" CausesValidation="false" Style="padding: 0px; margin: 0px;"></asp:LinkButton> </ItemTemplate> </asp:TemplateField> A: Simply you can get the row index like function GetSelectedRow(lnk) { alert("RowIndex: " + lnk.$index;);//This lnk.$index will get the index return false; }
unknown
d5541
train
@Angel O'Sphere: The package would contains models, visitors and factories all that ~2x (interfaces and impls). I had some thought about rogue programmer too, that's why I asked. Another approach would be: public class ModelImpl implement IRead { @Override public Foo getFoo() {...} private void setFoo(Foo f) {...} public void accept(Visitor v) { v.visit(new ModelEditor()); } private class ModelEditor implement IWrite { @Override public void setFoo(Foo f) { ModelImpl.this.setFoo(f); } } } But this approach has many drawbacks and is cumbersome without generative techniques :o
unknown
d5542
train
This is classic collapsing margin behavior. The people who wrote the CSS spec thought this was a good idea in order to prevent excessive white space from being created by margins. Without this behavior, it would be a lot more work to control margin/whitespace between block elements. References: CSS2 Spec - http://www.w3.org/TR/CSS2/box.html#collapsing-margins Andy Budd Article - http://andybudd.com/archives/2003/11/no_margin_for_error/ Eric Meyer Article - http://www.complexspiral.com/publications/uncollapsing-margins/ Why Collapsing Margins Are a Good Idea Collapsing margins are a feature of the CSS Box Model, which forms the basic working unit for the Visual Formatting Model, which allows us to have a rational environment in which to develop web pages. In designing the CSS specification, the authors had to balance how how rules would be written, for example: margin: 1.0em, and how these rules would work in a CSS formatting engine that needs to layout block of content from top-to-bottom and left-to-right (at least in Western European languages). Following the train-of-thought from Eric Meyer's article cited above, suppose we have a series of paragraphs with margins styled according to: p { margin: 1.00em; } For those of us who used to seeing printed pages with regular spacing between paragraphs, one would expect the space between any two adjacent paragraphs to be 1.00em. One would also expect the first paragraph to have a 1.00em margin before it and the last paragraph to have a 1.00em margin after it. This is a reasonable, and perhaps simplified, expectation of how the simple CSS rule for p should behave. However, for the programmers building the CSS engine that interprets the simple p rule, there is a lot of ambiguity that needs to be resolved. If one is expecting the printed page interpretation of the CSS rule, then this naturally leads to the collapsing margin behavior. So the programmers come up with a more complicated rule like: if there are two adjacent p tags with top and bottom margins, merge the margins together. Now this begs the question, how do you "merge margins together"? min or max of the adjacent top and bottom margins, average of the two? margin of first element always? And what if you have other block elements other than p's? and if you add a border or background? what next? Finally, how do you compute all of these margin settings in such a way so that you don't have to iterate through the entire set of HTML elements several times (which would make complicated pages load slowly especially in early generations of browsers)? In my opinion, collapsing margins offered a solution to a complicated problem that balanced the ease of writing CSS rules for margins, the user expectation of how printed pages are laid out in our typographic heritage, and finally, provided a procedure that could be implemented within the programming environment that browsers exist in. A: I achieved your desired layout by: * *Resetting the default margins and padding on the p tags: p{ margin: 0px auto; padding: 0px; } Make sure you add this to the top of your CSS. *Then changed the .headline and .text classes to use padding instead of margin; using your same values. *Removed the #main .inner CSS entirely.
unknown
d5543
train
You need also to check if your object myPage.URL has the property Url then assign it : if( myPage.URL != null ) if( myPage.URL.hasOwnProperty("Url") ) $pages.find("#myPage").attr("href", myPage.URL.Url); else $pages.find("#myPage").attr("href", "#") Hope this helps.
unknown
d5544
train
Did you make sure GetDataFromNumber is inside the class definition, and not after the closing brace? A: Check that the GetSchedule class is in the same namespace that you are trying to call it from, or that it is referenced. It looks from your updated post like your function GetDataFromNumber is in a class called IDNumber - is this the problem? Try: IDnumber myNumber = new IDnumber(); myNumber.GetDataFromNumber(text); A: The problem is because you are creating web forms and copying the code from one page to another. When you do this you have to be careful and make sure that you don't change the first directive in the page. It tells the web for what behind the code page it should look for where it should find the definitions and behind code logic. The reason you are having this problem is cause when you copied and pasted from one page to another it brought the directive for the other page which more than likely you do not have the functions you are calling within your page defined. So just make sure you changed the first line in your web page to point to the right .cs file and class from which it inherits.
unknown
d5545
train
You need to create the function inside another function. For example: div.onclick = (function(innerI) { return function() { alert(innerI); } })(i); This code creates a function that takes a parameter and returns a function that uses the parameter. Since the parameter to the outer function is passed by value, it solves your problem. It is usually clearer to make the outer function a separate, named function, like this: function buildClickHandler(i) { return function() { alert(i); }; } for(i = 0; i < 10; i++){ var div = document.createElement("div"); div.onclick = buildClickHandler(i); document.appendChild(div); } A: You could use an anonymous function: for(i = 0; i < 10; i++){ (function(i){ var div = document.createElement("div"); div.onclick = function(){alert(i);}; document.appendChild(div); })(i) }
unknown
d5546
train
Assuming the elements are visible on the page (not sure what the animation classes on the h6 elements are actually doing) then your first attempt wont work because of the extra > a on the selector in the within - which means you're finding the a already and then saying inside that find another a. Your second attempt won't work because find takes a selector type and selector (selector type defaults to css) to match against elements, but all returns an array of elements (you call either find to return one element or all to return multiple elements) - the following should work instead within(all('.animation-visible.tile-animation.link-group.color-white.border-round.bg-primary.animated')[0]) do find_link('More').click end which is saying inside the first .animation-visible... matching element find a link with 'More' for its text and click it. This could also be written within(first('.animation-visible.tile-animation.link-group.color-white.border-round.bg-primary.animated', minimum: 1)) do click_link('More') end That is basically the same thing except the minimum: 1 option will make it wait until at least one matching element is on the page (good for if your previous call is #visit or the elements are loading via ajax Note: you could use the minimum: 1 (or whatever number of elements you're expecting to appear on the page) on the first example too The find_link calls suggested in the other answer won't work because find_link doesn't take a css selector, it takes a string to match against the text, id, or title of the link. So the following would work find_link('More', href: 'http://some.com/page1/').click or click_link('More', href: 'http://some.com/page1/') A: Wouldn't these work? First link find_link("a[href$='page1/']").click Second link: find_link("a[href$='page2/']").click Translation of the css selector: Find the link that ends with XXX
unknown
d5547
train
The only reason I can think of that Google would index your cfc's would be that it is finding links to them in your pages. Remember, the Google bot can also find the links in your JavaScript code. You should be able to create/modify your robots.txt file to tell the search engines to exclude the directory(ies) that contain your cfc's from their indexes. Sample robots.txt entry: User-Agent: * Disallow: /cfc-directory/ The Google bot (but not all search engines) can even support some pattern matching (reference). So you could tell the Google bot not to index any files ending with .cfc by doing this: User-agent: Googlebot Disallow: /*.cfc$ A quick search turned up this similar question. In it @nosilleg mentions that the javascript code generated by ColdFusion's cfajaxproxy includes links to cfc's (in particular to /baseCFC/Statement.cfc. So if you are using that in any of your pages it will also contain links to cfc's.
unknown
d5548
train
public ActionForward pageLoad(ActionMapping a,ActionForm b,HttpServletRequest c,HttpServletResponse d){ b.setImageData(loadImageData()); return a.findForward("toPage"); } public ActionForward imageLoad(ActionMapping a,ActionForm b,HttpServletRequest c,HttpServletResponse d){ byte[] tempByte = b.getImageData(); d.setContentType("image/jpeg"); ServletOutputStream stream = d.getOutputStream(); /* Code to write tempByte into stream here. */ return null; } Write the tempByte into stream, flush and close it. return null from the action. now call the action from inside an <img src="yourAction.do"> A: <%@ page import="java.sql.*" %> <%@ page import="java.io.*" %> Connection connection = null; String connectionURL = "jdbc:mysql://localhost:3306/Test"; ResultSet rs = null; PreparedStatement psmnt = null; InputStream sImage; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); connection = DriverManager.getConnection(connectionURL, "Admin", "Admin"); psmnt = connection.prepareStatement("SELECT image FROM save_image WHERE id = ?"); psmnt.setString(1, "11"); // here integer number '11' is image id from the table rs = psmnt.executeQuery(); if(rs.next()) { byte[] bytearray = new byte[1048576]; int size=0; sImage = rs.getBinaryStream(1); response.reset(); response.setContentType("image/jpeg"); while((size=sImage.read(bytearray))!= -1 ){ response.getOutputStream().write(bytearray,0,size); } } } catch(Exception ex){ out.println("error :"+ex); } finally { rs.close(); psmnt.close(); connection.close(); } %> By this u can retrive Image from Database
unknown
d5549
train
You're going to want to have some driver code, that acts as the entry point to your program and orchestrates how functions will be called. Currently you are doing this in your compare_list() function, simply move this code (and change it a bit, there were some mistakes with the while loop structure) to a new function. Typically this code is placed in a main function. In your case, it could look something like: def main(): random_colours = [] colours_input = [] randomize() # you forgot to call this in your code while True: user_input() if compare_list(): print('Congratulations! You are a master mind') break # exit the program colours_input.clear() Then, we just need to refactor our compare_list() function so that it only compares the lists, and returns the result of the comparison (I just return a boolean representing whether the comparison was successful, but you could also return the correct_place value for example). def compare_list(): correct_place = 0 if random_colours[0] == colours_input[0]: colour_1 = True correct_place = correct_place + 1 else: colour_1 = False if random_colours[1] == colours_input[1]: ... print('Correct colour in the correct place: ' + str(correct_place)) return correct_place == 4 # returns True, if correct_place equals 4, False otherwise Now, in our main function, we can count how many times we have run this main loop for each user attempt: def main(): random_colours = [] colours_input = [] attempts = 0 while True: attempts += 1 user_input() randomize() if compare_list(): print('Congratulations! You are a master mind') print('It only took you {} attempt{}!'.format(attempts, 's' if attempts > 1 else "") break # exit colours_input.clear() random_colours.clear() Now we simply call the main() function in our file to run the driver code. Typically this is done in an if block that runs only if your script is being run directly as opposed to being imported by something else: ... def compare_list(): ... def main(): ... if __name__ == "__main__": main() (You can read up about this practice here: What does if __name__ == “__main__”: do?) A final refactor would be to reduce the use of global variables. You should aim to make your functions units of code that operate on input(s) and return output(s). Designing your functions so that they mutate global variables to produce a result is an anti-pattern. Here's one way to refactor it: import random colours = ('PINK', 'BLUE', 'YELLOW', 'RED') # this is okay since it is a constant. We can make it an immutable tuple to clearly indicate that this is read-only. # remove the following global variables # random_colours = [] # colours_input = [] #handles the users input and stores in a list (colours_input) def user_input(): colours_input = [] # define the variable here. We create a new list that this function will populate, then return it for i in range(5): ... print('Your selected colour sequence is: ' + str(colours_input)) return colours_input # return the populated list def randomize(): random_colours = [] # define the variable here. Similar to above. for i in range (0,4): random_colours.append(random.choice(colours)) return random_colours # return it to the caller # we take in the lists to compare as parameters to the function, rather then getting them from the global scope def compare_list(colours_input, random_colours): ... # (everything else is the same) def main(): random_colours = randomize() # colours_input = [] attempts = 0 while True: attempts += 1 colours_input = user_input() if compare_list(colours_input, random_colours): # pass the returned lists in as arguments to this function call print('Congratulations! You are a master mind') print('It only took you {} attempt{}!'.format(attempts, 's' if attempts > 1 else "") break # exit the program # no need to clear this anymore. We get a new list from each call to user_input() # colours_input.clear()
unknown
d5550
train
Usually this is done on two separate pages: profile of the current user (my profile) and general profile page. On my profile page you use the logged in user's ID, something like $_SESSION['user-id'] and on general profile pages you use the ID from a drop down or whatever coming through the URL so something like $_GET['user-id']. A: Correct. When you query the database, pass in an ID so it get's the info for that specific ID $select = $db->query('SELECT id, name, info FROM table WHERE id = :id'); $select->execute(array(':id' => $_POST['id'])); and your html would be <form method="post"> <select name="id"> <option value="1">Person 1</option> <option value="2">Person 2</option> </select> <input type="submit" value="Select user" /> </form> A: Basically, you can achieve what you want, just note that PHP script is not active while user watches a page. It works just when the page loads (or reloads). So, you will need to reload the page when user changes the selected item in the dropdown. That is easily achievable, simply make it in onchange event handler. There is another way of doing it: AJAX. You can invoke the server-side not on page load, but on some internal page event (like dropdown selected index change). Then the page would not reload, but you will need to properly handle AJAX response. For the server it would be like a new page is being loaded. Read more about ajax.
unknown
d5551
train
Not out-of-the-box, but it's pretty easy to customize... public class CustomAttributeSource extends AnnotationJmxAttributeSource implements EmbeddedValueResolverAware { private StringValueResolver embeddedValueResolver; @Override public void setEmbeddedValueResolver(StringValueResolver resolver) { this.embeddedValueResolver = resolver; } @Override public ManagedAttribute getManagedAttribute(Method method) throws InvalidMetadataException { ManagedAttribute managedAttribute = super.getManagedAttribute(method); if (this.embeddedValueResolver != null) { managedAttribute .setDescription(this.embeddedValueResolver.resolveStringValue(managedAttribute.getDescription())); } return managedAttribute; } @Override public ManagedOperation getManagedOperation(Method method) throws InvalidMetadataException { ManagedOperation managedOperation = super.getManagedOperation(method); if (this.embeddedValueResolver != null) { managedOperation .setDescription(this.embeddedValueResolver.resolveStringValue(managedOperation.getDescription())); } return managedOperation; } } Then... <bean class="org.springframework.jmx.export.annotation.AnnotationMBeanExporter"> <property name="assembler"> <bean class="org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler"> <property name="attributeSource"> <bean class="foo.CustomAttributeSource" /> </property> </bean> </property> </bean>
unknown
d5552
train
Changed web renderer to html renderer flutter build web --web-renderer html which resulted in significant reduction in initial load time A: For the moment there is no solution for this, anyways the Flutter team is working on that and there should be a solution as soon as possible. You can check the status of this in this link: Flutter github issue A: There is a possibility to integrate the canvaskit at build process and host it with your web app for offline support. Therefore you need to define the url like: flutter build web --dart-define=FLUTTER_WEB_CANVASKIT_URL=/canvaskit/ This may could also reduce loading time. (direct network connection, no dns lookup...)
unknown
d5553
train
I created a simple test tool for this scenario, check it out to see if it will be of any use to you. It's free, no licensing of any sort required. No guarantees on any performance or quality either ;-) Usage: StressDb.exe <No. of instances> <Tot. Runtime (mins)> <Interval (secs)> Connection string should reside in the configuration file. All command line arguments are required. Use integers. The stored proc to use is also in the config file. You need to have .NET framework 3.5 installed. You can also run it from multiple workstations for additional load, or from multiple folders on same machine if trying to run additional stored procedures. You also need a SQL user Id, as currently it doesn't use a trusted connection. This code was actually super simple, the only clever bit was making sure that the connections are not pooled. http://......com/..../stressdb.zip Let me know if you find it useful.
unknown
d5554
train
First translate Location into LatLng: LatLng newPoint = new LatLng(location.getLatitude(), location.getLongitude()); Then add a point to existing list of points: List<LatLng> points = lineRoute.getPoints(); points.add(newPoint); lineRoute.setPoints(points);
unknown
d5555
train
card_drawn is defined inside the function draw_card inside if cases. def draw_card(): randomrd_drawn_int = random.randint(1,20) card_drawn = None if card_drawn_int == [1,2,3,4,5,6,7,8,9,10,11,12]: card_drawn = ['Mechanized Infantry'] elif card_drawn_int == [13,14,15,16,17]: card_drawn = ['STRV 122'] elif card_drawn_int == [18,19,20]: card_drawn = ['JAS 37'] print(card_drawn) return card_drawn I have rewritten the function so it works. You need to learn about the scope in Python : https://www.w3schools.com/PYTHON/python_scope.asp
unknown
d5556
train
if anyone is following up... the solution is to use thunks (see redux-thunks). so i rewrote saveElement as thunk and just dispatch it. dispatch(saveElement())
unknown
d5557
train
I would do it this way: library(tidyverse) dat %>% group_by(species) %>% summarise(conditions = 'average', values = mean(values)) %>% bind_rows(dat) %>% ggplot(aes(x = species, y = values, fill = conditions)) + geom_col(position = "dodge") + ggthemes::theme_tufte() + scale_fill_brewer(palette = 'Set2') Data set.seed(57377888) dat <- data.frame( species = c( rep("sorgho" , 3), rep("poacee" , 3), rep("banana" , 3), rep("triticum" , 3) ), conditions = rep(c('normal', 'stress', 'nitrogen'), 4), values = abs(rnorm(12, 0, 15)), stringsAsFactors = F ) A: What you’re looking for is called a summary statistic (stat_summary in ggplot2 parlance). And rather than another bar, I suggest adding a new geometry that’s less ambiguous. A dot is conventional, or a short horizontal bar. Here’s a minimal code to add it: ggplot(data, aes(fill = condition, x = specie, y = value)) + geom_col(position = 'dodge') + stat_summary(aes(group = specie), fun.y = mean, geom = 'point') (Note that I’ve used geom_col() instead of geom_bar(stat = 'identity').)
unknown
d5558
train
You can discover what caused your pipeline to run. This may be cron trigger, manual trigger, code commit trigger, webhook trigger, comment on GitHub, upstream job, etc. (depending on plugins installed, the list may be long.) Here's and example of code to understand what the trigger was. This example sets the environment variable TRIGGERED_BY. def checkForTrigger() { def timerCause = currentBuild.rawBuild.getCause(hudson.triggers.TimerTrigger.TimerTriggerCause) if (timerCause) { echo "Build reason: Build was started by timer" env.TRIGGERED_BY = 'timer' return } def userCause = currentBuild.rawBuild.getCause(hudson.model.Cause$UserIdCause) if (userCause) { echo "Build reason: Build was started by user" env.TRIGGERED_BY = 'user' return } def remoteCause = currentBuild.rawBuild.getCause(hudson.model.Cause$RemoteCause) if (remoteCause) { echo "Build reason: Build was started by remote script" env.TRIGGERED_BY = 'webhook' return } // etc. println "We haven't caught any of triggers, might be a new one, here is the dump" def causes = currentBuild.rawBuild.getCauses() println causes.dump() } I think that a build might have more than one trigger, if so the order of your clauses is important. Once you have this figured out, you can run your stages only when the trigger fits your definition. stage ('B'){ when { beforeAgent true anyOf { expression{return env.GIT_BRANCH == "origin/development"} environment name: 'TRIGGERED_BY', value: 'timer' environment name: 'TRIGGERED_BY', value: 'webhook' } A: Not in a clean or first-class manner, but yes you can do it effectively. For any job which has been run at least once, you can click "replay" for the previous run. You will then be presented with the Jenkinsfile in a text edit box. At this point you can perform any edit you want to the Jenkinsfile (including pasting in a completely unrelated Jenkinsfile if you wanted) and Jenkins will execute the modified version. For your specific case, you can delete all the stages you don't want to re-run and just leave behind the one (or two, etc) you want.
unknown
d5559
train
If the date field is of type datetime, you'll have to do something like SELECT ... WHERE DATE(date)=CURDATE() Notice that I'm using curdate() in the query. There's no need to generate the date value in PHP. MySQL is perfectly capable of doing that itself. A: Try adding a GROUP BY statement to the second SQL statement. * *you should group by the key of the elemnts you want to be shown in the end result A: The use of the aggregate function SUM will result in a single result. You are asking the database to get all the rows then sum up a value and give you the value. To see the result for many groups of values you have to add a group by clause.
unknown
d5560
train
You need to make sure SBT is able to find that dependency. Follow a standard way of adding unmanaged dependencies to your project as described here. Citing that reference: Unmanaged dependencies Most people use managed dependencies instead of unmanaged. But unmanaged can be simpler when starting out. Unmanaged dependencies work like this: add jars to lib and they will be placed on the project classpath. Not much else to it! You can place test jars such as ScalaCheck, specs, and ScalaTest in lib as well. Dependencies in lib go on all the classpaths (for compile, test, run, and console). If you wanted to change the classpath for just one of those, you would adjust dependencyClasspath in Compile or dependencyClasspath in Runtime for example. There’s nothing to add to build.sbt to use unmanaged dependencies, though you could change the unmanagedBase key if you’d like to use a different directory rather than lib. To use custom_lib instead of lib: unmanagedBase := baseDirectory.value / "custom_lib" baseDirectory is the project’s root directory, so here you’re changing unmanagedBase depending on baseDirectory using the special value method as explained in more kinds of setting. There’s also an unmanagedJars task which lists the jars from the unmanagedBase directory. If you wanted to use multiple directories or do something else complex, you might need to replace the whole unmanagedJars task with one that does something else. To test if it works well just run SBT externally (outside of IntelliJ from cmd) and execute update or compile tasks. If your library is used in the code and you get no errors then SBT is happy. Afterwards simply use "Import Project" in IntelliJ and select "Use auto-import" option in one of the wizard steps. A: Add this to your build.sbt: libraryDependencies += "org.apache.commons" % "commons-math3" % "3.5"
unknown
d5561
train
By default, the output encoding in a sublime build is utf-8. This will cause an error if there are non-utf-8 characters in your sass or scss. You can create a custom sass .sublime-build along the lines of the following by going to Tools > Build System > New Build System. { "cmd": ["sass", "--update", "$file:${file_path}/${file_base_name}.css", "--stop-on-error", "--no-cache"], "selector": "source.sass, source.scss", "line_regex": "Line ([0-9]+):", "osx": { "path": "/usr/local/bin:$PATH" }, "windows": { "shell": "true" } "encoding": "cp1252" } Note the key (the only one that'll be surplus from the installed package) "encoding": "cp1252". Its value will have to match that of your source or be a superset thereof. There's a fairly comprehensive list of codecs in the Python docs.
unknown
d5562
train
I had the exact same problem. Sounds like you're trying to follow the tutorial videos only using the new Red5_1.0, Like I was. After many days, beers, and bruises from banging my head against my desk, I discovered that if you change your class to "org.red5.server.scope.WebScope" in your red5-web.xml file it should work correctly (bean id="web.scope"). Also, you may need to change your org.red5.core source imports from "import org.red5.server.api.IScope;" to "import org.red5.server.api.scope.IScope;". Apparently there has been some class refactoring in the newer versions of Red5 A: I was getting a similar error, although when I checked my class was already set to "org.red5.server.scope.WebScope" as mentioned in Ninth Realm Matt's answer. I later found that I was missing the lib directory under webaps/chat/WEB-INF/. This may be useful if anyone else has a similar problem.
unknown
d5563
train
Are your sounds embedded in the app or are you loading them at runtime? I assume embedded, but in that case it shouldn't take time before they are available. If loading sounds at runtime, just respond to Event.COMPLETE to hide your splash screen. Or use setTimeout with a suitable delay if you have no events to respond to: //wait 5000ms setTimeout(hideSplashScreenFunction, 5000); .... function hideSplashScreen():void { //hide splash screen } A: You can set splashScreenMinimumDisplayTimeproperty you can achieve. Like this <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" splashScreenImage="@Embed('assets/icons/chrome/logo.png')" splashScreenMinimumDisplayTime="4000" splashScreenScaleMode="none"> Hope it will help you.
unknown
d5564
train
There is no custom format for months in all-caps. If you can reference the existing cell, then use TEXT to get the date formatted as you want and then UPPER to convert to upper case. =UPPER(TEXT(A2,"dd-mmm-yyyy")) A: This worked UPPER(TEXT(C2, "DD-MMM-YYYY"))
unknown
d5565
train
A")) If Sheet1.Cells(i, 10).Value = Me.ComboBox8.Value Then Me.ListBox1.AddItem Sheet1.Cells(i, 10).Value 'ID Number Me.ListBox1.List(ListBox1.ListCount - 1, 0) = Sheet1.Cells(i, 1).Value 'Title Me.ListBox1.List(ListBox1.ListCount - 1, 1) = Sheet1.Cells(i, 2).Value So would it be more something like this.. Private Sub TextBox47_Change() Me.TextBox47.Text = Format(TextBox47.Text, "dd/mmm/yyyy") Me.TextBox47.BackColor = .Interior.Color End Sub Which gives a Compile Error 1 Newer code I've now changed it to this.. Private Sub TextBox47_Change() Dim cell As Range Me.TextBox47.Text = Format(TextBox47.Text, "dd/mmm/yyyy") With Range("data_table[Date Test]") Me.TextBox47.BackColor = Range("data_table[Date Test]").Interior.Color End With End Sub Which at least doesn't throw up an error, but on every selection the BackColor is black. I started with .. Private Sub TextBox47_Change() Dim cell As Range Me.TextBox47.Text = Format(TextBox47.Text, "dd/mmm/yyyy") With Range("data_table[Date Test]") Me.TextBox47.BackColor = Range("cell").Interior.Color End With End Sub But that just stopped at a Run Time error 1004 Yet another edit.. please tell me if continual adding to this post is the wrong way to do it. This, when hovering over is actually picking up the correct info from the cell that I'm after (I've tried different ones to make sure), in the Listbox selection that I'm clicking on, so I guess now it's a case of telling the Interior.Colour to look at the cell that is chosen? A: I managed to get it to work.. although not sure if it's the most elegant solution. :) To save confusing it with the code above, which has gotten a bit disjointed and messy, here's all the new working code and the explanation I came up with Code to colour cells in sheet: Dim cell As Range For Each cell In Range("data_table[Date Reviewed]") If cell.Value < Range("Today") Then cell.Interior.ColorIndex = 7 'Magenta ElseIf cell.Value >= Range("Today") And cell.Value <= Range("Thirty_Days") Then cell.Interior.ColorIndex = 3 'Red ElseIf cell.Value > Range("Thirty_Days") And cell.Value <= Range("Sixty_Days") Then cell.Interior.ColorIndex = 45 'Orange ElseIf cell.Value > Range("Sixty_Days") And cell.Value <= Range("Ninety_Days") Then cell.Interior.ColorIndex = 4 'Green ElseIf cell.Value > Range("Ninety_Days") Then cell.Interior.ColorIndex = 19 'Beige End If Next cell This is in UserForm_Initialize() And then to match the cell colour with TextBox.BackColor, I've used the ListBox.ListIndex to get the date, using the following code: Private Sub TextBox47_Change() Me.TextBox47.Text = Format(TextBox47.Text, "dd/mm/yyyy") If (Me.ListBox1.List(ListBox1.ListIndex, 65)) < Range("Today") Then TextBox47.BackColor = RGB(255, 0, 255) 'Magenta ElseIf (Me.ListBox1.List(ListBox1.ListIndex, 65)) >= Range("Today") And (Me.ListBox1.List(ListBox1.ListIndex, 65)) <= Range("Thirty_Days") Then TextBox47.BackColor = RGB(255, 0, 0) 'Red ElseIf (Me.ListBox1.List(ListBox1.ListIndex, 65)) > Range("Thirty_Days") And (Me.ListBox1.List(ListBox1.ListIndex, 65)) <= Range("Sixty_Days") Then TextBox47.BackColor = RGB(255, 153, 0) 'Orange ElseIf (Me.ListBox1.List(ListBox1.ListIndex, 65)) > Range("Sixty_Days") And (Me.ListBox1.List(ListBox1.ListIndex, 65)) <= Range("Ninety_Days") Then TextBox47.BackColor = RGB(0, 255, 0) 'Green ElseIf (Me.ListBox1.List(ListBox1.ListIndex, 65)) > Range("Ninety_Days") Then TextBox47.BackColor = RGB(255, 255, 204) 'Beige End If End Sub I can now call that TextBox.BackColor to set the associated Interior.Color of any other cell I'm forwarding on that value to, such as the Report I'm generating in Sheet2: Sheet2.Range("D105").Value = Me.TextBox47.Text Sheet2.Range("D105").Interior.Color = Me.TextBox47.BackColor Thankyou for your help and patience. It was your comment "So you have a listbox which returns a date" which helped me to see where I was actually getting the date from when hovering over the line of code, rather than it seeing a particular Cell.Address, and hence how I got the above to work. Again, thankyou, and I hope I didn't break too many posting rules in the meantime. :) Apologies, but I couldn't see a thanks button anywhere. Cheers Liam
unknown
d5566
train
no you have to get the ssl certificate to secure url check this What is SSL and what are Certificates? and Https connection without SSL certificate this is Free SSL Certificate :by Comodo for 90 days but never tried by me A: try heroku . Facebook provides you that option while you are registering your app.
unknown
d5567
train
Try this SELECT UNIX_TIMESTAMP( created_at ) AS DATE, COUNT( tweet_id ) AS count FROM `tweets` WHERE (DATE( created_at ) > '2012-11-01' AND DATE( created_at ) <= DATE( NOW( ) ) ) or DATE( created_at ) = date ('000-00-00') //I added this Line GROUP BY DATE
unknown
d5568
train
This might work for you (all GNU utilities using bash): lynx -dump -listonly bookmarks.html | grep -o 'https\?://[^/]*' | sort -u | parallel -k 'curl -I -m2 {} |& grep -q "HTTP/[0-9.]\+ 200" && echo {}' >bookmarks4 Use lynx to format links. Use grep to format urls. Use sort to sort and remove duplicates. Use parallel to check the urls using curl and checking its output for a 200 reply using grep. Output those urls that meet the requirements to bookmarks4. To output the original urls, perhaps: lynx -dump -listonly bookmarks.html | grep http | parallel --rpl '{url} s:.*(https?.*):$1:' \ --rpl '{dom} s:.*(https?\://[^/]*).*:$1:' \ 'curl -m2 -I {dom} |& grep -q "HTTP/[0-9.]\+ 200" && echo {url}' | sort -u >bookmarks4
unknown
d5569
train
You want to use Numpy's isclose np.isclose(s, 0.396515) array([False, False, True, False, False, False], dtype=bool) A: Your python series stores, or points to, numeric data represented as floats, not decimals. Here is a trivial example:- import pandas as pd s = pd.Series([1/3, 1/7, 2, 1/11, 1/3]) # 0 0.333333 # 1 0.142857 # 2 2.000000 # 3 0.090909 # 4 0.333333 # dtype: float64 s.iloc[0] == 0.333333 # False s.iloc[0] == 1/3 # True As @piRSquared explains, use np.isclose for such comparisons. Or, alternatively, round your data to a fixed number of decimal places.
unknown
d5570
train
* *Clear color and depth buffers *Set projection/modelview matrices for zoomed 2D/3D rendering *Enable depth test *Render zoomed 2D/3D scene *Reset projection/modelview for 2D overlay *Disable depth test *Draw 2D overlay *Repeat A: Ok, figured it out, you have to use two separate projection: 1.- Scale the world coordinates, so that the objects are drawn on the correct scene locations: g.pushTransform(); // Always zoom in the center of the screen. g.translate(resolution.getX(), resolution.getY()); g.scale(scale, scale); // Move the view g.translate(-view.getX(), -view.getY()); 2.- Push a new matrix to draw the object, inverting the scale transformation so the object's graphics don't change with scale: g.pushTransform(); // Center on the current object. g.translate(pos.x, pos.y); // Undo scaling of graphics! g.scale(1.0f/scale, 1.0f/scale);
unknown
d5571
train
i come from the link you posted on upwork, the way i understand your question, what you want to achieve seems to be impossible , what i think can work , is to fetch articles related to the author, with their corresponding tags, after that they are retrieved you do filtering and remove duplicates. otherwise the tag has nothing to connect it with the author,, A: The Django ORM is pretty cool when you get used to it, but regular SQL is pretty cool too # created_at, updated_at, name and tag_val are variables I # added due to my slight ocd lol class Author(models.Model): name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Tag(models.Model): tag_val = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Article(models.Model): author = models.ForeignKey(Author,related_name='articles', on_delete=models.CASCADE) tags = models.ManyToManyField(Tag, related_name='articles') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I can write my query like this, assuming the variable 'author' has been assigned an Author object instance, and get a list of dictionaries [{'tags':1},{'tags':2}] where the value is the auto generated primary key id of the Tag object instance author.articles.values('tags').distinct() A: I'm so jealous that's a great answer @since9teen94 Be aware, I will not base my answer in the easiest solution but how we model reality (or how we should do it). We put tags after things exists right? In that order I will make your life horrible with something like this: from django.db import models class Author(models.Model): name = models.CharField(max_length=30, null=False) class Article(models.Model): name = models.CharField(max_length=30, null=False) author = models.ForeignKey(Author, on_delete=models.CASCADE) class Tag(models.Model): name = models.CharField(max_length=30, null=False, unique=True) articles = models.ManyToManyField(Article) but believe me you don't want to follow this approach it will make your work harder. You can search for Articles based on Tags directly Tag.objects.filter(name='Scify').first().articles.all() # name is unique The real issue with this is that the reverse lookup is really complex (I mean.. get ready for debug) Article.objects.filter( id__in=list( Tag.objects.filter(name='Scify').first().articles.values_list('id', flat=True) ) ) I am sure this does not solve your problem and I don't like complex code for no reason but if you're open to suggestions I don't mind to think different and add some options Edit: About the author and clean repeated tags.. well you don't have to deal with that and if you want to find all Tag your author has you could loop the tags for tag in Tag.objects.all(): if tag.articles.filter(author__name='StackoverflowContributor'): print(tag.name) # > Scify I am just saying that there are options not that this is the best for you but don't be afraid of the terminal, it's really cool
unknown
d5572
train
I'll answer my own question mentio for angular does this job quite well
unknown
d5573
train
A feasible approach seems to be to load (and later update) all data into about 1GB RAM and perform the scoring and ranking outside MySQL in a language like C++. That should be faster than MySQL. The scoring must be relatively simple for this approache because your requirements only leave a tenth of a microsecond per row for scoring and ranking without parallelization or optimization. A: If you could post query you are having issue with can help. Although here are some things. Make sure you have indexes created on database. Make sure to use optimized queries and using joins instead of inner queries. A: Based on your criteria, the possibility of improving performance would depend on whether or not you can use the input criteria to pre-filter the number of rows for which you need to calculate scores. I.e. if one of the user-provided parameters automatically disqualifies a large fraction of the rows, then applying that filtering first would improve performance. If none of the parameters have that characteristic, then you may need either much more hardware or a database with higher performance. A: I'd say for this sort of problem, if you've done all the obvious software optimizations (and we can't know that, since you haven't mentioned anything about your software approaches), you should try for some serious hardware optimization. Max out the memory on your SQL servers, and try to fit your tables into memory where possible. Use an SSD for your table / index storage, for speedy deserialization. If you're clustered, crank up the networking to the highest feasible network speeds.
unknown
d5574
train
Your bucket is called cross-acct-permission-demo but your policy specifies cross-acct-perm-demo. Also your indentation is not correct for the first Action (though it should not cause this issue). Also not sure if the service-role principle is correct in this context. A: If you want IAM users in account A to be able to access resources in account B then you create an IAM role in account B that gives access to the relevant resources in account B, then you define account A as a trusted entity for the IAM role, then you permit access to that role to the relevant users in account A. Those users in account A can now assume the (cross-account) role in account B, and gain access to resources in account B. See Tutorial: Delegate Access Across AWS Accounts Using IAM Roles
unknown
d5575
train
* *If you're worried about changing the post service I would suggest using an API and that way you can change the backed storage for your service. The mobile or web client would call the service and then your api would place the file where it needed to go. The api you have more control over and you could just created a signed s3 url to send to the client and let them still do the uploading. *An api, like in 1, solves this problem too, the client doesn't have to do all the work. *Use Simple Token Services and Temporary Security Credentials. A: I agree with strongjz, you should use an API to upload your files from the server side. Cloudinary provides an API for uploading images and videos to the cloud. From what I know from my experience in using Cloudinary it is the right solution for you. All your images, videos and required metadata are stored and managed by Cloudinary in Amazon S3 buckets owned by Cloudinary. The default maximum file size limit for videos is 40MB. This can be customized for paid plans. For example in Ruby: Cloudinary::Uploader.upload("sample_spreadsheet.xls", :resource_type => :raw)
unknown
d5576
train
Usually, you have different containers for different table instances. Although, in some cases, you may want to share the same container instance between different components. It is totally possible and acceptable, as long as you understand the consequences: Filtering and sorting is done on the container level, meaning, that if you apply a filter on the container in one view and then navigate to another view, the container will be filtered there as well. Not understanding this may lead to "weird bugs" and lots of WTFs. The benefits of sharing the same container instance has to do with minimizing the memory footprint of your application - the more containers you have, the more memory you will consume. Note that both the table and the SQLContainer are lazy loading - meaning the table won't render more rows to the browser than what is needed to fill the table's area (+ some buffer), the SQLContainer won't fetch more rows than what are needed by the table --> your container won't actually contain in-memory more than a few dozen of items (* your mileage may vary). From a performance perspective (CPU), in your case, I don't see much benefit from sharing the same container instance in multiple views, since every time you switch a view, you need to apply new filters, thus triggering a new database query and fetching the needed data every time you switch views - even when going back to a view that was previously already filtered. So how about that best practice? Personally, I'd start with multiple container instances (one per view), do some profiling and optimize if needed. Premature optimization is the root of all evil. A: I don't believe it is possible to use the same container instance in multiple tables with different filter - (not 100% sure, but it's very strong instinct) With that in mind, I'd be inclined to do something like * *Create/use some kind of event bus to broadcast/subscribe messages saying "I've updated table XYZ" *Create an extension of SQLContainer overrides #fireContentsChange to broadcast when the table is updated, and that also reacts to the eventbus, calling #fireContentsChange (if the sourve of the event bus message isn't this) There's probably a more sophisticated/better way of doing this with a single shared Container.ItemSetChangeEvent, but it's tricky to think this through when typing into a browser text box. In short, on all containers, you want to propogate the ItemSetChangeEvent to all of the other containers that look at the same underlying table.
unknown
d5577
train
You would not be able to do this through a regular web page, since a web site gaining access to a file's path would be a gross security violation. One thing you could do is have a control on your page where the server creates a file tree from browsing the network share. Then the user would select the file path from this server-generated tree. A: suppose your network share drive is the S: drive if you use plain old file:// style URI's the links will auto open to your files on the share drive. i.e. file://s:\techfiles\myfile.txt in order to put the file on the share drive, you must be running that webapp on the share drive server(or have access to it), so just save that file off to the share server, then generate the path. The fact that the webapp server temporarily holds on to the file before storing it shouldn't bother you too much...
unknown
d5578
train
Wildcard on fields can't be applied on term query. Instead you can use query_string which supports wildcard on field as well. So following will work: Assuming text_mined_entities and nlp are of type nested { "query": { "nested": { "path": "text_mined_entities.nlp", "query": { "query_string": { "query": "BIRNLEX695", "fields": [ "text_mined_entities.nlp.tagged_entities_grouped.*.reference" ] } } } } } Update (if text_mined_entities & nlp are object type and not nested): { "query": { "query_string": { "query": "BIRNLEX695", "fields": [ "text_mined_entities.nlp.tagged_entities_grouped.*.reference" ] } } }
unknown
d5579
train
Your observation is reasonable: most of the time, nextIndex equals matchIndex + 1, but it is not always the case. For example, when a leader is initiated, matchIndex is initiated to the 0, while nextIndex is initiated to the last log index + 1. The difference here is because these two fields are used for different purposes: matchIndex is an accurate value indicating the index up to which all the log entries in leader and follower match. However, nextIndex is only an optimistic "guess" indicating which index the leader should try for the next AppendEntries operation, it can be a good guess (i.e. it equals matchIndex + 1) in which case the AppendEntries operation will succeed, but it can also be a bad guess (e.g. in the case when a leader was just initiated) in which case the AppendEntries will fail so that the leader will decrement nextIndex and retry. As for lastApplied, it's simply another accurate value indicating the index up to which all the log entries in a follower have been applied to the underlying state machine. It's similar to matchIndex in that they both are both accurate values instead of heuristic "guess", but they really mean different things and serve for different purposes. A: ... lastApplied is the highest log entry applied to state machine, but how is that any different than the commitIndex? These are different in a practical system because the component that commits the data in the log is typically separate from the component that applies it to replicated state machine or database. The commitIndex is typically just nanoseconds or maybe a few milliseconds more up-to-date than lastApplied. Is the matchIndex on leader just the commitIndex on followers? If not what is the difference? They are different. There is a period of time when the data is on a server and not yet committed, such as during the replication itself. The leader keeps track of the latest un-committed data on each of its peers and only need to send log[matchIndex[peer], ...] to each peer instead of the whole log. This is especially useful if the peer is significantly behind the leader; because the leader can update the peer with a series of small AppendEntries calls, incrementally bringing the peer up to date. A: * *commit is not mean already applied, there is time different between them. but eventually applied will catch up commit index. *matchIndex[i] which is saved in leader is equal to follower_i's commitIndex, and they are try to catch up to nextIndex
unknown
d5580
train
Reduce is one of the cheapest operations in Spark,since that the only thing it does is actually grouping similar data to the same node.The only cost of a reduce operation is the reading of the tuple and a decision of where it should be grouped. This means that the simple reduce,in contrast to the reduceByKey or reduceGroups is more expensive because Spark does not know how to make the grouping and searches for correlations among tuples. Reduce can also ignore a tuple if it does not meet any requirement.
unknown
d5581
train
I am assuming that the input data are 4 variables. For example public String parse(Integer year, String title, String genere, Date duration) So you just have to operate the values. For example return year + " - " + title + " " + genere + " " + toMinutes(duration) + " minutes" where toMinutes(duration) is a function which parse a date to minutes.
unknown
d5582
train
Your first example implicitly converts characters to strings and uses appropriate operator + While your second example is adding up characters https://en.cppreference.com/w/cpp/string/basic_string/operator_at returns reference to character at position A: Writing instead hd = ""s + ah[2] + ah[1] + ah[0]; will, informally speaking, put + into a "concatenation mode", achieving what you want. ""s is a C++14 user-defined literal of type std::string, and that tells the compiler to use the overloaded + operator on the std::string class on subsequent terms in the expression. (An overloaded + operator is also called in the first example you present.) Otherwise, ah[2] + ah[1] + ah[0] is an arithmetic sum over char values (each one converted to an int due to implicit conversion rules), with the potential hazard of signed overflow on assignment to hd. A: How about making use of everything that's already available? string rev(const string &x) { return string{x.rbegin(), x.rend()}; } Reverse iterators allow you to reverse the string, and the constructor of string with 2 iterators, constructs an element by iterati from begin to end.
unknown
d5583
train
I suspect the issue is that your input coordinates are rendering a 2D shape, not a 3D one (i.e. you have a constant Z value for all 4 vertices). Rather than rendering a 2D shape, render a square which is tilted in 3D, and the varying interpolation will do the perspective correct divide for you. You can then use a normal texture2D() operation. You probably don't want projective texturing in this case - you could - but it's needlessly complicated (you still need to generate an appropriate "w" value for the texture coordinate to get the perspective divide working, so you may as well just do that per vertex and use the varying interpolator to do the heavy lifting). A: If you really want to use texture2DProj then you can copy the W coordinate from the position to the texture coordinate. For example: uniform mat4 uPrj; attribute vec2 aXY; attribute vec2 aST; varying vec4 st; void main(void) { vec4 pos=uPrj*vec4(aXY,0.0,1.0); gl_Position=pos; st=vec4(aST,0.0,pos.w); st.xy*=pos.w; // Not sure if this is needed with texture2DProj } However, I got round the problem of textures in perspective by splitting my quadrilateral into a grid of smaller quads, and then splitting each small quad into two triangles. Then you can use GLSL code like this: uniform mat4 uPrj; attribute vec2 aST; // Triangles in little squares in range [0,1]. varying vec2 st; void main(void) { vec2 xy=aST*2.0-1.0; // Convert from range [0,1] to range [-1,-1] for vertices. gl_Position=uPrj*vec4(xy,0.0,1.0); st=aST; } The above code runs fast enough (maybe even faster than texture2DProj), because the fragment shader runs for the same number of pixels, and the fragment shader can use the simpler texture2D method (no fragment projection necessary). You can reuse the net of triangles in aST for each of your quadrilaterals. Here is how I made aST in JavaScript: var nCell = 32; var nVertex = nCell * nCell * 6; var arST = prog._arST = new Float32Array(nVertex * 2); var k = 0; for (var j = 0; j < nCell; j++) { var j0 = j / nCell; var j1 = (j + 1) / nCell; for (var i = 0; i < nCell; i++) { var i0 = i / nCell; var i1 = (i + 1) / nCell; arST[k++] = i0; arST[k++] = j0; arST[k++] = i1; arST[k++] = j0; arST[k++] = i0; arST[k++] = j1; arST[k++] = i0; arST[k++] = j1; arST[k++] = i1; arST[k++] = j0; arST[k++] = i1; arST[k++] = j1; } } gl.bindBuffer(gl.ARRAY_BUFFER, prog._bufferST); gl.bufferData(gl.ARRAY_BUFFER, prog._arST, gl.STATIC_DRAW);
unknown
d5584
train
Use eval() function. However be aware that this is by design a HUGE hole of security. A: You have to use eval(). Extract the user input from an onclick event and pass it into eval like so: eval(userString)
unknown
d5585
train
Yes, you need an iOS Developer Account in order to create the provisioning profiles and certificates you need for your app to actually run on a real device. A: Yes, it is mandatory to have a certificate and provisioning profile to build your app for device. You have to enroll for developer program/enterprise developer program if you wish to install your app on a device. It does not matter if you choose to use TestFlight or not.
unknown
d5586
train
At a glance, here are some tips. Your code needs many more safety checks & small fixes: Your main function signature seems to be sus: int main(int numberOfInvItems, inventoryItem inv[], ...... .....) { } should really be int main(int argc, char *argv[]) { } Note: if this isn't your ACTUAL APPLICATION MAIN function, then do NOT call it main. Secondly, your code readInventory method should really return a bool if it was successful or not, and only return the correct values via the arguments: ie: bool readInventory(inventoryItem inv[], int& numberOfInvItems, int& lastOrderNum) { // Could not open if(f.fail()) return false; // Dont set NumberOfInvItems to READ_ERROR? WHAT DOES THAT EVEN MEAN? // ... // Successful return true; } and in your main function int main(...) { int numberOfInvItems = 0; int lastOrderNum = 0; // Ensure it was successful via the return type if(readInventory(inv, numberOfInvItems,lastOrderNum)) { // ALL VALUES WEOULD BE VALID HERE for(int i = 0; i < numberOfInvItems; ++i) { // ... } } } Thirdly, my opinion is to avoid using C arrays. I'd suggest swapping them to std::vectors, or at least, a std::array to help reduce possible bugs. Finally, in your for loop: for (int m = 0; m < numberOfInvItems; m++) { //Inventory[m].prodNum = m; Inventory[m].prodCode = inv[m].prodCode; Inventory[m].description = inv[m].description; Inventory[m].price = inv[m].price; } Have you verified, or FORCED both Inventory[] and inv[] to be the same size? what if one size is larger than the other - it WILL crash. Either iterate to the smallest of either one, or dont iterate at all. You should add debugging (std::couts or printf's) after each line to see where it crashes specifically. Debug Debug Debug. You can then determine what line / function / expression caused the problem. If it crashes and no debugging was printed at all, then its probably due to your dodgy main function.
unknown
d5587
train
No. DeleteItem() requires a primary key for the table (docs) You'd need to query the metadata table, and delete the rows with the matching UID. If you don't already have it, I'd recommend a global secondary index with hash key = UID sort key = MID Then a Query(GSI, hash = UID) would using your example data return two rows. You'd then call DeleteItem(Table, HashKey = MID) for each returned row. Or better yet, collect both deletes and send once as a BatchWriteItem()
unknown
d5588
train
Replace your checkbox with <select name="more" onchange="showhidefield()"> <option value="yes">Yes</option> <option value="yes">Yes</option> </select> And replace the if (document.frm.chkbox.checked) in your showhidefield() function with if (document.frm.more.value == 'yes') A: <form name='frm' action='nextpage.asp'> <select name="chkbox" onChange="showhidefield(this)"> <option value="0" selected="true">-Select-</option> <option value="1">Yes</option> <option value="2">No</option> </select> Check/uncheck here to show/hide the other form fields <br> <div id='hideablearea' style='display:none;'> <input type='text'><br> <input type='submit'> </div> This is a text line below the hideable form fields.<br> </form> And javascript code is: <script language="JavaScript"> function showhidefield(that) { if (that.value == 1) { document.getElementById("hideablearea").style.display = "block"; } else { document.getElementById("hideablearea").style.display = "none"; } } </script>
unknown
d5589
train
Simply have the Eigenvalues target depend on all the .o files (not the .c files, as you have!) that make up the application. Conventionally, the list of these objects is put in a variable: PROGRAMS = Eigenvalues Eigenvalues_OBJS = Eigenvalues.o foo.o bar.o #etc all: $(PROGRAMS) Eigenvalues: $(Eigenvalues_OBJS) $(CC) $(CFLAGS) -o $@ $^ $(LFLAGS) # delete the "Eigenvalues: Eigenvalues.c" line, # leave everything else as you have it By the way, since you are using the standard variable names $(CC) and $(CFLAGS), you can leave out the %.o: %.c rule entirely; Make has a built-in rule that does the same thing. A: Try this mate! PROGRAMS = Eigenvalues MKL_INCLUDE=/opt/intel/mkl/include MKLROOT=/opt/intel/mkl/lib IFLAGS = -I$(MKL_INCLUDE) CFLAGS = -Wall -O2 $(IFLAGS) -std=c99 LFLAGS = $(MKLROOT)/libmkl_intel_lp64.a $(MKLROOT)/libmkl_sequential.a $(MKLROOT)/libmkl_core.a -lpthread -lm all: $(PROGRAMS).c OBJS = \ Eigenvalues.o \ myfile.o\ ############################################################################## .SUFFIXES : .c .o CC = mpicc LD = mpicc RM = rm -rf $(PROGRAMS).c : $(OBJS) $(CC) $(CFLAGS) -o $@ $^ $(LFLAGS) clean: $(RM) *.o $(OBJS) $(PROGRAMS) .c.o : $(CC) -c $(CFLAGS) -o $@ $<
unknown
d5590
train
It happened to a friend on his Moto X Force, Instagram kept crashing. He was using LineageOS 7.1, we wiped everything and installed the original firmware (through TRWP) and when we was installing the package, it returned IO Error on "data/data/com.instagram.android/analytics/xxxxxxxx.pending". We formatted the /data partition but the problem persisted. We installed the original firmware along with Magisk, installed Root Explorer and renamed the "com.instagram.android" folder to "insta.broken", uninstalled and reinstalled the app and voilá, working again. A: Huh, Turns out that if you uninstall the app, rename the folder containing the corrupted file and then re-install everything goes swimmingly. No idea what caused it or even what is wrong but hey, I have my calendar back.
unknown
d5591
train
The technical answer is because you have both an "Add to the global assembly cache ..." option checked and the Destination location option set on the Resource's properties in BizTalk Administrator. The first puts a copy in the GAC. The second puts a copy in the install folder. If you don't want the copy in the install folder, set Destination location to blank. Why does it default this way? It's pretty much a standard .Net practice. BizTalk itself installed a lot of assemblies on both Program Files and the GAC. Some though are GAC only, I don't know the exact reason.
unknown
d5592
train
IDs, as their name imply, should be unique to a document, you are duplicating the buttons IDs for every row. Normaly most browsers don't make a fuss if you have dulicates (though they should), but it seems in your case, it's causing problems. So, give your buttons unique IDs accross rows, or use classes to see if it helps: $html .= ' <td><button class="editDriver"></button><button class="timeDriver"></button></td>'; A: Could you write something between the button tag and add type attribute? <button type="button">Something</button> ref A: There are 3 things you need to fix/check: * *The id attribute id unique. You should not have more than one per page *<tr></tr> tags should be inside a <table></table> element. *Maybe your query return a single row, in which case your code is working properly. Also, you should check the official documentation for the button element: http://www.w3.org/wiki/HTML/Elements/button
unknown
d5593
train
I think it is inheriting styles from the parent tag. Please check the parent elements for any font size style.
unknown
d5594
train
Firstly, the word you're looking for is "deprecated". As far as I'm aware, the success and error properties are definitely not deprecated. You can (and should, in your case) continue to use them. The problem with your attempt to use ajaxError and ajaxComplete is that they are implemented as instance methods, rather than static methods on the jQuery object itself. For that reason, you need to select some element and call the methods on that collection. The element itself doesn't matter at all: $("#someElement").ajaxComplete(function () { // Do stuff }); The next problem, which you haven't come across yet, is that the ajaxError and related methods register global AJAX event handlers. Each time you call one of those methods, you add a new event handler to the global set, and every time an AJAX event is fired, all of your registered handlers will be executed. Update (Thanks @DCoder) Looks like the success and error properties are deprecated as of jQuery 1.8. Instead, you can use the fail, done and always methods of the jQuery modified XHR object. Any objects that inherit from the deferred object can use these methods (the jqXHR object is one of these): $.ajax(ajaxSetupObject).done(function () { // Handle success }).error(function () { // Handle error }); A: This code handles a success and error inside the ajax method.if there is a success it prints out success, with the object you receive, and vica versa. $.ajax({ type: 'json', url: 'foobar.com', success: function(s) { console.log('success' + s); }, error: function(e) { console.log('error' + e); } });
unknown
d5595
train
You should use the fully qualified name of the WriterSample, which is com.spotfire.samples.WriterSample and the correct java command is: java -cp .:././sbdf.jar com.spotfire.samples.WriterSample
unknown
d5596
train
Try (without _path suffix in as option): get '/roomidex_requests/:id/accept' => 'roomidex_requests#accept', :as => :accept_roomidex_requests And probably you should change http verb to post.
unknown
d5597
train
the background script will check only once when started as is. You could pass a mesage from the options script to background scripts after you update the local storage and use that as a trigger to check storage. try this: Options page function addToStorage(key, val){ let obj = {}; obj[key] = val; chrome.storage.local.set( obj, function() { if(chrome.runtime.lastError) { console.error( "Error setting " + key + " to " + JSON.stringify(val) + ": " + chrome.runtime.lastError.message ); } chrome.runtime.sendMessage({status: "Storage Updated"}, function (responce) { console.log(responce); }) }); } Background Page: chrome.runtime.onMessage.addListener( function (request, sender, responce) { if (request.status === "Storage Updated") { chrome.storage.local.get('code', function(code) { // ... with code.code ... }); sendResponce({status: "Update Recieved"}); } } ); Hope that helps, message passing docs here: https://developer.chrome.com/extensions/messaging
unknown
d5598
train
If Id and Values are same as the other one. It will remove that item from list. distinctList = list.Distinct().ToList(); If you are okay with converting the Tuple to Dictionary: Try This: If Only Id's are duplicate removes that item from list. It will not consider the value duplication. var distinctDictionary = list.GroupBy(id => id.Item1) .Select(group => group.First()) .ToDictionary(id => id.Item1, val => val.Item2); Look at the Screen shots: Solution 1: Solution 2: A: Why are you a List with tuples? With the requested functionality I would use a Dictionary so you won't have duplicates. A: Given your opinion that LINQ is generally more readable / maintainable and is generally equitable to efficiency, I present the following solution, which uses LINQ, and (IMHO compared to others presented so far) is more efficient in execution as well - list = list.Where((entry, i) => i == 0 || entry.Item1 != list[i - 1].Item1).ToList(); A: DistinctByKey = list.Select(x => x.Keys).Distinct(); DistinctByValue= DistinctByKey.Select(x => x.Values).Distinct();
unknown
d5599
train
Call apply on the series, just like you did when filling in the APIOutput column. df['apioutput1'] = df['APIOutput'].apply(lambda url: requests.get(url, verify=False)) A: Use .apply to call requests.get on every row df['apioutput1'] = df['APIOutput'].apply(lambda x: requests.get(x, verify=False) )
unknown
d5600
train
This reddit post links to a KvantSwarm which may be one way to approach it. You may also want to take a look at their flocking wiki for some code that you can drop in and test right away. Infrared5 posted a blog on swarming done for an aerial dogfight.
unknown