Dataset Viewer
Auto-converted to Parquet
response_k
stringlengths
15
30.7k
has_code_k
bool
2 classes
question
stringlengths
12
50.5k
url_question
stringlengths
41
44
qid
int64
17.9k
74.7M
response_j
stringlengths
26
29.8k
date
stringlengths
10
10
Looks like built-in `iter` doesn't check for `next` callable in an instance but in a class and `IteratorWrapper2` doesn't have any `next`. Below is simpler version of your problem ``` class IteratorWrapper2(object): def __init__(self, otheriter): self.next = otheriter.next def __iter__(self): return self it=iter([1, 2, 3]) myit = IteratorWrapper2(it) IteratorWrapper2.next # fails that is why iter(myit) fails iter(myit) # fails ``` so the solution would be to return `otheriter` in `__iter__` ``` class IteratorWrapper2(object): def __init__(self, otheriter): self.otheriter = otheriter def __iter__(self): return self.otheriter ``` or write your own `next`, wrapping inner iterator ``` class IteratorWrapper2(object): def __init__(self, otheriter): self.otheriter = otheriter def next(self): return self.otheriter.next() def __iter__(self): return self ``` Though I do not understand why doesn't `iter` just use the `self.next` of instance.
true
As part of some WSGI middleware I want to write a python class that wraps an iterator to implement a close method on the iterator. This works fine when I try it with an old-style class, but throws a TypeError when I try it with a new-style class. What do I need to do to get this working with a new-style class? Example: ``` class IteratorWrapper1: def __init__(self, otheriter): self._iterator = otheriter self.next = otheriter.next def __iter__(self): return self def close(self): if getattr(self._iterator, 'close', None) is not None: self._iterator.close() # other arbitrary resource cleanup code here class IteratorWrapper2(object): def __init__(self, otheriter): self._iterator = otheriter self.next = otheriter.next def __iter__(self): return self def close(self): if getattr(self._iterator, 'close', None) is not None: self._iterator.close() # other arbitrary resource cleanup code here if __name__ == "__main__": for i in IteratorWrapper1(iter([1, 2, 3])): print i for j in IteratorWrapper2(iter([1, 2, 3])): print j ``` Gives the following output: ``` 1 2 3 Traceback (most recent call last): ... TypeError: iter() returned non-iterator of type 'IteratorWrapper2' ```
https://Stackoverflow.com/questions/1152238
1,152,238
There are a bunch of places where CPython take surprising shortcuts based on *class* properties instead of *instance* properties. This is one of those places. Here is a simple example that demonstrates the issue: ``` def DynamicNext(object): def __init__(self): self.next = lambda: 42 ``` And here's what happens: ``` >>> instance = DynamicNext() >>> next(instance) … TypeError: DynamicNext object is not an iterator >>> ``` Now, digging into the CPython source code (from 2.7.2), here's the implementation of the `next()` builtin: ``` static PyObject * builtin_next(PyObject *self, PyObject *args) { … if (!PyIter_Check(it)) { PyErr_Format(PyExc_TypeError, "%.200s object is not an iterator", it->ob_type->tp_name); return NULL; } … } ``` And here's the implementation of PyIter\_Check: ``` #define PyIter_Check(obj) \ (PyType_HasFeature((obj)->ob_type, Py_TPFLAGS_HAVE_ITER) && \ (obj)->ob_type->tp_iternext != NULL && \ (obj)->ob_type->tp_iternext != &_PyObject_NextNotImplemented) ``` The first line, `PyType_HasFeature(…)`, is, after expanding all the constants and macros and stuff, equivalent to `DynamicNext.__class__.__flags__ & 1L<<17 != 0`: ``` >>> instance.__class__.__flags__ & 1L<<17 != 0 True ``` So that check obviously isn't failing… Which must mean that the next check — `(obj)->ob_type->tp_iternext != NULL` — *is* failing. In Python, this line is roughly (roughly!) equivalent to `hasattr(type(instance), "next")`: ``` >>> type(instance) __main__.DynamicNext >>> hasattr(type(instance), "next") False ``` Which obviously fails because the `DynamicNext` type doesn't have a `next` method — only instances of that type do. Now, my CPython foo is weak, so I'm going to have to start making some educated guesses here… But I believe they are accurate. When a CPython type is created (that is, when the interpreter first evaluates the `class` block and the class' metaclass' `__new__` method is called), the values on the type's `PyTypeObject` struct are initialized… So if, when the `DynamicNext` type is created, no `next` method exists, the `tp_iternext`, field will be set to `NULL`, causing `PyIter_Check` to return false. Now, as the Glenn points out, this is almost certainly a bug in CPython… Especially given that correcting it would only impact performance when either the object being tested isn't iterable or dynamically assigns a `next` method (*very* approximately): ``` #define PyIter_Check(obj) \ (((PyType_HasFeature((obj)->ob_type, Py_TPFLAGS_HAVE_ITER) && \ (obj)->ob_type->tp_iternext != NULL && \ (obj)->ob_type->tp_iternext != &_PyObject_NextNotImplemented)) || \ (PyObject_HasAttrString((obj), "next") && \ PyCallable_Check(PyObject_GetAttrString((obj), "next")))) ``` **Edit**: after a little bit of digging, the fix would not be this simple, because at least some portions of the code assume that, if `PyIter_Check(it)` returns `true`, then `*it->ob_type->tp_iternext` will exist… Which isn't necessarily the case (ie, because the `next` function exists on the instance, not the type). SO! That's why surprising things happen when you try to iterate over a new-style instance with a dynamically assigned `next` method.
2009/07/20
Or you could use RegEx: ``` var str = "<name>"; var reg = /[<>:\/?#\[\]@!]/g //add more characters to the RegEx var newStr = str.replace(reg, ""); console.log(newStr); ```
true
I was trying to find and replace string by JavaScript but my routine is not working. I guess there is some mistake. Please guide me what to fix in js routine. Here is my script. ``` function ReplaceChars(srcString) { var IgnoreChars = ['<', '>',':', '/', '?', '#', '[', ']', '@', '!', '$', '&', '(', ')', '*', '', '+', ',', ';', '=', ']', ';']; for (i = 0; i < srcString.length; i++) { for (j = 0; j < IgnoreChars.length; j++) { if (srcString.charAt(i) == IgnoreChars.charAt(j)) { srcString=srcString.replace(srcString.charAt(i), ''); } } } return srcString; } var str = '<name>'; alert(ReplaceChars(str)); ```
https://Stackoverflow.com/questions/26675576
26,675,576
You're almost there. IgnoreChars is an array - not a String - so it doesn't have a charAt function; change this line: ``` if (srcString.charAt(i) == IgnoreChars.charAt(j)) ``` to ``` if (srcString.charAt(i) == IgnoreChars[j]) ``` Here's a fiddle: <http://jsfiddle.net/q0ztudLd/>
2014/10/31
You should use a backslash(`\`) before using `'` . Because `'` is a special character. So, you should use as follows, ``` case '\'': printf("039"); break; ```
true
I met a problem when I try to send email in Java by using Gmail SMTP. Once I started the email feature, there will be a email window pop out: [![enter image description here](https://i.stack.imgur.com/DKtUu.png)](https://i.stack.imgur.com/DKtUu.png) The user will key in the subject and email content and then send an email by clicking the `button`. There will be two errors come out once the user clicked the `button`. How can I fix the problem? The errors are: ``` java.lang.reflect.InvocationTargetException java.lang.VerifyError: (class: com/sun/mail/handlers/handler_base, method: getTransferData signature: (Ljavax/activation/ActivationDataFlavor;Ljavax/activation/DataSource;)Ljava/lang/Object;) Incompatible argument to function ``` My code is shown below: ``` package seedu.address.ui.email; import java.util.Properties; import java.util.logging.Logger; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import seedu.address.commons.core.LogsCenter; public class EmailWindowController { private final Logger logger = LogsCenter.getLogger(EmailWindowController.class); private String password; private String from; private String to; @FXML private Button sendButton; @FXML private Label senderEmailAddress; @FXML private Label receiverEmailAddress; @FXML private TextField subjectTestField; @FXML private TextArea emailContentArea; @FXML void handleButtonAction(ActionEvent event) { if (event.getSource() == sendButton) { String subject = subjectTestField.getText(); String content = emailContentArea.getText(); //sendEmail(subject, content); sendSimpleEmail(subject, content); } } void initData(String from, String password, String to) { senderEmailAddress.setText(from); receiverEmailAddress.setText(to); this.password = password; this.from = from; this.to = to; } private void sendSimpleEmail(String subject, String content) { String host = "smtp.gmail.com"; final String senderAddress = from; final String senderPassword = this.password; final String toAddress = this.to; //setup mail server Properties props = System.getProperties(); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.user", senderAddress); props.put("mail.smtp.password", senderPassword); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props); MimeMessage m = new MimeMessage(session); try { m.setFrom(new InternetAddress(senderAddress)); m.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toAddress)); m.setSubject(subject); m.setText(content); //send mail Transport transport = session.getTransport("smtp"); transport.connect(host, senderAddress, senderPassword); transport.sendMessage(m, m.getAllRecipients()); transport.close(); //sentBoolValue.setVisible(true); System.out.println("Message sent!"); } catch (MessagingException ae) { ae.printStackTrace(); } } /* private void sendEmail(String subject, String content) { Properties properties = new Properties(); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.port", "587"); Session session = Session.getInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); } }); Message message = prepareMessage(session, from, to, subject, content); try { Transport.send(message); } catch (MessagingException e) { logger.info(" -------- Email Send Process Failed -------- "); e.printStackTrace(); } } private Message prepareMessage(Session session, String sender, String receiver, String subject, String content) { MimeMessage mimeMessage = new MimeMessage(session); try { // Create Email mimeMessage.setFrom(new InternetAddress(sender)); mimeMessage.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiver)); mimeMessage.setSubject(subject); mimeMessage.setText(content); return mimeMessage; } catch (MessagingException e) { logger.info(" -------- Email Prepare Process Failed -------- "); e.printStackTrace(); } return mimeMessage; } */ } ```
https://Stackoverflow.com/questions/71693629
71,693,629
You can use an escape sequence. ```c case '\'': printf("039"); break; ```
2022/03/31
+1 for jfriend00's answer. But including jQuery in a page overwrites both of the global symbols jQuery and $ (see [jQuery.js line 9579](https://github.com/jquery/jquery/blob/10399ddcf8a239acc27bdec9231b996b178224d3/test/data/jquery-1.9.1.js#L9579)) potentially causing conflicts with other libraries that define a global $. So taking this a step further to also stop the global $ conflict: ``` (function($) { // you can use $ here to refer to jQuery })(jQuery.noConflict()); ``` as demonstrated by: ``` <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script> <script> (function($) { console.log('want $ to be jQuery here so want true: ' + ($ === jQuery)); })(jQuery.noConflict()); console.log('do not want $ to be jQuery here so want false: ' + ($ === jQuery)); </script> ```
true
I need help understanding this pattern for jQuery plugin authoring. Can somebody explain this simple bit of code for me? ``` (function($) { /* Code here */ })(jQuery); ``` I know this is to avoid conflict with different plugins using the same `$` character but somehow cannot get around my head to understand how it works. What relation does the parameter `$` has to the `jQuery` object that got parsed in?
https://Stackoverflow.com/questions/19610586
19,610,586
A function in JavaScript can [be either a statement or an expression](http://kangax.github.io/nfe/#expr-vs-decl). When you use a function expression, you can pass it around like any other value: ``` > console.log(function() { 1 + 1; }); > (function() {}) && doExpensiveWork(); // etc. ``` One of the things you can do with a function expression is immediately invoke it. In such cases the function is called [an immediately invoked function expression (or IIFE for short)](http://benalman.com/news/2010/11/immediately-invoked-function-expression/): ``` > (function() { console.log("IIFE running"); })(); IIFE running ``` This is the same as creating the function and invoking it in two steps: ``` > var notAnIIFE = function() { console.log("running"); }; > notAnIIFE(); running ``` A function expression can, of course, take arguments: ``` > var someFunction = function(x, y) { return x + y; }; > var seven = someFunction(3, 4); > seven 7 ``` So an [IIFE](http://benalman.com/news/2010/11/immediately-invoked-function-expression/) can be invoked with arguments as well: ``` > var seven = (function(x, y) { return x + y; })(3, 4); > seven 7 ``` In the case of an invocation like this: ``` (function($) { /* do work with $ */ })(jQuery); ``` the value bound to the name `jQuery` is being passed into the function expression as the argument `$`. This is similar to doing the following: ``` var initializePlugin = function($) { /* do work with $ */ }; initializePlugin(jQuery); ``` but it leaves no trace in the parent namespace (whereas, in our second example, our `initializePlugin` name is left behind after we finish setting up our plugin).
2013/10/26
The click is bound to the element not the class. Maybe you can attach the events to the - elements and detect/toggle the elements classes: ``` $('li').click(function(event) { event.preventDefault(); if( $(this).hasClass('on') ) { $(this).removeClass('on'); } else { $(this).addClass('on'); $(this).siblings().removeClass('on'); } }); ```
true
I have two list items that, when clicked, should change classes from '.off' to '.on'. Only one element should be '.on' at a time so when one is already turned on and the other is clicked both elements should change classes from '.off' to '.on' and vice versa. If a list item with a class of '.on' is clicked it should change classes to '.off' The problem I am having is when a list item with class '.on' is clicked it still runs the click function as if it had a class of '.off' My html: ``` <ul> <li><a href="about" class="off">ABOUT</a></li> <li><a href="upload" class="off">SUBMIT</a></li> </ul> ``` My javascript (running on jQuery 1.7.1) ``` $('.off').click(function(event) { event.preventDefault(); $(".on").addClass("off").removeClass("on"); $(this).addClass("on").removeClass("off"); }); $('.on').click(function(event) { event.preventDefault(); $(this).addClass("off").removeClass("on"); }); ``` Does anyone know what is going on here? Is there something wrong in my code or have I encountered some sort of bug here? <http://jsfiddle.net/ZC3CW/6/>
https://Stackoverflow.com/questions/9036106
9,036,106
I would suggest adding a click handle to a different selector, this should work for you... ``` $("ul li a").click(function(e){ e.preventDefault(); if($(this).hasClass("off")){ $("ul li a").addClass("off").removeClass("on"); $(this).addClass("on").removeClass("off"); } else{ $(this).addClass("off").removeClass("on"); } }); ```
2012/01/27
this is my solution S = input("Input a word: ") ``` def isPalindrome(S): for i in range(0, len(S)): if S[0 + i] == S[len(S) - 1]: return "True" else: return "False" print(isPalindrome(S)) ```
true
I'm doing some python online tutorials, and I got stuck at an exercise:A palindrome is a word which is spelled the same forwards as backwards. For example, the word racecar is a palindrome: the first and last letters are the same (r), the second and second-last letters are the same (a), etc. Write a function isPalindrome(S) which takes a string S as input, and returns True if the string is a palindrome, and False otherwise. These is the code I wrote : ``` def isPalindrome(S): if S[0] == S[-1] return print("True") elif S[0] == S[-1] and S[1] == S[-2] : return print("True") else: return print("False") ``` But, if the word is for example ,,sarcas,, , the output is incorect. So I need a fix to my code so it works for any word.
https://Stackoverflow.com/questions/11758791
11,758,791
A one line solution but O(n) and memory expensive is : ``` def isPalindrome(word) : return word == word[::-1] ``` A O(n/2) solution that uses the same amount of memory is: ``` def palindrome(word): for i in range(len(word)//2): if word[i] != word[-1-i]: return False return True ``` This is the trick @LennartRegebro mentioned
2012/08/01
Blit means 'BL'ock 'I'mage 'T'ranfser When you are displaying things on the screen you will, in some way, use `screen` because that's where you are putting it. When you do: ``` pygame.draw.circle(screen, (0, 0, 0), (100, 100), 15, 1) ``` you are still using screen but you are just not blitting because pygame is drawing it for you. And when you use text, pygame renders it into an image then you have to blit it. So basically you blit images, but you can also have pygame draw them for you. But remember when you blit an image, say over a background, you need to loop it back and fourth; so that it blits the background, then the image, then the background etc... You dont need to know much more than that, but you can read all about it here [Pygame Blit](http://www.pygame.org/docs/ref/surface.html#pygame.Surface.blit) I hope this helped. Good Luck!
true
I've just started learning some pygame (quite new to programming overall), and I have some very basic questions about how it works. I haven't found a place yet that explains when I need to blit or not to include a certain surface on the screen. For example, when drawing a circle: ``` circle = pygame.draw.circle(screen, (0, 0, 0), (100, 100), 15, 1) ``` I don't need to do `screen.blit(circle)`, but when displaying text: ``` text = font.render("TEXT", 1, (10, 10, 10)) textpos = text.get_rect() textpos.centerx = screen.get_rect().centerx screen.blit(text, textpos) ``` If I don't blit, the text won't appear. To be honest, I really don't know what blitting is supposed to do, apart from "pasting" the desired surface onto the screen. I hope I have been clear enough.
https://Stackoverflow.com/questions/17454257
17,454,257
The short answer ================ > > I haven't found a place yet that explains when I need to blit or not to include a certain surface on the screen. > > > Each operation will behave differently, and you'll need to read the documentation for the function you're working with. The long answer =============== What Is Blitting? ----------------- First, you need to realize what blitting is doing. Your screen is just a collection of pixels, and blitting is doing a complete copy of one set of pixels onto another. For example, you can have a surface with an image that you loaded from the hard drive, and can display it multiple times on the screen in different positions by blitting that surface on top of the `screen` surface multiple times. So, you often have code like this... ``` my_image = load_my_image() screen.blit(my_image, position) screen.blit(my_image, another_position) ``` In two lines of code, we copied a ton of pixels from the source surface (my\_image) onto the screen by "blitting". How do the pygame.draw.\* functions blit? ----------------------------------------- Technically, the pygame.draw.\* methods could have been written to do something similar. So, instead of your example... ``` pygame.draw.circle(screen, COLOR, POS, RADIUS, WIDTH) ``` ...they COULD have had you do this... ``` circle_surface = pygame.draw.circle(COLOR, RADIUS, WIDTH) screen.blit(circle_surface, POS) ``` If this were the case, you would get the same result. Internally, though, the `pygame.draw.circle()` method directly manipulates the surface you pass to it rather than create a new surface. This might have been chosen as the way to do things because they could have it run faster or with less memory than creating a new surface. So which do I do? ----------------- So, to your question of "when to blit" and "when not to", basically, you need to read the documentation to see what the function actually does. Here is the [pygame.draw.circle()](http://www.pygame.org/docs/ref/draw.html#pygame.draw.circle) docs: > > pygame.draw.circle(): > > > draw a circle around a point > > > circle(Surface, color, pos, radius, width=0) -> Rect > > > Draws a circular shape on the Surface. The pos argument is the center of the circle, and radius is the size. The width argument is the thickness to draw the outer edge. If width is zero then the circle will be filled. > > > Note that it says that "draws a shape on the surface", so it has already done the pixel changes for you. Also, it doesn't return a surface (it returns a Rect, but that just tells you where the pixel changes were done). Now let's look at the [pygame.font.Font.render() documentation](http://www.pygame.org/docs/ref/font.html#pygame.font.Font.render): > > draw text on a new Surface > > > render(text, antialias, color, background=None) -> Surface > > > This creates a new Surface with the specified text rendered on it. Pygame provides no way to directly draw text on an existing Surface: instead you must use Font.render() to create an image (Surface) of the text, then blit this image onto another Surface. > ... > > > As you can see, it specifically says that the text is drawn on a NEW Surface, which is created and returned to you. This surface is NOT your screen's surface (it can't be, you didn't even tell the `render()` function what your screen's surface is). That's a pretty good indication that you will need to actually blit this surface to the screen.
2013/07/03
Unless you really want or have to do it yourself I would use `numpy`. <http://docs.scipy.org/doc/numpy/reference/generated/numpy.var.html> <http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html>
false
I have a code which calculates the square of a number using Gaussian distribution in python. Now my task is to calculate the variance for the same. But when I try, i keep getting error. The code is as follows: ``` import random def generate_data(size): n = 5 m =0.5 mu, sigma = n ** 2, m/3 return [random.gauss(mu, sigma) for _ in range(size)] def average(ls): avg = sum(ls) / len(ls) variance = (sum(ls) - sum(avg)) ** 2 / len(ls) return variance ``` I am not good in statistics, so I might be wrong with the formula too. and I am also a beginner in python.The error I get is ``` 'float' object is not iterable ```
https://Stackoverflow.com/questions/32867324
32,867,324
Your variance formula should be ``` variance = sum(map(lambda x: (x-avg) ** 2, ls)) / len(ls) ``` [source](https://en.wikipedia.org/wiki/Variance#Discrete_random_variable) Since `variance = sigma^2` you can test your code by printing `math.sqrt(variance)` ``` import random, math def generate_data(size): n = 5 m = 0.5 mu, sigma = n ** 2, m/3 return [random.gauss(mu, sigma) for _ in range(size)] def variance(ls): avg = sum(ls) / len(ls) variance = sum(map(lambda x: (x-avg) ** 2, ls)) / len(ls) return variance print(0.5/3) #0.16666666666666666 print(math.sqrt(variance(generate_data(100)))) #0.15702629417476763 print(math.sqrt(variance(generate_data(1000)))) #0.16248850600497303 print(math.sqrt(variance(generate_data(10000)))) #0.16774494705918871 ```
2015/09/30
You can do it like this: ``` import random weight_dict = { 1:"A", 2:"B", 3:"C" } def show_rand(): key = random.choice(list(weight_dict)) print ("Random key value pair from dictonary is ", key, " - ", weight_dict[key]) show_rand() ```
true
I've been working on a little project with Java Spring. I've already set the table structure in Navicat to be able "null" values. I have also set the model to be able to null values. But still, I can't input null values into the column and received this error messages. FYI: I'm using Spring Tool Suite 3.9.7 IDE ``` Field error in object 'sertifikasihapus' on field 'modified_on': rejected value []; codes [typeMismatch.sertifikasihapus.modified_on,typeMismatch.modified_on,typeMismatch.java.sql.Timestamp,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [sertifikasihapus.modified_on,modified_on]; arguments []; default message [modified_on]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.sql.Timestamp' for property 'modified_on'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@javax.persistence.Column java.sql.Timestamp] for value ''; nested exception is java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]]] ``` ```js <script> $('#idBtnHapusHapus').click(function() { var vDataRole = $('#idFrmHapusSertifikasi').serialize(); var angka = $('#Id').val(); var nama = $('#idNamaSertifikasi').val(); if ($("#idModifiedOn").val().length < 1) { $('#idModifiedOn').val(null); debugger; $.ajax({ url : './hapussertifikasi/' + angka, type : 'Put', data : vDataRole, dataType : "json", success : function(model) { debugger; window.location = './sertifikasi' }, error : function(model) { debugger; } }); } else { debugger; $.ajax({ url : './hapussertifikasi/' + angka, type : 'Put', data : vDataRole, dataType : "json", success : function(model) { debugger; window.location = './sertifikasi' }, error : function(model) { debugger; } }); } }); </script> ``` ```html <div class="col-xs-12"> <div class="row"> <form id="idFrmHapusSertifikasi" method="post"> <input type="hidden" class="form-control" id="Id" name="id" placeholder=""> <input type="hidden" class="form-control" id="idNamaSertifikasi" name="certificate_name" placeholder=""> <input type="hidden" class="form-control" id="idBulanBerlaku" name="valid_start_month" placeholder=""> <input type="hidden" class="form-control" id="idTahunBerlaku" name="valid_start_year" placeholder=""> <input type="hidden" class="form-control" id="idPenerbit" name="publisher" placeholder=""> <input type="hidden" class="form-control" id="idBulanBerlakuS" name="until_month" placeholder=""> <input type="hidden" class="form-control" id="idTahunBerlakuS" name="until_year" placeholder=""> <input type="hidden" class="form-control" id="idCatatan" name="notes" placeholder=""> <input type="hidden" class="form-control" id="idCreateOn" name="createOn" placeholder=""> <input type="hidden" class="form-control" id="idCreateBy" name="createBy" placeholder=""> <input type="hidden" class="form-control" id="idModifiedOn" name="modified_on" placeholder=""> <input type="hidden" class="form-control" id="idModifiedBy" name="modified_by" placeholder=""> </form> <div class="col-xs-2"> <i class="glyphicon glyphicon-trash center" style="font-size: 50px"></i> </div> <div class="col-xs-8"> <div class="clTulisanHapus center" id="idTulisanHapus"> <p>Anda Yakin ingin menghapus Sertifikasi</p> <!-- I WANTED THE CERTIFICATE NAME TO BE HERE --> <div th:each="item:${oneprofil}"> <b><p th:text="${item.certificate_name}+' ?'"></p></b> </div> </div> </div> </div> </div> <div class="col-md-offset-8"> <div class="btn-group"> <input type="hidden" id="idDataId"> <input type="hidden" id="idDataNama"> <button type="button" id="idBtnHapusBatal" data-dismiss="modal" class="btn clBtnMdlHapus">Tidak</button> <button type="button" id="idBtnHapusHapus" data-id="${item.id}" class="btn clBtnMdlHapus">Ya</button> </div> </div> ```
https://Stackoverflow.com/questions/57302415
57,302,415
Do you want it to select values instead of keys, or both? If both - Noufal Ibrahim's answer works. If only value - you can call `.values()` instead of `.items()`: ``` from random import choice example = {'a':1, 'b':2} choice(list(example.values())) ```
2019/08/01
Actually it's pretty easy. You just have to understand what the HEX values mean. In the hexadecimal system each number from 10 to 15 is represented by the letters A to F. The numbers lower ten are normal numbers 1 - 9. So if you want to convert 11 into hex it would be 0B. Because you need no number below 11 (0) and the letter B represents 11. If you read a little bit about the hex system, you should be able to write you new function very easily ;)
false
I have an existing fn that does the following: ``` public GetColor = (argb: number) => { var a = 1;// (argb & -16777216) >> 0x18; // gives me FF var r = (argb & 0xff0000) >> 0x10; var g = (argb & 0x00ff00) >> 0x8; var b = (argb & 0x0000ff); var curKendoColor = kendo.parseColor("rgba(" + r + "," + g + "," + b + "," + a + ")", false); ``` I would like to know the function I would need to return that back to a number. for example if i have AARRGGBB of (FFFF0000) and I would like to get back to the number version that toColor would have derived from. I would be ok with the unsigned version of the return number or the signed version. Unsigned would be -65536 but the unsigned would be fine as well (not sure what that number would be off top of my head now) I tried to do this but the attempts all end out at 0 which i know is not correct: colorSend |= (parseInt(this.Color.substr(0,2),16) & 255) << 24; colorSend |= (parseInt(this.Color.substr(1, 2), 16) & 255) << 16; colorSend |= (parseInt(this.Color.substr(3, 2), 16) & 255) << 8; the parseInt gives me the 255,0,0 that I think I would expect but the & and the shift logic does not seem correct because & zeros the integers out thus the result was 0
https://Stackoverflow.com/questions/35995696
35,995,696
Ok I was able to get something that seems to work for me. I am simplifying it a bit but for the ARGB i can do something like ``` val = "0xFFFF0000" val = parseInt(val, 16) if((val & 0x80000000) != 0) { val = val - 0x100000000; } ``` So for example for Red with an A of FF I would get- -65536 or with unsigned I can omit the last part.
2016/03/14
I believe this line is problematic: `DigestStudents ds = (DigestStudents) digester.parse(this.getClass().getClassLoader().getResourceAsStream("D:/workspace/RD_Axway/src/leo/test/digester/student/student.xml"));` The resource cannot be found, thus null is being returned.
false
Please help me to know what is wrong with my code.[I tried from this link for Sample.](http://www.theserverside.com/news/1364926/Using-The-Digester-Component) OS : Windows 7 **Code 1 :** ``` DigestStudents ds = (DigestStudents) digester.parse(this.getClass() .getClassLoader() .getResourceAsStream("leo/test/digester/student/student.xml")); ``` **Exception 1:** ``` true:isFile:isHidden:false java.lang.IllegalArgumentException: InputStream to parse is null at org.apache.commons.digester3.Digester.parse(Digester.java:1621) at leo.test.digester.student.DigestStudents.digest(DigestStudents.java:41) at leo.test.digester.student.DigestStudents.main(DigestStudents.java:16) ``` **Code 2 :** ``` File f = new File ("D:/workspace/RD_Axway/src/leo/test/digester/student/student.xml"); System.out.println(f.isFile()+":isFile:isHidden:"+f.isHidden()); DigestStudents ds = (DigestStudents) digester.parse(f); ``` **Exception 2:** ``` true:isFile:isHidden:false log4j:WARN No appenders could be found for logger (org.apache.commons.digester3.Digester). log4j:WARN Please initialize the log4j system properly. java.lang.NullPointerException at org.apache.commons.digester3.Digester.getXMLReader(Digester.java:790) at org.apache.commons.digester3.Digester.parse(Digester.java:1588) at org.apache.commons.digester3.Digester.parse(Digester.java:1557) at leo.test.digester.student.DigestStudents.digest(DigestStudents.java:41) at leo.test.digester.student.DigestStudents.main(DigestStudents.java:16) ``` **Student.java** ``` package leo.test.digester.student; public class Student { private String name; private String course; public Student() { } public String getName() { return name; } public void setName(String newName) { name = newName; } public String getCourse() { return course; } public void setCourse(String newCourse) { course = newCourse; } public String toString() { return("Name="+this.name + " & Course=" + this.course); } } ``` **student.xml** ``` <?xml version="1.0" encoding="UTF-8"?> <students> <student> <name>Java Boy</name> <course>JSP</course> </student> <student> <name>Java Girl</name> <course>EJB</course> </student> </students> ``` **DigestStudents.java** ``` package leo.test.digester.student; import java.util.Vector; import org.apache.commons.digester3.Digester; public class DigestStudents { Vector students; public DigestStudents() { students= new Vector(); } public static void main(String[] args) { DigestStudents digestStudents = new DigestStudents(); digestStudents.digest(); } private void digest() { try { Digester digester = new Digester(); //Push the current object onto the stack digester.push(this); //Creates a new instance of the Student class digester.addObjectCreate( "students/student", Student.class ); //Uses setName method of the Student instance //Uses tag name as the property name digester.addBeanPropertySetter( "students/student/name"); //Uses setCourse method of the Student instance //Explicitly specify property name as 'course' digester.addBeanPropertySetter( "students/student/course", "course" ); //Move to next student digester.addSetNext( "students/student", "addStudent" ); File f = new File ("D:/workspace/RD_Axway/src/leo/test/digester/student/student.xml"); System.out.println(f.isFile()+":isFile:isHidden:"+f.isHidden()); DigestStudents ds = (DigestStudents) digester.parse(this.getClass() .getClassLoader() .getResourceAsStream("D:/workspace/RD_Axway/src/leo/test/digester/student/student.xml")); //Print the contents of the Vector System.out.println("Students Vector "+ds.students); } catch (Exception ex) { ex.printStackTrace(); } } public void addStudent( Student stud ) { //Add a new Student instance to the Vector students.add( stud ); } } ```
https://Stackoverflow.com/questions/18780611
18,780,611
`ClassLoader#getResourceAsStream()` is able to locate files relative to the "**root**" of the classpath. You need to replace this line: ``` DigestStudents ds = (DigestStudents) digester.parse(this.getClass() .getClassLoader() .getResourceAsStream("D:/workspace/RD_Axway/src/leo/test/digester/student/student.xml")); ``` With ``` DigestStudents ds = (DigestStudents) digester.parse(this.getClass() .getClassLoader() .getResourceAsStream("leo/test/digester/student/student.xml")); ```
2013/09/13
The second loop to extract b tags in unnecessary. You have a list of `p` tags and inside them only one `b` and one `span` tag. You can just run a single loop to extract all the `p` tags and then extract the `b` and `span` tag with `p.find('b')`. Here is an example with small payload. ``` from bs4 import BeautifulSoup soup = BeautifulSoup('<div class="post-single-content selectionShareable"> <p><b>1. Disney Cruise Line:</b><span style="font-weight:400;"> Service Score –– 9.59 out of 10</span></p><p><b>2. See’s Candies: </b><span style="font-weight:400;">Service Score –– 9.38 out of 10</span></p><p><b>3. Justice:</b><span style="font-weight:400;"> Service Score –– 9.24 out of 10</span></p></div>', "html.parser") p_tags = list(soup.find_all('p')) for p in p_tags: b_tags = p.find('b') span_tags = p.find('span') b_text = b_tags.getText() if b_tags else "" span_text = span_tags.getText() if span_tags else "" print(b_text + span_text) ```
true
[This is text that I want to scrape](https://i.stack.imgur.com/EPeq8.png) [This is the HTML code for it](https://i.stack.imgur.com/56Ahg.png) ``` soup = BeautifulSoup(html_text, 'html.parser') p_tags = soup.find_all('p')[15:24] for p_tag in p_tags: for b in p_tags.find_all('b'): data = b.string print(data) ``` The above code returns nothing but also does not give an error. What are the changes required?
https://Stackoverflow.com/questions/67684229
67,684,229
To get the desired list you can use next example: ```py import requests from bs4 import BeautifulSoup url = "https://www.the-future-of-commerce.com/2020/03/20/brands-with-the-best-customer-service/" headers = { "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:88.0) Gecko/20100101 Firefox/88.0" } soup = BeautifulSoup(requests.get(url, headers=headers).content, "html.parser") h2 = soup.find("h2", text="Top 10 brands with the best customer service") for row in h2.find_next_siblings( lambda tag: tag.name == "p" and [t.name for t in tag.find_all()] == ["b", "span"] ): b = row.b.get_text(strip=True) span = row.span.get_text(strip=True) print("{:<30} {}".format(b, span)) ``` Prints: ```none 1. Disney Cruise Line: Service Score –– 9.59 out of 10 2. See’s Candies: Service Score –– 9.38 out of 10 3. Justice: Service Score –– 9.24 out of 10 4. Lands’ End: Service Score –– 9.18 out of 10 5. Chick-fil-a: Service Score –– 9.11 out of 10 6. Publix: Service Score –– 9.07 out of 10 7. Vitacost: Service Score –– 9.04 out of 10 8. Avon: Service Score –– 9.02 out of 10 9. Morton’s The Steakhouse: Service Score –– 9.02 out of 10 10. Cracker Barrel: Service Score –– 9.01 out of 10 ``` --- Or: ```py for span in soup.select("b + span"): if not "Service Score" in span.text: continue print( span.find_previous("b").text, span.text.replace("Service Score –– ", "") ) ``` Prints: ```none 1. Disney Cruise Line: 9.59 out of 10 2. See’s Candies: 9.38 out of 10 3. Justice: 9.24 out of 10 4. Lands’ End: 9.18 out of 10 5. Chick-fil-a: 9.11 out of 10 6. Publix: 9.07 out of 10 7. Vitacost: 9.04 out of 10 8. Avon: 9.02 out of 10 9. Morton’s The Steakhouse: 9.02 out of 10 10. Cracker Barrel: 9.01 out of 10 ```
2021/05/25
First, you while loop is exhausting your CPU, the variable millisecond is increasing, and decreasing when reach 999, nonstop, CPU never get a break to rest, and everytime the value millisecond changes, you ask panel to repaints, it is impossible mission for your CPU to do that. Second, the millisecond won't work the way you expect it to, unless your CPU take 1 millisecond for every clock cycle, not even a antique computer is that slow. You should replace your while loop with Timer, (Google Java Timer example), so your code get run once every millisecond, which your CPU can handle one handed. :)
false
I'm trying to make a chronometer but when I click on "Iniciar (start)", the program freezes. This is the part that give me problems: ``` ActionListener escucha = new ActionListener() { public void actionPerformed(ActionEvent e) { iniciar.setEnabled(false); pausar.setEnabled(true); reiniciar.setEnabled(true); rb1.setEnabled(false); rb2.setEnabled(false); try { while (true) { milisegundos++; if (milisegundos > 999) { milisegundos = 0; segundos++; if (segundos > 59) { segundos = 0; minutos++; if (minutos > 59) { minutos = 0; horas++; } } } if (milisegundos < 10) { MS = "00"+milisegundos; } else if (milisegundos < 100) { MS = "0"+milisegundos; } else { MS = Integer.toString(milisegundos); } if (segundos < 10) { S = "0"+segundos; } else { S = Integer.toString(segundos); } if (minutos < 10) { M = "0"+minutos; } else { M = Integer.toString(minutos); } if (horas < 10) { H = "0"+horas; } else { H = Integer.toString(horas); } cadena = H+":"+M+":"+":"+S+":"+MS; tiempo.setText(cadena); panel.repaint(); } } catch (Exception w) { w.printStackTrace(); } } }; iniciar.setText("Iniciar"); iniciar.addActionListener(escucha); ``` I have done another similar algorithm but it is a very basic digital clock, with the same method of a while and a Thread.sleep() and it works: ``` import java.util.Date; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.Font; public class asdfasdflkj { public static void main(String[] args) { try { JFrame frame = new JFrame(); JPanel panel = new JPanel(); JLabel lblHoli = new JLabel("Holi"); lblHoli.setFont(new Font("Arial", Font.PLAIN, 43)); frame.setTitle("Hola Gráfica"); frame.setSize(400, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(panel); panel.setLayout(null); panel.add(lblHoli); lblHoli.setBounds(10, 11, 364, 106); int hora, minuto, segundo; while (true) { Date dt = new Date(); hora = dt.getHours(); minuto = dt.getMinutes(); segundo = dt.getSeconds(); lblHoli.setText(hora+":"+minuto+":"+segundo); Thread.sleep(1000); } } catch (Exception e) { e.printStackTrace(); } } } ``` Little edit: posting all program code (It's incomplete): ``` import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import java.awt.Toolkit; import javax.swing.SwingConstants; import java.awt.Font; ``` public class principal { ``` public static int horas = 0, minutos = 0, segundos = 0, milisegundos = 0; public static String cadena = "00:00:00:00", MS, S, M, H; public static boolean condición = true, alredySelected = false; public static void main(String[] args) { JFrame frame = new JFrame(); JPanel panel = new JPanel(); JPanel panel_botones = new JPanel(); JPanel panel_opciones = new JPanel(); JRadioButton rb1 = new JRadioButton(); JRadioButton rb2 = new JRadioButton(); ButtonGroup bg = new ButtonGroup(); JButton iniciar = new JButton(); JButton pausar = new JButton(); JButton reiniciar = new JButton(); Dimension minimumSize = new Dimension(400, 200); JTextField tiempo = new JTextField(cadena); JCheckBox siempreArriba = new JCheckBox(); tiempo.setFont(new Font("Arial", Font.BOLD, 45)); tiempo.setHorizontalAlignment(SwingConstants.CENTER); tiempo.setEditable(false); pausar.setEnabled(false); reiniciar.setEnabled(false); frame.setTitle("Cronómetro"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(minimumSize); frame.setMinimumSize(minimumSize); frame.setLocationRelativeTo(null); frame.setVisible(true); frame.setIconImage(Toolkit.getDefaultToolkit().getImage(principal.class.getResource("/icons/icono.png"))); panel.setLayout(new BorderLayout()); panel.add(panel_botones, BorderLayout.PAGE_END); panel.add(panel_opciones, BorderLayout.PAGE_START); panel.add(tiempo, BorderLayout.CENTER); panel.add(siempreArriba, BorderLayout.EAST); panel_botones.setLayout(new FlowLayout()); panel_botones.add(iniciar); panel_botones.add(pausar); panel_botones.add(reiniciar); siempreArriba.setText("Siempre arriba"); siempreArriba.addItemListener(new ItemListener(){ public void itemStateChanged(ItemEvent e) { if (siempreArriba.isSelected()) { frame.setAlwaysOnTop(true); }else{ frame.setAlwaysOnTop(false); } } }); ActionListener escucha = new ActionListener() { public void actionPerformed(ActionEvent e) { iniciar.setEnabled(false); pausar.setEnabled(true); reiniciar.setEnabled(true); rb1.setEnabled(false); rb2.setEnabled(false); try { while (true) { milisegundos++; if (milisegundos > 999) { milisegundos = 0; segundos++; if (segundos > 59) { segundos = 0; minutos++; if (minutos > 59) { minutos = 0; horas++; } } } if (milisegundos < 10) { MS = "00"+milisegundos; } else if (milisegundos < 100) { MS = "0"+milisegundos; } else { MS = Integer.toString(milisegundos); } if (segundos < 10) { S = "0"+segundos; } else { S = Integer.toString(segundos); } if (minutos < 10) { M = "0"+minutos; } else { M = Integer.toString(minutos); } if (horas < 10) { H = "0"+horas; } else { H = Integer.toString(horas); } cadena = H+":"+M+":"+":"+S+":"+MS; tiempo.setText(cadena); panel.repaint(); } } catch (Exception w) { w.printStackTrace(); } } }; iniciar.setText("Iniciar"); iniciar.addActionListener(escucha); pausar.setText("Pausar"); pausar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { condición = false; pausar.setEnabled(false); iniciar.setEnabled(true); iniciar.setText("Reanudar"); } }); reiniciar.setText("Reiniciar"); reiniciar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); rb1.setText("Cronómetro"); rb1.setSelected(true); rb1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { alredySelected = false; } }); rb2.setText("Cuenta regresiva"); rb2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { if (rb2.isSelected() && alredySelected==false) { alredySelected = true; String temp = JOptionPane.showInputDialog(frame, "Ingrese el número en segundos:"); while (temp.equals("")) { JOptionPane.showMessageDialog(frame, "¡Debe ingresar un valor!", "Error", JOptionPane.ERROR_MESSAGE); temp = JOptionPane.showInputDialog(frame, "Ingrese el número en segundos:"); } horas = Integer.parseInt(temp); } } catch (java.lang.NumberFormatException x) { JOptionPane.showMessageDialog(frame, "¡Solo debe ingresar números!", "Error", JOptionPane.ERROR_MESSAGE); rb1.setSelected(true); alredySelected = false; } catch (java.lang.NullPointerException x) { rb1.setSelected(true); alredySelected = false; } } }); bg.add(rb1); bg.add(rb2); panel_opciones.setLayout(new FlowLayout()); panel_opciones.add(rb1); panel_opciones.add(rb2); } } ```
https://Stackoverflow.com/questions/41584711
41,584,711
Basically, you're violating the single threaded nature of Swing. 1. Never update the UI from any thread other then the Event Dispatching Thread 2. Never block the Event Dispatching Thread Doing the second will prevent the EDT from updating the UI (and responding to events and other important things) Take a look at [The Event Dispatching Thread](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html) for more details In your case, a Swing `Timer` would be more then sufficient. Have a look at [Swing Timer](https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html) for more details ``` import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import java.awt.Toolkit; import javax.swing.SwingConstants; import java.awt.Font; import javax.swing.SwingUtilities; import javax.swing.Timer; public class Principal { public int horas = 0, minutos = 0, segundos = 0, milisegundos = 0; public String cadena = "00:00:00:00", MS, S, M, H; public boolean condición = true, alredySelected = false; private Timer timer; public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new Principal(); } }); } public Principal() { JFrame frame = new JFrame(); JPanel panel = new JPanel(); JPanel panel_botones = new JPanel(); JPanel panel_opciones = new JPanel(); JRadioButton rb1 = new JRadioButton(); JRadioButton rb2 = new JRadioButton(); ButtonGroup bg = new ButtonGroup(); JButton iniciar = new JButton(); JButton pausar = new JButton(); JButton reiniciar = new JButton(); Dimension minimumSize = new Dimension(400, 200); JTextField tiempo = new JTextField(cadena); JCheckBox siempreArriba = new JCheckBox(); tiempo.setFont(new Font("Arial", Font.BOLD, 45)); tiempo.setHorizontalAlignment(SwingConstants.CENTER); tiempo.setEditable(false); tiempo.setColumns(11); pausar.setEnabled(false); reiniciar.setEnabled(false); frame.setTitle("Cronómetro"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setVisible(true); // frame.setIconImage(Toolkit.getDefaultToolkit().getImage(Principal.class.getResource("/icons/icono.png"))); panel.setLayout(new BorderLayout()); panel.add(panel_botones, BorderLayout.PAGE_END); panel.add(panel_opciones, BorderLayout.PAGE_START); panel.add(tiempo, BorderLayout.CENTER); panel.add(siempreArriba, BorderLayout.EAST); panel_botones.setLayout(new FlowLayout()); panel_botones.add(iniciar); panel_botones.add(pausar); panel_botones.add(reiniciar); siempreArriba.setText("Siempre arriba"); siempreArriba.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (siempreArriba.isSelected()) { frame.setAlwaysOnTop(true); } else { frame.setAlwaysOnTop(false); } } }); timer = new Timer(1, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { milisegundos++; if (milisegundos > 999) { milisegundos = 0; segundos++; if (segundos > 59) { segundos = 0; minutos++; if (minutos > 59) { minutos = 0; horas++; } } } if (milisegundos < 10) { MS = "00" + milisegundos; } else if (milisegundos < 100) { MS = "0" + milisegundos; } else { MS = Integer.toString(milisegundos); } if (segundos < 10) { S = "0" + segundos; } else { S = Integer.toString(segundos); } if (minutos < 10) { M = "0" + minutos; } else { M = Integer.toString(minutos); } if (horas < 10) { H = "0" + horas; } else { H = Integer.toString(horas); } cadena = H + ":" + M + ":" + S + ":" + MS; tiempo.setText(cadena); panel.repaint(); } }); ActionListener escucha = new ActionListener() { public void actionPerformed(ActionEvent e) { milisegundos = 0; iniciar.setEnabled(false); pausar.setEnabled(true); reiniciar.setEnabled(true); rb1.setEnabled(false); rb2.setEnabled(false); timer.start(); // try { // while (true) { // milisegundos++; // if (milisegundos > 999) { // milisegundos = 0; // segundos++; // if (segundos > 59) { // segundos = 0; // minutos++; // if (minutos > 59) { // minutos = 0; // horas++; // } // } // } // // if (milisegundos < 10) { // MS = "00" + milisegundos; // } else if (milisegundos < 100) { // MS = "0" + milisegundos; // } else { // MS = Integer.toString(milisegundos); // } // // if (segundos < 10) { // S = "0" + segundos; // } else { // S = Integer.toString(segundos); // } // // if (minutos < 10) { // M = "0" + minutos; // } else { // M = Integer.toString(minutos); // } // // if (horas < 10) { // H = "0" + horas; // } else { // H = Integer.toString(horas); // } // // cadena = H + ":" + M + ":" + ":" + S + ":" + MS; // tiempo.setText(cadena); // panel.repaint(); // // } // } catch (Exception w) { // w.printStackTrace(); // } } }; iniciar.setText("Iniciar"); iniciar.addActionListener(escucha); pausar.setText("Pausar"); pausar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { condición = false; pausar.setEnabled(false); iniciar.setEnabled(true); iniciar.setText("Reanudar"); timer.stop(); } }); reiniciar.setText("Reiniciar"); reiniciar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { timer.start(); } }); rb1.setText("Cronómetro"); rb1.setSelected(true); rb1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { alredySelected = false; } }); rb2.setText("Cuenta regresiva"); rb2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { if (rb2.isSelected() && alredySelected == false) { alredySelected = true; String temp = JOptionPane.showInputDialog(frame, "Ingrese el número en segundos:"); while (temp.equals("")) { JOptionPane.showMessageDialog(frame, "¡Debe ingresar un valor!", "Error", JOptionPane.ERROR_MESSAGE); temp = JOptionPane.showInputDialog(frame, "Ingrese el número en segundos:"); } horas = Integer.parseInt(temp); } } catch (java.lang.NumberFormatException x) { JOptionPane.showMessageDialog(frame, "¡Solo debe ingresar números!", "Error", JOptionPane.ERROR_MESSAGE); rb1.setSelected(true); alredySelected = false; } catch (java.lang.NullPointerException x) { rb1.setSelected(true); alredySelected = false; } } }); bg.add(rb1); bg.add(rb2); panel_opciones.setLayout(new FlowLayout()); panel_opciones.add(rb1); panel_opciones.add(rb2); frame.add(panel); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } ``` Personally, I don't like incrementing a counter in a `Timer` like this, as the `Timer` is inaccurate, a better solution would be to keep a starting point in time and calculate the difference between when the `Timer` ticks and this point, but, that's me
2017/01/11
try ``` $('label.button').live('click', function() { alert(1); }); ``` or ``` $('ul#more-items').delegate('label.button','click', function() { alert(1); }); ```
true
Here's my code: HTML: ``` <ul id="more-items"> <li><label class="button">hi</label></li> <li><label class="button">hi</label></li> <li><label class="button">hi</label></li> </ul> ``` Javascript: ``` $('ul#more-items label.button').live('click', function() { alert(1); }); ``` Clicking on the labels doesn't cause the alert() to fire. The .live() bind seems to have no affect on the label element... If I change it to use .click() or even .bind(), it works perfectly. Is there any reason why .live() isn't working? Is there a way to fix this? The reason I'm using .live() is because `ul#more-items` will be readded to the page multiple times and I don't want to have to fire off a function each time that happens to rebind the click.
https://Stackoverflow.com/questions/2971129
2,971,129
jQuery's `live()` method relies on event bubbling (all the way up to the root node) to work. If there's any code that will stop the bubbling of the event on either the `label` or any of its ancestors, `live()` will not work. Any chance that the `label` or one of its ancestors has a handler with either of the following? ``` return false; ``` or ``` event.stopPropagation(); ``` If so, `live()` will fail. --- **Relevant jQuery docs:** * `.live()` - <http://api.jquery.com/live/> * `.stopPropagation()` - [http://api.jquery.com/event.stopPropagation/](http://api.jquery.com/http://api.jquery.com/event.stopPropagation/)
2010/06/04
Are you parsing the DATABASE\_URL environment variable? It will look something like this: ``` postgres://username:password@host:port/database_name ``` So you will want to pull that in and parse it before you open a connection to your database. Depending on how you've declared your database (in your config or next to your wsgi app) it might look like this: ``` import os import urlparse urlparse.uses_netloc.append('postgres') url = urlparse.urlparse(os.environ['DATABASE_URL']) # for your config DATABASE = { 'engine': 'peewee.PostgresqlDatabase', 'name': url.path[1:], 'password': url.password, 'host': url.hostname, 'port': url.port, } ``` See the notes here: <https://devcenter.heroku.com/articles/django>
true
I am attempting to deploy a [Flask](http://flask.pocoo.org/) app to [Heroku](http://www.heroku.com/). I'm using [Peewee](http://peewee.readthedocs.org/en/latest/) as an ORM for a Postgres database. When I follow the [standard Heroku steps to deploying Flask](https://devcenter.heroku.com/articles/python), the web process crashes after I enter `heroku ps:scale web=1`. Here's what the logs say: ``` Starting process with command `python app.py` /app/.heroku/venv/lib/python2.7/site-packages/peewee.py:2434: UserWarning: Table for <class 'flask_peewee.auth.User'> ("user") is reserved, please override using Meta.db_table cls, _meta.db_table, Traceback (most recent call last): File "app.py", line 167, in <module> auth.User.create_table(fail_silently=True) File "/app/.heroku/venv/lib/python2.7/site-packages/peewee.py", line 2518, in create_table if fail_silently and cls.table_exists(): File "/app/.heroku/venv/lib/python2.7/site-packages/peewee.py", line 2514, in table_exists return cls._meta.db_table in cls._meta.database.get_tables() File "/app/.heroku/venv/lib/python2.7/site-packages/peewee.py", line 507, in get_tables ORDER BY c.relname""") File "/app/.heroku/venv/lib/python2.7/site-packages/peewee.py", line 313, in execute cursor = self.get_cursor() File "/app/.heroku/venv/lib/python2.7/site-packages/peewee.py", line 310, in get_cursor return self.get_conn().cursor() File "/app/.heroku/venv/lib/python2.7/site-packages/peewee.py", line 306, in get_conn self.connect() File "/app/.heroku/venv/lib/python2.7/site-packages/peewee.py", line 296, in connect self.__local.conn = self.adapter.connect(self. database, **self.connect_kwargs) File "/app/.heroku/venv/lib/python2.7/site-packages/peewee.py", line 199, in connect return psycopg2.connect(database=database, **kwargs) File "/app/.heroku/venv/lib/python2.7/site-packages/psycopg2/__init__.py", line 179, in connect connection_factory=connection_factory, async=async) psycopg2.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? Process exited with status 1 State changed from starting to crashed ``` I've tried a bunch of different things to get Heroku to allow my app to talk to a Postgres db, but haven't had any luck. Is there an easy way to do this? What do I need to do to configure Flask/Peewee so that I can use a db on Heroku?
https://Stackoverflow.com/questions/10755833
10,755,833
According to the [Peewee docs](http://docs.peewee-orm.com/en/latest/peewee/database.html?highlight=postgres#dynamically-defining-a-database), you don't want to use `Proxy()` unless your local database driver is different than your remote one (i.e. locally, you're using SQLite and remotely you're using Postgres). If, however, you are using Postgres both locally and remotely it's a much simpler change. In this case, you'll want to only change the connection values (database name, username, password, host, port, etc.) at runtime and do not need to use `Proxy()`. Peewee has a [built-in URL parser for database connections](http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#database-url). Here's how to use it: ``` import os from peewee import * from playhouse.db_url import connect db = connect(os.environ.get('DATABASE_URL')) class BaseModel(Model): class Meta: database = db ``` In this example, peewee's `db_url` module reads the environment variable `DATABASE_URL` and parses it to extract the relevant connection variables. It then creates a `PostgresqlDatabase` [object](http://docs.peewee-orm.com/en/latest/peewee/api.html#PostgresqlDatabase) with those values. Locally, you'll want to set `DATABASE_URL` as an environment variable. You can do this according to the instructions of whatever shell you're using. Or, if you want to use the Heroku toolchain (launch your local server using `heroku local`) you can [add it to a file called `.env` at the top level of your project](https://devcenter.heroku.com/articles/heroku-local#set-up-your-local-environment-variables). For the remote setup, you'll want to [add your database URL as a remote Heroku environment variable](https://devcenter.heroku.com/articles/config-vars#setting-up-config-vars-for-a-deployed-application). You can do this with the following command: ``` heroku config:set DATABASE_URL=postgresql://myurl ``` You can find that URL by going into Heroku, navigating to your database, and clicking on "database credentials". It's listed under `URI`.
2012/05/25
This works like charm! So I edited the code as per my requirement. And here are the changes: It will save the id number from the response into the environment variable. ``` var jsonData = JSON.parse(responseBody); for (var i = 0; i < jsonData.data.length; i++) { var counter = jsonData.data[i]; postman.setEnvironmentVariable("schID", counter.id); } ```
true
I'm using Sencha Touch (ExtJS) to get a JSON message from the server. The message I receive is this one : ``` { "success": true, "counters": [ { "counter_name": "dsd", "counter_type": "sds", "counter_unit": "sds" }, { "counter_name": "gdg", "counter_type": "dfd", "counter_unit": "ds" }, { "counter_name": "sdsData", "counter_type": "sds", "counter_unit": " dd " }, { "counter_name": "Stoc final", "counter_type": "number ", "counter_unit": "litri " }, { "counter_name": "Consum GPL", "counter_type": "number ", "counter_unit": "litri " }, { "counter_name": "sdg", "counter_type": "dfg", "counter_unit": "gfgd" }, { "counter_name": "dfgd", "counter_type": "fgf", "counter_unit": "liggtggggri " }, { "counter_name": "fgd", "counter_type": "dfg", "counter_unit": "kwfgf " }, { "counter_name": "dfg", "counter_type": "dfg", "counter_unit": "dg" }, { "counter_name": "gd", "counter_type": "dfg", "counter_unit": "dfg" } ] } ``` My problem is that I can't parse this JSON object so that i can use each of the counter objects. I'm trying to acomplish that like this : ``` var jsonData = Ext.util.JSON.decode(myMessage); for (var counter in jsonData.counters) { console.log(counter.counter_name); } ``` What am i doing wrong ? Thank you!
https://Stackoverflow.com/questions/9991805
9,991,805
"Sencha way" for interacting with server data is setting up an `Ext.data.Store` proxied by a `Ext.data.proxy.Proxy` (in this case `Ext.data.proxy.Ajax`) furnished with a `Ext.data.reader.Json` (for JSON-encoded data, there are other readers available as well). For writing data back to the server there's a `Ext.data.writer.Writer`s of several kinds. Here's an example of a setup like that: ``` var store = Ext.create('Ext.data.Store', { fields: [ 'counter_name', 'counter_type', 'counter_unit' ], proxy: { type: 'ajax', url: 'data1.json', reader: { type: 'json', idProperty: 'counter_name', rootProperty: 'counters' } } }); ``` `data1.json` in this example (also available in [this fiddle](https://fiddle.sencha.com/#view/editor&fiddle/20hi)) contains your data verbatim. `idProperty: 'counter_name'` is probably optional in this case but usually points at primary key attribute. `rootProperty: 'counters'` specifies which property contains array of data items. With a store setup this way you can re-read data from the server by calling `store.load()`. You can also wire the store to any Sencha Touch appropriate UI components like grids, lists or forms.
2012/04/03
According [this fiddle](https://jsfiddle.net/gLu18aho/) bootstrap was installed successfully All you need is to use [`bootstrap 4 spacing`](https://getbootstrap.com/docs/4.0/utilities/spacing/) See example:(I use `mb-1` to the first wrap div what means `margin-bottom` ) ```html <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script> <div class="mb-1"> <button type="button" class="btn btn-primary">Primary</button> <button type="button" class="btn btn-secondary">Secondary</button> <button type="button" class="btn btn-success">Success</button> <button type="button" class="btn btn-danger">Danger</button> <button type="button" class="btn btn-warning">Warning</button> <button type="button" class="btn btn-info">Info</button> <button type="button" class="btn btn-light">Light</button> <button type="button" class="btn btn-dark">Dark</button> </div> <div> <button type="button" class="btn btn-primary">Primary</button> <button type="button" class="btn btn-secondary">Secondary</button> <button type="button" class="btn btn-success">Success</button> <button type="button" class="btn btn-danger">Danger</button> <button type="button" class="btn btn-warning">Warning</button> <button type="button" class="btn btn-info">Info</button> <button type="button" class="btn btn-light">Light</button> <button type="button" class="btn btn-dark">Dark</button> </div> ```
true
I have the following scenario: ``` public abstract class BaseTask{...} public class TaskA extends BaseTask {....} public class TaskB extends BaseTask {....} public interface TaskService<T extends BaseTask>{ void process(T task); } @Service @Qualifier("taskServiceA") public class TaskServiceA<TaskA> implements TaskService<TaskA>{ } @Service @Qualifier("taskServiceB") public class TaskServiceB<TaskB> implements TaskService<TaskB>{ } public class ProcessingService{ @Autowired @Qualifier("taskServiceA") private TaskService<TaskA> taskAService; @Autowired @Qualifier("taskServiceB") private TaskService<TaskB> taskBService; public void process(Order o){ BaseTask task = o.getTask(); getTaskService(o).start(task); } private <T extends BaseTask> TaskService<T> getTaskService(Order o){ if("atype".equals(o.type)){ return (TaskService<T>) taskAService; } else if("btype".equals(o.type)){ return (TaskService<T>) taskBService; } } } ``` **Update: I have reworded the question because the answers I was getting was not what I was looking for.** My questions is related to the getTaskService method. 1. Why do I need to cast the return value like this return (TaskService) taskAService; 2. Is there another way to implement the getTaskService() method without having to do the cast? I will really appreciate if someone can provide some explanation or better implementation for the `getTaskService` method.
https://Stackoverflow.com/questions/53276456
53,276,456
It is due to the [preserveWhitespaces](https://angular.io/api/core/Component#preserveWhitespaces) option which is false by default and nothing to do with bootstrap. You can enable it by the setting that option to true as follows: ``` @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ], preserveWhitespaces: true }) ``` demo: <https://stackblitz.com/edit/angular-cabspk>
2018/11/13
You may do this via two aggregations: ``` SELECT Column1, SUM(Column3Avg) AS Column3 FROM ( SELECT Column1, Column2, AVG(Column3) AS Column3Avg FROM yourTable GROUP BY Column1, Column2 ) t GROUP BY Column1; ``` This approach first aggregates by both the first and second column, to generate an intermediate result looking like: ``` Column1 | Column2 | Column3Avg H1 | A1 | 10 H1 | A2 | 30 ``` Then, we aggregate the above by the first column alone, and sum the column 3 averages.
true
Let's suppose in a pandas dataframe I have for a certain record: ``` x.index.quarter ``` is 3 I need to generate an integer from 1 to 365 as day of the year, that would belong to the same quarter. How does pandas decide the year quarter? Is there a mathematical formula? Does it depends only on the months?
https://Stackoverflow.com/questions/62449880
62,449,880
``` SELECT column1, SUM(Avg_col3) AS total FROM ( SELECT column1, column2, AVG(column3) AS avg_col3 FROM t GROUP BY column1, column2 ) A GROUP BY column1; ```
2020/06/18
Here's a version without the ugly `while True` pattern and without other modules: ``` for line in iter(original.readline, ''): if …: # to the beginning of the title or abstract for i in range(lineNumber): print original.readline(), break ```
true
I'm writing a script that logs errors from another program and restarts the program where it left off when it encounters an error. For whatever reasons, the developers of this program didn't feel it necessary to put this functionality into their program by default. Anyways, the program takes an input file, parses it, and creates an output file. The input file is in a specific format: ```none UI - 26474845 TI - the title (can be any number of lines) AB - the abstract (can also be any number of lines) ``` When the program throws an error, it gives you the reference information you need to track the error - namely, the UI, which section (title or abstract), and the line number relative to the beginning of the title or abstract. I want to log the offending sentences from the input file with a function that takes the reference number and the file, finds the sentence, and logs it. The best way I could think of doing it involves moving forward through the file a specific number of times (namely, n times, where n is the line number relative to the beginning of the seciton). The way that seemed to make sense to do this is: ``` i = 1 while i <= lineNumber: print original.readline() i += 1 ``` I don't see how this would make me lose data, but Python thinks it would, and says `ValueError: Mixing iteration and read methods would lose data`. Does anyone know how to do this properly?
https://Stackoverflow.com/questions/826493
826,493
Use `for` and [enumerate](http://docs.python.org/library/functions.html#enumerate). Example: ``` for line_num, line in enumerate(file): if line_num < cut_off: print line ``` **NOTE**: This assumes you are already cleaning up your file handles, etc. Also, the [takewhile](http://docs.python.org/library/itertools.html#itertools.takewhile) function could prove useful if you prefer a more functional flavor.
2009/05/05
There are different ways of achieving the output you are looking for. Here is one among them, I have used [`Object.keys`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), [`Object.entries`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) and [`Object.values`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values) along with [`Array.forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) ```js let data = {cases:{'10/6/20':35806972,'10/7/20':36156226,'10/8/20':36515563,'10/9/20':36876248,'10/10/20':37105925},deaths:{'10/6/20':1049875,'10/7/20':1055683,'10/8/20':1061877,'10/9/20':1068040,'10/10/20':1071388},recovered:{'10/6/20':24834868,'10/7/20':25088883,'10/8/20':25306451,'10/9/20':25509379,'10/10/20':25610521}}; const formatData = (data) => { const finalRes = {}; Object.keys(data).forEach(key => { Object.entries(data[key]).forEach(([date, val]) => { //Creating/Updating the object with key as `date` in the //finalRes object with the other properties such as `cases`, `deaths` and `recovered` finalRes[date] = { ...finalRes[date], date, [key]: val } }) }); //Finally, converting the object values to an array return Object.values(finalRes); } console.log(formatData(data)); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ```
true
I am not an expert with Jquery, my developer is unavailable . I am using <https://jqcron.arnapou.net/demo/> . This works fine. The code is as follows, ``` $(function(){ $('.example7').jqCron({ enabled_minute: true, multiple_dom: true, multiple_month: true, multiple_mins: true, multiple_dow: true, multiple_time_hours: true, multiple_time_minutes: true, default_period: 'week', default_value: '*/14 */2 */3 * *', bind_to: $('.example7-input'), bind_method: { set: function($element, value) { $element.val(value); } }, no_reset_button: false, lang: 'en' }); }); ``` The html ``` <div class="example7"></div> <input class="example7-input" /> ``` **My problem** I need to add the above function into a number of divs like as follows, ``` <div class="example7"></div> <input class="example7-input" /> <div class="example8"></div> <input class="example8-input" /> <div class="example8"></div> <input class="example8-input" /> ``` The solution is when click on **example7** div the value only need to apply to input box **example7-input** . So each div need to show different values. All these use the same Jquery function. So how can I modify the jQuery function
https://Stackoverflow.com/questions/64301459
64,301,459
You can use `Object.keys` and array `map` method. ```js let data = { "cases": { "10/6/20": 35806972, "10/7/20": 36156226, "10/8/20": 36515563, "10/9/20": 36876248, "10/10/20": 37105925 }, "deaths": { "10/6/20": 1049875, "10/7/20": 1055683, "10/8/20": 1061877, "10/9/20": 1068040, "10/10/20": 1071388 }, "recovered": { "10/6/20": 24834868, "10/7/20": 25088883, "10/8/20": 25306451, "10/9/20": 25509379, "10/10/20": 25610521 }} let keys = Object.keys(data.cases); let modifiedData = keys.map(key => ({ date: key, cases: data.cases[key], deaths: data.deaths[key], recovered: data.recovered[key] })); console.log("modifiedData", modifiedData) ```
2020/10/11
After trying all of the other solutions, it turned out that the problem in my case was that there wasn't enough available storage space - the package installer gives a generic "Install failed" in this case too. Hopefully this saves someone else the hours I wasted.
false
I have a Problem where i need to find the first occurrence of the char according to the order which they occur in the given String. For Example : I have a String **"Unitedin"** where the char **"n"** and **"i"** have a multiple occurrence in the String. **char n** occurred at charAt(1,7) **char i** occurred at charAt (2,6) But the char **"i"** had occurred first before char **"n"**. I have Tried Something like this But i am not getting the required output.Can Anyone Help me please? Note : **Challenge is Not to use any type of List or Hashset or Hashmap** ```java public static void main(String[] args) { Scanner in = new Scanner(System.in); StringBuilder nodup = new StringBuilder(); StringBuilder dup = new StringBuilder(); System.out.println("Enter a string : "); String instring = in.next(); for (int i = 0; i < instring.length(); i++) { for (int j = i + 1; j < instring.length(); j++) { if (instring.charAt(i) == instring.charAt(j)) { nodup.append(instring.charAt(i)); } else { dup.append(instring.charAt(i)); } } } System.out.print(nodup.toString()); ``` i am getting the OutPut as : **ni** . but the Required output is **in**.
https://Stackoverflow.com/questions/58128675
58,128,675
The reason of the message "Installation Failed" or "App not installed" can vary, simply because this is the only error you can get while installing your app. I agree that it is not helpful. However, it is for most cases due to a **signing** issue. Here are some solutions : 1. Make sure you used a Release Signed APK for your Firebase Distribution. <https://developer.android.com/studio/build/build-variants#signing> [![enter image description here](https://i.stack.imgur.com/Obx72.png)](https://i.stack.imgur.com/Obx72.png) 2. When you generate your signed APK, you can choose V1 or V2 signatures. Try using the V1 signature. V2 signature was a feature introduced in Android 7.0 : <https://developer.android.com/about/versions/nougat/android-7.0#apk_signature_v2> 3. Make sure your app is signed correctly, by checking the values in your file, **`app/build.gradle`** : ``` android { ... defaultConfig {...} signingConfigs { release { storeFile file("myreleasekey.keystore") storePassword "password" keyAlias "MyReleaseKey" keyPassword "password" } } buildTypes { release { ... signingConfig signingConfigs.release } } ``` } Last but not least, make sure that your phone has **enough storage** to install the app, and that the option **"Install from unknown sources"** is checked in the settings.
2019/09/27
One way to do it would be to enumerate your sort explicitly: ```js var definedSort = [1,2,3,4,5,6,7,8,9,10,'1A','1B','1C']; var someArray = ['1A', 4, 8, 5, 1, 9, '1C', '1B']; someArray.sort(function(a,b) { return definedSort.indexOf(a) - definedSort.indexOf(b); }); alert(someArray); ``` However, given your simple restrictions, you can also implement it in more convoluted ways: ```js var someArray = ['1A', 4, 8, 5, 1, 9, '1C', '1B']; someArray.sort(function(a,b) { return (a - b) || -a || +b || (a > b) }); alert(someArray); ```
true
```js var table = [ {"name":"Joe", "Level":1}, {"name":"Bob", "Level":1B}, {"name":"Carl", "Level": 7}, {"name":"Mike", "Level": 1A}, {"name":"Sal", "Level": 2} ] var tableHeaders = scope.SortTableColumnHeaders(table) scope.SortTableColumnHeaders = function (array) { var unique = {}; var distinct = []; for (var i in array) { if (typeof (unique[array[i].Level]) == "undefined") { distinct.push(array[i].Level); } unique[array[i].Level] = 0; } return distinct.sort(); }; ``` I have an object that looks like the above code where I pull out a distinct array like [1,10,1A,1B,2,7] where I can have int (1-10) and strings (1A, 1B, 1C) I want to sort the int's in order first and then the strings second so it will always look like [1...10,1A,1B,1C] I tried distinct.sort(), but that doesn't work.
https://Stackoverflow.com/questions/31327707
31,327,707
Well, ASCII values are continuous, and numbers are lower than chars from the alphabet, so if you can live with the sum of the ASCII values (that would work with `1A`, `1B` and so on) ``` var table = [ {"name":"Joe", "Level": '1'}, {"name":"Bob", "Level": '1B'}, {"name":"Carl", "Level": '7'}, ... ] function sortByCharCode(a,b) { function charCodeInt(s) { result = 0; for (var i=0;i<s.length;i++) { result += s.charCodeAt(i); } return result; } a = charCodeInt(a.Level); b = charCodeInt(b.Level); if (a < b) return -1; if (a > b) return 1; return 0; } $scope.sortTable = function() { $scope.table.sort(sortByCharCode); } ```
2015/07/09
``` $(document).ready(function() { $('#submit').hide(); $('#mobiletask').on('change',function() { if($('#mobiletask').attr('checked')) { check_availability(); //$( "#notifyresult" ).html( "<p>Awesome, we'll send you an email!</p>" ); } }); function check_availability() { //get the username // var username = $('#username').val(); var username = '<?php echo $_GET['id']; ?>'; $.ajax({ url: 'check_username.php', type: 'POST', async: false, data: {'name':'username','value':username}, success: function(result) { alert(result); //if the result is 1 if(result == '1') { //show that the username is available $("#errormessage").html('<p>PLease complete the task before proceeding</p>'); }else if(result == '0') { //show that the username is NOT available $('#submit').show(); } }, error: function(error) { alert(error); } }); } }); ``` \*\* Remove the alerts when done with testing the code. \*\*
true
The instructions here were to create a BowlingScores class and BowlingScoresViewer client class: In the BowlingScores class, create a method named printScores(): * This class should keep track of scores for multiple bowlers. Scores are integer values between 0 and 300. * Create a normal one-dimensional array to keep track of bowler nicknames. Use an initializer list to populate this array with 6 bowler nicknames (6 elements). * Create a two-dimensional array to keep track of multiple scores per bowler + Each bowler has bowled 4 games. -Each row number of this array will correspond to the index of the bowler from the “bowler nicknames” array you just created. + Each column represents one of the four scores for the bowler. + Use an initializer list to populate the scores for each bowler. * Write a loop to process the two arrays as follows: + Loop through each bowler in the bowler array + For each bowler, loop through the corresponding scores for that bowler + Output the bowler nickname and a list of his/her scores to the console similar to the following. + Also, calculate the average score for the bowler [Here is the link to the BowlerScoresViewer class](http://www.wsfcs.k12.nc.us/cms/lib/NC01001395/Centricity/domain/173/2010-2011/homework/java%20concepts/BowlingScoresViewer.txt) [Here is the link to the BowlerScores class](http://www.wsfcs.k12.nc.us/cms/lib/NC01001395/Centricity/domain/173/2010-2011/homework/java%20concepts/BowlingScores.txt) Right now here is what I have in terms of code I need help with finding the averages and making sure I am doing this right.: ``` package javaconcepts; // import javax.swing.JOptionPane; //BowlingScores is used to practice using parallel arrays and 2-dimensional arrays public class BowlingScores_MatthewBall { public void printScores() { System.out.println("BOWLING SCORES:"); String[] bowlers = {"L'Carpetron Dookmarriot", "Jackmerius Tacktheritrix", "Hingle McCringleberry", "Beezer Twelve Washingbeard", "X-Wing @Aliciousness", "Shakiraquan T.G.I.F. Carter"}; int[][] bowlerScores = {{110, 90, 160, 140, 110}, // row 0 {92, 96, 80, 112, 204}, // row 1 {200, 200, 200, 190, 210}, // row 2 {103, 90, 90, 150, 170}, // row 3 {118, 120, 116, 102, 200}, // row 4 {96, 96, 80, 112, 200}}; // row 5 /* for (int i = 0; i < bowlers[i].length; i++) { for (int x = 0; x < bowlerScores[x].length; i++) { System.out.println("L'Carpetron Dookmarriot bowled games of " + bowlerScores[x] + " which results in an average of " + "."); System.out.println("Jackmerius Tacktheritrix bowled games of " + bowlerScores[1] + " which results in an average of " + "."); System.out.println("Hingle McCringleberry bowled games of " + bowlerScores[2] + " which results in an average of " + "."); System.out.println("Beezer Twelve Washingbeard bowled games of " + bowlerScores[3] + " which results in an average of " + "."); System.out.println("X-Wing @Aliciousness bowled games of " + bowlerScores[4] + " which results in an average of " + "."); System.out.println("Shakiraquan T.G.I.F. Carter bowled games of " + bowlerScores[5] + " which results in an average of " + "."); } }*/ for (int row = 0; row < bowlers.length; row++) //loops thru rows { System.out.println(""); System.out.print(bowlers[row] + " bowled games of " ); for (int col = 0; col < bowlerScores[0].length; col++) //loops thru columns { System.out.print( bowlerScores[row][col] + ", " ); } System.out.print( "which results in an average of " ); for (int col = 0; col < bowlerScores[0].length; col++) //loops thru columns { System.out.print(bowlerScores[1][2]/bowlerScores[0].length); } } } ```
https://Stackoverflow.com/questions/27436579
27,436,579
Based on the response you are getting: ``` <html><body>1</body></html> ``` What you have to do is to work on your **PHP** file and make sure to remove any HTML in it.
2014/12/12
in that case, it is because it never gets into the else statement, it is always false. I usually use alert(string); to debug and know the value of variables, try one at the beginning of the if, or use console.log() I also recommend you to read the following regarding let or var: [What's the difference between using "let" and "var" to declare a variable?](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable).
false
Why does the code below doesn't throw a warning/error about variable re-assignment? I spent a good amount of time debugging something like this because of the trailing comma. When the code inside the else statement is moved outside of the if scope, it throws the proper error. Any explanation would be great. ```js let a if (false) { // Nothing } else { const b = 100, a = 10 } console.log(a) // undefined ```
https://Stackoverflow.com/questions/47180800
47,180,800
In else condition, a is re declared as const.So whatever the value (u assigned 10) within in else condition. you have to put ; at end of b declaration. otherwise `a` will be declared as const.So, `a` value is undefined in the outside of else condition. ```js let a if (false) { // Nothing } else { const b = 100; a = 10 } console.log(a) ```
2017/11/08
Here is my own function that receives a vector of image files and merge them vercially. wstring CombineBitmaps(vector files) { wstring NewFile{ L"Output.png" }; ``` Gdiplus::Status rc; CLSID pngClsid; GetEncoderClsid(L"image/png", &pngClsid); vector< Gdiplus::Bitmap*> bmpSrc; int Height{ 0 }; for (int i = 0; i < files.size(); i++) { bmpSrc.push_back (Gdiplus::Bitmap::FromFile(files[i].c_str())); Height += bmpSrc[0]->GetHeight(); } Gdiplus::Bitmap dstBitmap(bmpSrc[0]->GetWidth(), Height); Gdiplus::Graphics* g = Gdiplus::Graphics::FromImage(&dstBitmap); for (int i = 0; i < files.size(); i++) { rc = g->DrawImage(bmpSrc[i], 0, i*bmpSrc[i]->GetHeight()); } rc = dstBitmap.Save(NewFile.c_str(), &pngClsid, NULL); delete g; return NewFile; ``` } You would call it as shown below: ``` vector<wstring> screens; screens.push_back(L"screenshot1"); screens.push_back(L"screenshot2"); screens.push_back(L"screenshot3"); screens.push_back(L"screenshot4"); screens.push_back(L"screenshot5"); CombineBitmaps(screens); ```
true
I'd like to ask one general question about JavaFX implementation strategy. Let's say I already have a java project with many classes and objects that uses maybe swing as a GUI. Now I want to use JavaFX as GUI. I want to display those objects in nice JFX UI. But to use JavaFX and its binding and all that stuff, classes need to utilize JavaFX style properties. The question is: what should I do with all those "old" classes and business objects I already have? Do I need to rewrite at least those to be displayed to new JFX form? But those objects are also used for other purposes like database and file persistence. It doesn't seem to be OK to use JFX properties on plain business objects. Should I wrap BOs in corresponding JFX "brothers"? (This idea remainds me "ViewModel" from .NET WPF MVVM pattern.) Can somenone advice me what's the correct way how to deal with this? Thank you.
https://Stackoverflow.com/questions/17796874
17,796,874
Use a Graphics object to combine them. Here's some sample working code... Of course, you should use smart ptrs like unique\_ptr<> instead of new/delete but I did not want to assume you're using VS 2012 or newer. ``` void CombineImages() { Status rc; CLSID pngClsid; GetEncoderClsid(L"image/png", &pngClsid); Bitmap* bmpSrc1 = Bitmap::FromFile(L"Image1.JPG"); assert(bmpSrc1->GetLastStatus() == Ok); Bitmap* bmpSrc2 = Bitmap::FromFile(L"Image2.JPG"); assert(bmpSrc2->GetLastStatus() == Ok); Bitmap dstBitmap(bmpSrc1->GetWidth(), bmpSrc1->GetHeight() + bmpSrc2->GetHeight()); assert(dstBitmap.GetLastStatus() == Ok); Graphics* g = Graphics::FromImage(&dstBitmap); rc = g->DrawImage(bmpSrc1, 0, 0 ); assert(rc == Ok); rc = g->DrawImage(bmpSrc2, 0, bmpSrc1->GetHeight()); assert(rc == Ok); rc = dstBitmap.Save(L"Output.png", &pngClsid, NULL); assert(rc == Ok); delete g; delete bmpSrc1; delete bmpSrc2; } ``` main fn.. ``` int _tmain(int argc, _TCHAR* argv[]) { ULONG_PTR token; GdiplusStartupInput input; GdiplusStartup(&token, &input, nullptr); CombineImages(); GdiplusShutdown(token); return 0; } ```
2013/07/22
Here with full path, network compatible: ``` (Get-ChildItem "\\folder1\" -Dir).fullname | ForEach {(Get-ChildItem $_ -Dir).name} ``` Want it stored in an array? ``` $subfolders = (Get-ChildItem "\\folder1\" -Dir).fullname | ForEach {(Get-ChildItem $_ -Dir).name} ```
true
Is there a function in Java Script that divide a string with several arguments? ``` var string = "This is a test text, again, this is a testing text"; ``` For example, I can split with `,` by saying `string.split(',');` and I will have: ``` var string = ["This is a test text", "again", "this is a testing text"]; ``` Now, I want to split it with several parameters, so string now would be ``` var string = ["test text", "testing text"] ``` I'm looking for a function that extract all the parts that start with `test` and end with `text`.
https://Stackoverflow.com/questions/39395993
39,395,993
You should just be able to use some fun wildcards to get what you want here. ``` Get-ChildItem \*\*\ | Where-Object{$_.PSIsContainer} ``` Or if you have at least PowerShell 3.0 this would be faster ``` Get-ChildItem \*\*\ -Directory ``` Then if you wanted just the names tack on `| Select-Object -ExpandProperty Name`
2016/09/08
The g in /g stands for global. This make sure that all matches are replaced. In the absence of /g, only the first match is replaced. /i (ignore case) is another commonly used switch. Each time the javascript engine finds a match(for your regular expression) in the string, it calls the function that you passed in with the parameters for each match. Explained in detail [here](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace)
false
I would like to get a deeper understanding of the nuances of javascript. Take the function below: ``` str.replace(/(\b[^:]+):'([^']+)'/g, function ($0, param, value) { ret[param] = value; }); ``` * Why is there a need for /g? * What exactly gets passed into the function? * Where do these values come from? Thanks!
https://Stackoverflow.com/questions/3679372
3,679,372
> > Why is there a need for /g? > > > Because presumably you will have multiple pairs on the matching string, e.g. `a:'b' c:'d'` > > What exactly gets passed into the function? > > > The callback function gets the whole match as the first argument, the two later arguments are the capturing groups specified on your regexp. For example: ``` "a:'b' c:'d'".replace(/(\b[^:]+):'([^']+)'/g, function ($0, param, value) { console.log($0, param, value); }); ``` The callback will be executed twice, and it will show you `"a:'b'"` for `$0`, `"a"` for `param` and `"b"` for `value` on the first execution. In the second execution -for the second match-, will show you `"c:'d'"` for `$0`, `"c"` for `param` and `"d"` for value.
2010/09/09
I wrote my own distance code ref the top answer, just as it says, it was extremely slow, the built-in distance code was much better. I'm wondering how to speed up.
false
I have objects and a distance function, and want to cluster these using `DBSCAN` method in `scikit-learn`. My objects don't have a representation in Euclidean space. I know, that it is possible to use`precomputed` metric, but in my case it's very impractical, due to large size of distance matrix. Is there any way to overcome this in `scikit-learn`? Maybe, are there another python implementations of DBSCAN that can do so?
https://Stackoverflow.com/questions/32938494
32,938,494
scikit-learn has support for a large variety of metrics. Some of them can be accelerated using the kdtree (very fast), using the ball tree (fast), using precomputed distance matrixes (fast, but needs a lot of memory) or no precomputation but Cython implementations (quadratic runtime) or even python callbacks (very slow). This last option that is implemented but extremely slow: ``` def mydistance(x,y): return numpy.sum((x-y)**2) labels = DBSCAN(eps=eps, min_samples=minpts, metric=mydistance).fit_predict(X) ``` is, unfortunately, much much much much slower than ``` labels = DBSCAN(eps=eps, min_samples=minpts, metric='euclidean').fit_predict(X) ``` I found ELKI to perform much better when you need to use your own distance functions. Java can compile them into near native code speed using the Hotspot JNI compiler. Python (currently) cannot do this.
2015/10/04
For Chrome browser, just need to set `Capability.ACCEPT_INSECURE_TLS_CERTS, true`. It is working for me. ``` const { Builder, By, until, Capabilities, Capability } = require('selenium-webdriver'); const capabilities = Capabilities.chrome(); capabilities.set(Capability.ACCEPT_INSECURE_TLS_CERTS, true); this.driver = new Builder() .withCapabilities(capabilities) .forBrowser('chrome') .build(); ```
true
Given these Node dependencies: ``` { "chromedriver": "^2.24.1", "cucumber": "^1.3.0", "geckodriver": "^1.1.2", "phantomjs-prebuilt": "^2.1.12", "selenium-webdriver": "^3.0.0-beta-2" } ``` I would like PhantomJS and Firefox to ignore SSL certificates. Here is how my browser.js looks: ``` require('geckodriver'); // main browser object var browserHandle; // load selenium webdriver and some rules var webdriver = require('selenium-webdriver'), By = webdriver.By, until = webdriver.until; // load phantomjs into webdriver capabilities var phantomjs_exe = require('phantomjs-prebuilt').path; var customPhantom = webdriver.Capabilities.phantomjs(); customPhantom.set("phantomjs.binary.path", phantomjs_exe); webdriver.Builder() //.forBrowser('firefox') //.forBrowser('phantomjs') .withCapabilities(customPhantom) .build(); ``` Any suggestions with `--ignore-ssl-errors=yes`? How can I implement it in the code? I want to use only JavaScript, rather than Java.
https://Stackoverflow.com/questions/39638830
39,638,830
For Firefox, you can use the following code: ``` var driver = new webdriver.Builder().withCapabilities(Capabilities.firefox() .set("acceptInsecureCerts", true)).build(); ```
2016/09/22
This is most likely a Mono runtime bug, reported here: <https://github.com/mono/mono/issues/19893> The workaround is indeed to disable parallel restore by passing `/p:RestoreDisableParallel=true` property to MSBuild.
false
I am building a management system in which the admin can select an item from the database table and update the details. To achieve this I have two forms on two pages. The first form is to select the item from table and pass it's ID to the second page where I will use the ID to fetch the details from the table using php. I want to do this with javascript so it will not refresh the page. My question is how to pass this value? I am using the following code, but it is not working. **HTML** ``` <div id="result"></div> <form action="update_item.php" id="update" method="post" > <select name="selected" class="form-control" id="myItem" required> <option>Select item</option> <?php <!-- PHP script to select the item --> ?> </select> <button id="submit">Select</button> </form> ``` **JAVASCRIPT** ``` $(document).ready(function() { $("#submit").click(function() { var chat = $('#myItem').val(); if(chat=='') { alert("Please select an item!"); } else{ $.ajax({ type: "POST", url:"update_item.php", data:{ data:chat, }, success: function (msg) { //alert(msg): $('#result').html(msg); }, error: function(){ alert('error'); } }); } }); }); ``` **PHP** Second page ``` $item_id = $_POST['data']; $get_item = "select * from items where item_id='$item_id'"; <--PHP script continues--> ```
https://Stackoverflow.com/questions/46133427
46,133,427
I cannot help with the networking problem but you may be able to reduce the amount of NuGet packages that are being downloaded by Visual Studio for Mac as a possible workaround. This can be done for a .NET Core 2.0 project by using the NuGet fallback folder: ``` /usr/local/share/dotnet/sdk/NuGetFallbackFolder/ ``` The fallback folder holds many NuGet packages that are used by .NET Core 2.0 by default. This folder should be created if you install the .NET Core SDK. Using the above folder will prevent a lot of NuGet packages from being downloaded. You can either add it directly as a NuGet package source or edit your ~/.config/NuGet/NuGet.Config file and add the fallback folder as follows: Alternatively you could add an explicit fallback folder into your ~/.config/NuGet/NuGet.Config file: ``` <fallbackPackageFolders> <add key="DotNetCore2FallbackFolder" value="/usr/local/share/dotnet/sdk/NuGetFallbackFolder" /> </fallbackPackageFolders> ``` Visual Studio for Mac would need to be restarted. Also check that the folder exists. Note that due to another bug Visual Studio for Mac will still download a few NuGet packages when restoring a .NET Core project.
2017/09/09
You can use a specify the range (min/max) in `Math.random` function and then use this function `Math.floor(Math.random() * (max - min + 1)) + min;` to limit the returned value of the random function between min and max. * `maxTop` : height of the container - height of shape * `maxLeft` : width of the container - width of shape * `minTop` : 0 * `minLeft` : 0 > > You need to use `position:absolute` and `px` value on shape for this to work > > > **See code snippet:** ```js function position() { var minTop = 0; var maxTop = document.getElementById("playSpace").clientHeight - document.getElementById("shape").clientHeight; var minLeft = 0; var maxLeft = document.getElementById("playSpace").clientWidth - document.getElementById("shape").clientWidth ; var positionTop = Math.floor(Math.random() * (maxTop - minTop + 1) + minTop); var positionLeft = Math.floor(Math.random() * (maxLeft - minLeft + 1) + minLeft); var position = "position:absolute;top:" + positionTop + "px;left:" + positionLeft + "px;" return position; } document.getElementById("shape").onclick = function() { document.getElementById("shape").style.cssText = position(); } ``` ```css #gameSpace { width: 100%; height: 470px; background: blue; margin: 0; padding-top: 30px; text-align:center; } #playSpace { width: 90%; height: 90%; border: 1px black solid; position:relative; display:inline-block; } #shape { width: 100px; height: 100px; background-color: red; } ``` ```html <div id="gameSpace"> <div id="playSpace"> <!-- here we put the shape --> <div id="shape"></div> </div> </div> ```
true
I have a square, when clicked it appears in a random location and it also change size (so for example if I have a 30px box but it is 10px from the left border I still get 10px outside the gamespace). sometimes the square exceed his container border How can I make sure that the square will never exceed his container? ```js function position() { var positionTop = Math.random() * 100; var positionLeft = Math.random() * 100; var position = "position:relative;top:" + positionTop + "%;left:" + positionLeft + "%;" return position; } document.getElementById("shape").onclick = function() { document.getElementById("shape").style.cssText = position(); } ``` ```css #gameSpace { width: 100%; height: 470px; background: blue; margin: 0; padding-top: 30px; } #playSpace { width: 90%; height: 90%; margin: 0 auto; margin-top: 10px; border: 1px black solid; } #shape { width: 100px; height: 100px; background-color: red; } ``` ```html <div id="gameSpace"> <div id="playSpace"> <!-- here we put the shape --> <div id="shape"></div> </div> </div> ```
https://Stackoverflow.com/questions/44384278
44,384,278
You need to set `position: relative;` to the parent element and `position: absolute;` to the `shape` element. Then use max min value for random where max is the parent width/height and subtract the `shape` width/height ... **This is snippet before update** ```js function position() { var playSpace = document.querySelector('#playSpace'); var shape = document.getElementById("shape"); var maxHeight = playSpace.offsetHeight - shape.offsetHeight; var maxWidth = playSpace.offsetWidth - shape.offsetWidth; var positionTop = Math.random() * (maxHeight - 0) + 0; var positionLeft = Math.random() * (maxWidth - 0) + 0; // think of this like so: // var positionTop = Math.random() * (max - min) + min; // more information about it https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random var position = "position:absolute;top:" + positionTop + "px;left:" + positionLeft + "px;" return position; } document.getElementById("shape").onclick = function() { document.getElementById("shape").style.cssText = position(); } ``` ```css #gameSpace { width: 100%; height: 470px; background: blue; margin:0; padding-top: 30px; } #playSpace { position: relative; /* add this line */ width: 90%; height: 90%; margin: 0 auto; border: 1px black solid; } #shape { width: 100px; height: 100px; background-color: red; } ``` ```html <div id="gameSpace"> <div id="playSpace"> <!-- here we put the shape --> <div id="shape"></div> </div> </div> ``` **Updated after comment** Not sure how you added the `size()` function but probably the problem was with using `...cssText` that you overwrote the changes. So now I changed the code with passing the `element` to the functions and then only change the single CSS statements which need to be changed. ```js function position(element) { var playSpace = document.querySelector('#playSpace'); var shape = document.getElementById("shape"); var maxHeight = playSpace.offsetHeight - shape.offsetHeight; var maxWidth = playSpace.offsetWidth - shape.offsetWidth; var positionTop = Math.random() * (maxHeight - 0) + 0; var positionLeft = Math.random() * (maxWidth - 0) + 0; // think of this like so: // var positionTop = Math.random() * (max - min) + min; // more information about it https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random element.style.position = 'absolute'; element.style.top = positionTop + "px"; element.style.left = positionLeft + "px"; } function size(element) { var sizeMath = (Math.random() * 200) + 50; element.style.width = sizeMath + "px"; element.style.height = sizeMath + "px"; } document.getElementById("shape").onclick = function() { size(document.getElementById("shape")); position(document.getElementById("shape")); } ``` ```css #gameSpace { width: 100%; height: 470px; background: blue; margin:0; padding-top: 30px; } #playSpace { position: relative; /* add this line */ width: 90%; height: 90%; margin: 0 auto; border: 1px black solid; } #shape { width: 100px; height: 100px; background-color: red; } ``` ```html <div id="gameSpace"> <div id="playSpace"> <!-- here we put the shape --> <div id="shape"></div> </div> </div> ```
2017/06/06
You could just print out a lot of new line characters to make it look like the screen has been cleared. Also its easy to implement and helpful for debugging. The code would be some thing like: `print "\n"*100`
false
I don't know if this can be done but I'm sure I saw this in some scripts, that's why I'm asking. I need to print a string like this one: ``` ++++++++++++++++++++++++++++++ +++++++++++++++ + A 1 ++ A 2 + + A n + +-------------++-------------+ +-------------+ + B 1 ++ B 2 + ... + B n + +-------------++-------------+ +-------------+ + C 1 ++ C 2 + + C n + ++++++++++++++++++++++++++++++ +++++++++++++++ ``` where n is the number of columns and it depends on user's input. The A row is fixed, while B and C has to change while the program goes. So, first of all I need a way to print this kind of string, knowing that A and B are strings with length of 8 but C goes from 8 to 1 char. I took a look at the various "formatter" solutions and to `ppretty` but they seem way too far from what I need (and I didn't found a lot of examples!). (I've just tried `ppretty` because the other solutions required something like a data source while I'm getting my data with `class.getData()` since I'm coming from Java!) Now, after printing this string, I want it to be updated as B and C changes, without printing it again to avoid a lot of printed stuff and to make everything tidier and easier to be read. Is there any way to do that? edit: This is what I've tried (with no success) ``` def printCrackingState(threads): info_string = ''' ++++++++++++++++++++++++++++++++++ + Starting password = s.%08d + +--------------------------------+ + Current pin = s.%08d + ++++++++++++++++++++++++++++++++++ + Missing pins = %08d + ++++++++++++++++++++++++++++++++++ ''' while 1: for t in threads: printed_string = info_string % (t.starting_pin, t.testing_pin, t.getMissingPinsCount()) sys.stdout.write(printed_string) time.sleep(3500) ``` and this is the result: ``` ++++++++++++++++++++++++++++++++++ + Starting password = s.00000000 + +--------------------------------+ + Current pin = 00000523 + ++++++++++++++++++++++++++++++++++ + Missing pins = 01249477 + ++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++ + Starting password = s.01250000 + +--------------------------------+ + Current pin = 01250491 + ++++++++++++++++++++++++++++++++++ + Missing pins = 01249509 + ++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++ + Starting password = s.02500000 + +--------------------------------+ + Current pin = 02500465 + ++++++++++++++++++++++++++++++++++ + Missing pins = 01249535 + ++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++ + Starting password = s.03750000 + +--------------------------------+ + Current pin = 03750564 + ++++++++++++++++++++++++++++++++++ + Missing pins = 01249436 + ++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++ + Starting password = s.05000000 + +--------------------------------+ + Current pin = 05000592 + ++++++++++++++++++++++++++++++++++ + Missing pins = 01249408 + ++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++ + Starting password = s.06250000 + +--------------------------------+ + Current pin = 06250579 + ++++++++++++++++++++++++++++++++++ + Missing pins = 01249421 + ++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++ + Starting password = s.07500000 + +--------------------------------+ + Current pin = 07500577 + ++++++++++++++++++++++++++++++++++ + Missing pins = 01249423 + ++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++ + Starting password = s.08750000 + +--------------------------------+ + Current pin = 08750555 + ++++++++++++++++++++++++++++++++++ + Missing pins = 01249445 + ++++++++++++++++++++++++++++++++++ ``` I've used `sys.stdout.write()` to have them on the same line but it doesn't work! edit 2: My second attemp is with curses, as suggested in the replies. I can write things on the same line but they don't get updated. Here's my code: ``` import curses import time import threading class CursesPrinter(threading.Thread): windows = [] screen = None processes = [] info_string = ''' +++++++++++++++++++++++++ + Starting = s.%08d + +-----------------------+ + Current = s.%08d + +-----------------------+ + Missing = %08d + +++++++++++++++++++++++++ ''' def _makeWindows(self, numWindows): x = 0 y = 0 height = 15 width = 30 for i in range(numWindows): win = curses.newwin(height, width, x, y) #win.border(1) y+=width if y>self.screen.getmaxyx(): #This should make a new line if we reach the end of the terminal y = 0 x+=height self.windows.append(win) def run(self): while 1: for i in range(len(self.processes)-1): print_string = self.info_string % (self.processes[i].starting_pin, self.processes[i].testing_pin, self.processes[i].getMissingPinsCount()) self.windows[i].addstr(0,0, print_string) self.windows[i].refresh() #time.sleep(60) def __init__(self, threads, processes): super(CursesPrinter, self).__init__() self.screen = curses.initscr() curses.curs_set(0) self.processes = processes self._makeWindows(threads) #curses.endwin() ```
https://Stackoverflow.com/questions/15702518
15,702,518
A quick-and-dirty method that relies on your terminal handling [VT100 escape sequences](http://www.termsys.demon.co.uk/vtansi.htm) is to clear the screen and then move the cursor to the home position before printing the output. A quick demo: ``` import sys import time import random ESC = "\x1b" def home(): sys.stdout.write(ESC + '[0;0H') sys.stdout.flush() def cls(): sys.stdout.write(ESC + '[2J') sys.stdout.flush() def print_status(): w = 8 print('+' + '-'*w + '+') for row in range(3): fmt = '|%%%dd |' % (w - 1) print(fmt % random.randint(0, 1000)) print('+' + '-'*w + '+') sys.stdout.flush() if __name__ == "__main__": cls() for k in range(16, 0, -1): home() # or use cls() print_status() time.sleep(0.5) ``` Instead of using the "home" sequence, you could keep track of how many lines you printed, and print that many "cursor up" escape sequences before printing the next update. If you want to get fancier, check out the python [curses module](http://docs.python.org/2/library/curses.html), [blessings](https://pypi.python.org/pypi/blessings/), or [urwid](http://excess.org/urwid/). I don't think any of those work in a regular Windows terminal; that's why I asked about the OS you were targeting.
2013/03/29
This is what you want: ```js .replace(/\[(\w+)[^\]]*](.*?)\[\/\1]/g, '$2'); ``` [JavaScript demo](http://jsfiddle.net/7vyuwk0t/) Basically you catch the value between tags and then replace the whole string with that value. Using a regex to do this isn't a very clean way of doing it though... Sorry Alex but you didn;t read it seems.
true
I am trying to remove BBCode with attributes and content between those tags. I'm using this regular expression that I got here from [here](https://stackoverflow.com/questions/6777257/remove-bbcode-tags-and-their-content-in-php/6777448#6777448). I also tried other regex I found on stackoverflow but they didn't work for me, just the one I copy here is the closest. ``` ([[\/\!]*?[^\[\]]*?]) ``` I added a `.` before `*?])` and it maches the text between the tags but also matches `pokemon` and I don't want that. ``` **Regex**: ([[\/\!]*?[^\[\]].*?]) **Text**: I'm a pokemon master and I like [TAG] this [/TAG] pokemon [TAG] and this [/TAG] text... ``` I use this web to test regex <http://regexpal.com/> Can anyone help me? Thanks in advance.
https://Stackoverflow.com/questions/7117309
7,117,309
``` str = str.replace(/\[(\w+)[^\]]*](.*?)\[\/\1]/g, ''); ``` [jsFiddle](http://jsfiddle.net/alexdickson/5r5x2/).
2011/08/19
If we accept a lateral thinking approach, in a browser there are several API's we can abuse to execute arbitrary JavaScript, including calling a function, without any actual parenthesis characters. ### 1. `location` and `javascript:` protocol: One such technique is to abuse the `javascript:` protocol on `location` assignment. **Working Example:** ```js location='javascript:alert\x281\x29' ``` Although *technically* `\x28` and `\x29` are still parenthesis once the code is evaluated, the actual `(` and `)` character does not appear. The parentheses are escaped in a string of JavaScript which gets evaluated on assignment. --- ### 2. `onerror` and `eval`: Similarly, depending on the browser we can abuse the global `onerror`, by setting it to `eval`, and throwing something that will stringify to valid JavaScript. This one is trickier, because browsers are inconsistent in this behavior, but here's an example for Chrome. **Working example for Chrome (not Firefox, others untested):** ```js window.onerror=eval;Uncaught=0;throw';alert\x281\x29'; ``` This works in Chrome because `throw'test'` will pass `'Uncaught test'` as the first argument to `onerror`, which is almost valid JavaScript. If we instead do `throw';test'` it will pass `'Uncaught ;test'`. Now we have valid JavaScript! Just define `Uncaught`, and replace test with the payload. --- In conclusion: -------------- Such code is **truly awful**, and **should never be used**, but is sometimes used in XSS attacks, so the moral of the story is don't rely on filtering parenthesis to prevent XSS. Using a [CSP](https://developer.mozilla.org/en-US/docs/Web/Security/CSP) to prevent such code would also be a good idea.
true
I was told today that it's possible to invoke a function without parentheses. The only ways I could think of was using functions like [`apply`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) or [`call`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call). ``` f.apply(this); f.call(this); ``` But these require parentheses on `apply` and `call` leaving us at square one. I also considered the idea of passing the function to some sort of event handler such as [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout): ``` setTimeout(f, 500); ``` But then the question becomes "how do you invoke `setTimeout` without parentheses?" So what's the solution to this riddle? How can you invoke a function in Javascript without using parentheses?
https://Stackoverflow.com/questions/35949554
35,949,554
The easiest way to do that is with the `new` operator: ```js function f() { alert('hello'); } new f; ``` While that's unorthodox and unnatural, it works and is perfectly legal. The `new` operator doesn't require parentheses if no parameters are used.
2016/03/11
Try This, ``` $(".countdown, .event").removeClass("hidden").addClass("Hello"); ```
true
I've generated a dataframe of probabilities from a scikit-learn classifier like this: ``` def preprocess_category_series(series, key): if series.dtype != 'category': return series if series.cat.ordered: s = pd.Series(series.cat.codes, name=key) mode = s.mode()[0] s[s<0] = mode return s else: return pd.get_dummies(series, drop_first=True, prefix=key) data = df[df.year == 2012] factors = pd.concat([preprocess_category_series(data[k], k) for k in factor_keys], axis=1) predictions = pd.DataFrame([dict(zip(clf.classes_, l)) for l in clf.predict_proba(factors)]) ``` I now want to append these probabilities back to my original dataframe. However, the `predictions` dataframe generated above, while preserving the order of items in `data`, has lost `data`'s index. I assumed I'd be able to do ``` pd.concat([data, predictions], axis=1, ignore_index=True) ``` but this generates an error: ``` InvalidIndexError: Reindexing only valid with uniquely valued Index objects ``` I've seen that this comes up sometimes if column names are duplicated, but in this case none are. What is that error about? What's the best way to stitch these dataframes back together. `data.head()`: ``` year serial hwtfinl region statefip \ cpsid 20121000000100 2012 1 3796.85 East South Central Division Alabama 20121000000100 2012 1 3796.85 East South Central Division Alabama 20121000000100 2012 1 3796.85 East South Central Division Alabama 20120800000500 2012 6 2814.24 East South Central Division Alabama 20120800000600 2012 7 2828.42 East South Central Division Alabama county month pernum cpsidp wtsupp ... \ cpsid ... 20121000000100 0 11 1 20121000000101 3208.1213 ... 20121000000100 0 11 2 20121000000102 3796.8506 ... 20121000000100 0 11 3 20121000000103 3386.4305 ... 20120800000500 0 11 1 20120800000501 2814.2417 ... 20120800000600 1097 11 1 20120800000601 2828.4193 ... race hispan educ votereg \ cpsid 20121000000100 White Not Hispanic 111 Voted 20121000000100 White Not Hispanic 111 Did not register 20121000000100 White Not Hispanic 111 Voted 20120800000500 White Not Hispanic 92 Voted 20120800000600 White Not Hispanic 73 Did not register educ_parsed age4 educ4 \ cpsid 20121000000100 Bachelor's degree 65+ College grad 20121000000100 Bachelor's degree 65+ College grad 20121000000100 Bachelor's degree Under 30 College grad 20120800000500 Associate's degree, academic program 45-64 College grad 20120800000600 High school diploma or equivalent 65+ HS or less race4 region4 gender cpsid 20121000000100 White South Male 20121000000100 White South Female 20121000000100 White South Female 20120800000500 White South Female 20120800000600 White South Female ``` `predictions.head()`: ``` a b c d e f 0 0.119534 0.336761 0.188023 0.136651 0.095342 0.123689 1 0.148409 0.346429 0.134852 0.169661 0.087556 0.113093 2 0.389586 0.195802 0.101738 0.085705 0.114612 0.112557 3 0.277783 0.262079 0.180037 0.102030 0.071171 0.106900 4 0.158404 0.396487 0.088064 0.079058 0.171540 0.106447 ``` Just for fun, I've tried this specifically with only the head rows: ``` pd.concat([data_2012.iloc[0:5], predictions.iloc[0:5]], axis=1, ignore_index=True) ``` Same error comes up.
https://Stackoverflow.com/questions/36978874
36,978,874
Is this working? You have forgotten an `,` ``` $(".countdown,.event").removeClass("hidden").addClass("Hello"); ``` > > $(".intro,.demo") All elements with the class "intro" > or "demo" > > > see [w3schools](http://www.w3schools.com/jquery/jquery_ref_selectors.asp)
2016/05/02
Despite you saying it doesn't work, I used `clearRect` quite fine. > > Clears the specified rectangle by filling it with the background color > of the current drawing surface. This operation does not use the > current paint mode. > > > Beginning with Java 1.1, the background color of offscreen images may > be system dependent. Applications should use setColor followed by > fillRect to ensure that an offscreen image is cleared to a specific > color. > > > --- > > Fills the specified rectangle. The left and right edges of the > rectangle are at x and x + width - 1. The top and bottom edges are at > y and y + height - 1. The resulting rectangle covers an area width > pixels wide by height pixels tall. The rectangle is filled using the > graphics context's current color. > > > It is not clearly stated here that one will *set* the rectangle to the background color, while the other will *paint* with the foreground color on top of the current colors, but it's what it seems to do. This is pure speculation, but I think the note about offscreen images relates to `Graphics` objects obtained from offscreen AWT components, as they are native. I can hardly imagine how the background color of a `BufferedImage` could be system dependent. As the API doc is for `Graphics`, this could be a generalization not applying to the `BufferedImage` case. My testing code: ``` JFrame jf = new JFrame(); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); BufferedImage img = new BufferedImage(200, 300, BufferedImage.TYPE_INT_ARGB); Graphics2D g = img.createGraphics(); //fill right half with opaque white g.setColor(Color.WHITE); g.fillRect(100, 0, 100, 300); //leave top third as it is //fill middle third with transparent color g.setColor(new Color(0, true)); g.fillRect(0, 100, 200, 100); //clear bottom third with transparent color g.setBackground(new Color(0, true)); g.clearRect(0, 200, 200, 100); g.dispose(); jf.add(new JLabel(new ImageIcon(img))); jf.pack(); jf.setVisible(true); ``` the result is two white squares, top right. Where no white was painted, or `clearRect` was used to overwrite the white, the result is a light gray, the frame's default background color. Performance-wise, it's regular drawing. `arraycopy` might well be faster, I don't know, but at least this is likely hardware accelerated just as any other drawing operation. A plus point versus the array solution is a) no additional memory and b) independence from the color model; this should work no matter how the image was set up. A minus point versus the Composite solution is that it only allows clearing rectangles; setting the composite allows you to clear any kind of shape.
true
I have an off-screen BufferedImage, constructed with the type `BufferedImage.TYPE_INT_ARGB`. It can contain anything, and I'm looking for a way to (fairly efficiently) completely overwrite the image with transparent pixels, resulting in an 'invisible' image. Using something like this: ``` (bufimg.getGraphics()).setColor(new Color(10, 10, 100, 0)); (bufimg.getGraphics()).fillRect (0, 0, x, y); ``` Has no effect. One possible method might be just to write over every pixel in the BufferedImage, but I'm not sure this is the best solution. How would you do it? [edit] The Graphics documentation advises against using clearRect for off-screen images, but I have tried it with the same results as above. [edit2] After experimenting with MeBigFatGuy's code (thanks!), it does clear an image. But it also stops further painting to that image (or appears to). This code for example: ``` BufferedImage img = new BufferedImage (600, 600, BufferedImage.TYPE_INT_ARGB); Graphics g = img.createGraphics () g.drawLine (100, 100, 500, 500); AlphaComposite composite = AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f); g.setComposite(composite); g.setColor(new Color(0, 0, 0, 0)); g.fillRect(0, 0, 600, 600); graphicsAI.setColor(new Color (10, 10, 10, 255)); graphicsAI.drawLine (100, 100, 500, 500); ``` Results in nothing seen on the image (I'm drawing the image to a JPanel). Is this something to do with the addition of alpha values?
https://Stackoverflow.com/questions/5672697
5,672,697
After you clear the background with the CLEAR composite, you need to set it back to SRC\_OVER to draw normally again. ex: ``` //clear g2.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR)); g2.fillRect(0,0,256,256); //reset composite g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); //draw g2.setPaint(Color.RED); g2.fillOval(50,50,100,100); ```
2011/04/15
You could take a hash table for collecting the values and map new objects form the entries. ```js var data = [{ id: "122334", "name": "bob", commits: 10, email: "[email protected]" }, { id: "223411","name": "frank", commits: 4, email: "[email protected]" }, { id: "223411","name": "bob", commits: 19, email: "[email protected]" }], result = Object .entries(data.reduce((r, { name, commits }) => { r[name] = (r[name] || 0) + commits; return r; }, {})) .map(([name, commits]) => ({ name, commits })); console.log(result); ```
true
I have an API response (committers to a git project) where members are repeated due to them having the same name but different email address. Sample response: ``` [ {"id": "122334", "name": "bob", "commits":10, "email": "[email protected]"}, {"id": "223411","name": "frank", "commits":4, "email": "[email protected]"}, {"id": "223411","name": "bob", "commits":19, "email": "[email protected]"}, ] ``` So here I want to produce a result like: ``` [ {"name": "bob", "commits":29}, {"name": "frank", "commits":4}, ] ``` It feels like there is need for both a reduce and a loop.... but perhaps someone can suggest a simpler way as this feels like a common everyday kind of thing! I looked a little in underscore.js and it's groupBy function but it feels like overkill for a single usage and I couldn't get that working either :)
https://Stackoverflow.com/questions/60625996
60,625,996
You don't need the additional `for` loop. You can do this simply with a `Array.reduce` function. Additionally, I would avoid importing a library such as `underscore` to do something that is already possible with native JavaScript. You would essentially be importing thousands of lines of code to do a simple thing. Not the best approach to anything. You should always avoid using a library unless you're going to use multiple pieces of it or if there is no other option. Example: ```js const data = [ {"id": "122334", "name": "bob", "commits":10, "email": "[email protected]"}, {"id": "223411","name": "frank", "commits":4, "email": "[email protected]"}, {"id": "223411","name": "bob", "commits":19, "email": "[email protected]"}, ]; const results = data.reduce( (acc, curr) => { acc[curr.name] = acc[curr.name] ? acc[curr.name] + curr.commits : curr.commits; return acc; }, {}); console.log(results); ```
2020/03/10
Have you considered using a CSS transition? if you are changing the value of top you should be able to add transition: top 1.6s in your css (to picture). (Then the vendor prefixed versions when you get it working)
false
I know how to fix the animation that goes down only when the image is showing up in the window with jQuery, but now I want to do that with JavaScript. Struggling with that. The image must be fluently go down (+50px for 1.6 seconds). Have googling around, but most of them are done with jQuery I suggest and that is not what I want. Furtermore the animation should start when the scrollTop is between 600px and 800px. ```js function scrollFunction() { var animate = document.getElementById("picture"); var position = 0; var top = 0; var scrollTop = window.pageYOffset || document.documentElement.scrollTop; if(scrollTop > 600 && scrollTop < 800){ position++; animate.style.top = position + "50px"; } else { stop(); } } function stop() { clearTimeout(animate); } ``` ```css #picture { width: 100%; height: auto; top: -5px; position: relative; display: block; margin-left: auto; margin-right: auto; margin-bottom: 20px; } ``` ```html <div class="col-sm-12 col-xs-12"> <h1 class="responsive-h1">Mi<span class="logo-orange"> Pad2</span></h1> <p class="edition-title above-text-black">Black Edition</p> <img src="Img/picture.jpg" id="picture"/> </div> ```
https://Stackoverflow.com/questions/39498657
39,498,657
jsFiddle : <https://jsfiddle.net/n1q3fy8w/> Javascript ``` var imgSlide = document.getElementById('slidedown-image'); var slideDown = setInterval(function() { var topVal = parseInt(window.getComputedStyle(imgSlide).top, 10); imgSlide.style.top = (topVal + 1) + "px"; }, 15); setTimeout(function( ) { clearInterval( slideDown ); }, 1600); ``` You get the element first, after that you setup a `setInterval` which will basically move our `img` downwards, we then also set a `setTimeout` which after `1600`ms remvoes the `slideDown` interval and the image stops. Your image however may need `position: absolute`. The above answer will only work in Chrome, this however should work in all browswers jsFiddle : <https://jsfiddle.net/n1q3fy8w/1/> javascript ``` var imgSlide = document.getElementById('slidedown-image'); var slideDown = setInterval(function() { var topVal = parseInt(imgSlide.style.top, 10); imgSlide.style.top = (topVal + 1) + "px"; }, 15); setTimeout(function( ) { clearInterval( slideDown ); }, 1600); ``` Ok so `getComputedStyle` only works in chrome, so to get this to work on all other browsers, you have to specifically set the `css` property on the element and not via CSS. When you use javascript to access an element and change its style like so `element.style.bottom = '150px'` the `.style` gets you all of the css values for your inline styles on that element, so any `css` changes on an element that is done via a .css/.less file you can't access via javascript. So all the above code does is we set a `top: 0` on the element itself and in our code we use `imageSlide.style.top` instead of chrome's `window.getComputedStyle`
2016/09/14
here is my code to hide placeholder text on input and textarea focus(). Simple and working great. ```js $('textarea,input').focus(function(e){ val=$(this).attr('value'); if (!val) $(this).attr('value',' '); this.select(); }).blur(function(e){ val=$(this).attr('value'); if (val==' ') $(this).attr('value',''); }); ```
true
I´m using the "placeholder" attr. for placeholder text in input-fields I need to have this functionality in IE-incarnations too. I want the Placeholder to hide on FOCUS! every workaround i found hides the placeholder when the first type is entered. I´m unable to work it out myself, it needs to simply delete the input´s Placeholder-Text on focus but also recovers that placeholder-text on blur if input-value is empty. I´m trying to put this to work ``` jQuery(document).ready(function () { jQuery('[placeholder]').focus(function() { input = jQuery(this); if (input.val() == input.attr('placeholder')) { input.val(''); input.removeClass('placeholder'); input.attr('placeholder','') } }).blur(function() { var input = jQuery(this); if (input.val() == '' || input.val() == input.attr('placeholder')) { input.addClass('placeholder'); input.val(input.attr('placeholder')); } }).blur().parents('form').submit(function() { jQuery(this).find('[placeholder]').each(function() { var input = jQuery(this); if (input.val() == input.attr('placeholder')) { input.val(''); } }) }); }); ``` this changes the value of the placeholder to "(nothing)" and the behaviour is as i want but on blur it cant recover the placeholder-value beacause its "(nothing)" now //Update the solution for me : ``` $(function() { $('input').each(function() { $(this).val($(this).attr('holder')); }); $('input').focus(function() { if($(this).attr('holder')==$(this).val()) { $(this).val(''); } }); $('input').focusout(function() { if($.trim($(this).val())=='') { var holder = $(this).attr('holder'); $(this).val(holder); } }); }); ```
https://Stackoverflow.com/questions/14339588
14,339,588
For Webkit based browsers and Firefox you can hide the placeholder in pure CSS: ``` input:focus::-webkit-input-placeholder, input:focus::-moz-placeholder { opacity:0; } ```
2013/01/15
Of course it is possibile. In the most obvious case you can set each property of the target object with the corresponding value in the json object. More than *conversion*, I would call this object *creation*.
false
Is it possible to convert org.json.simple.jsonobject to java object
https://Stackoverflow.com/questions/52099753
52,099,753
I prefer to use jackson's objectMapper for this ``` ObjectMapper objectMapper=new ObjectMapper(); ClassName object=objectMapper.readValue(json.toString(),ClassName.class); ``` To use GSON ``` Gson g = new Gson(); ClassName object=g.fromJSON(json.toString(),ClassName.class); ```
2018/08/30
That's [the code](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/lang/String.java?av=f): ``` if (h == 0 && count > 0) { ... for (int i = 0; i < len; i++) { h = 31*h + val[off++]; } ... } return h; //0 ``` The String is empty, the result is 0. See also the [docs](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#hashCode()): ![enter image description here](https://i.stack.imgur.com/tpiDb.jpg)
true
What happens when assigning empty parentheses value to a String in Java? ``` String s = ""; ``` Does the object reference variable s refer to an object in the heap memory carrying a String value of nothing? what made me ask this question is that when printing the hash code of the object I get a zero, which did not make sense to me! ``` System.out.println("hash code is = " + s.hashCode()); ``` hash code is = 0
https://Stackoverflow.com/questions/23336138
23,336,138
The documentation of hashCode fro String. ``` /** * Returns a hash code for this string. The hash code for a * <code>String</code> object is computed as * <blockquote><pre> * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] * </pre></blockquote> * using <code>int</code> arithmetic, where <code>s[i]</code> is the * <i>i</i>th character of the string, <code>n</code> is the length of * the string, and <code>^</code> indicates exponentiation. * (The hash value of the empty string is zero.) // look at this line * * @return a hash code value for this object. */ public int hashCode() {// some code } ```
2014/04/28
another way, that I'm using, that could make it for you: ```js // here's the value we wanna get by ratio (where v is value and r is ratio) // r is an array with min and max value, this example is based on a 100% ratio const ratioValues = [ {v: 1, r: [0,75]}, // 75% chance to get 1 {v: 2, r: [76,100]} // 25% chance to get 2 ]; //actual function to get our value function getRandByRatio(ratioValues) { // idx is a random integer between 0 and 100 let idx = Math.floor(Math.random() * (100 + 1)); for (let item of ratioValues) { // test if idx is within the r range if (idx >= item.r[0] && idx <= item.r[1]) { //if it is return our value return item.v; } } }; // let's make a testing function function makeTest(nb) { const ul = document.getElementById("rand-value"); for (let i = 0; i < nb; i++) { ul.innerHTML += "<li>" + getRandByRatio(ratioValues) + "</li>"; } }; makeTest(10); ``` ```html <ul id="rand-value"></ul> ``` while it might be quite a lot of code for just 2 values, I find it more readable and easier to maintain.(And it's great when you have more values!!!) Hope this can be usefull to someone!! :)
true
I want to randomize my list with custom widths. For this, I wrote simple JavaScript snippet generating numbers between `1 and 2`. Function is as follows: ``` randomizePortfolio: function() { $('ul.works').children('li').each(function() { var Random = Math.floor(Math.random() * 2) + 1, words = 'normal'; if(Random == '2') { words = 'wide'; } $(this).addClass('col-md-'+3*Random+' col-sm-'+3*Random+' '+words); }); $('ul.works').masonry({ itemSelector: 'li' }); } ``` Problem is, I'd like have bigger ratio for `1`. Now it - obviosly - random, so sometimes I'm getting all `2`'s, some other time - all `1`'s. How can I add ratio (let's say 3:1) to this?
https://Stackoverflow.com/questions/19069923
19,069,923
To get a 3:1 distribution you can create an array with the numbers that you want, and add three 1s and one 2, and randomize the index: ``` var rvalues = [1,1,1,2]; var Random = rvalues[Math.floor(Math.random() * rvalues.length)]; ``` Here's another, equivalent, method based on the fact that 3/4 of the time the random value is less than 3/4: ``` var Random: if (Math.random() < .75) Random = 1; else Random = 2; ```
2013/09/28
Return **does not** print strings! ``` def show_excitement(str,n): print(str) if(n!=1): show_excitement(str,n-1) str="I am super excited for this course!" show_excitement(str,5) ```
true
I am supposed to Write a function called `"show_excitement"` where the string `"I am super excited for this course!"` is returned exactly 5 times, where each sentence is separated by a single space. I can only have the string once in my code. I have tried following code, but I think it is wrong somewhere. Please give an improved or alternate solution. ``` def show_excitement(str,n): if(n==0): return str else: show_excitement(str,n-1) str="I am super excited for this course!" print show_excitement(str,5) ```
https://Stackoverflow.com/questions/56144323
56,144,323
``` def show_excitement(): str = "I am super excited for this course!" return (str + " ")* 5 print show_excitement() ```
2019/05/15
Maybe you should check in your loop that month of current date (in loop) is the same as month of previous date by keeping at the end of every loop the last value of month (`$actualMonth`). You probably have to setup this value outside the loop with null and ignore this verification if `$actualMonth` is null. Also, you can start verification after first loop. If it's different, you have to `break` your loop. You can compare directly with your `$month` parameter. OR You could restrict your SQL query to get absence only for the month currently displayed. MySQL : ``` SELECT * FROM employees WHERE MONTH(date_to_checked) = month_number; ``` <https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_month>
true
I try to make a grouped plot with `matplotlib.pyplot` library in `Python`. I want to have date signature as a `string`, presented on x-axis. Despite I defined its values ("day\_date" column) as `string`, the resulted plot keeps displaying the values as int-s. **How to have the x-axis values displayed as string?** (Please note I do not want to have them converted into any dedicated date-format). ``` # Define data frame day_date = ['20151103', '20151103', '20151103', '20151103', '20151103', '20151103', '20151104', '20151104', '20151104', '20151104', '20151104', '20151104', '20151105', '20151105', '20151105', '20151105', '20151105', '20151105', '20151106', '20151106', '20151106', '20151106', '20151106', '20151106', '20151107', '20151107', '20151107', '20151107', '20151107', '20151107', '20151108', '20151108', '20151108', '20151108', '20151108', '20151108'] country_code = ['BY', 'DE', 'ID', 'PL', 'RU', 'US', 'BY', 'DE', 'ID', 'PL', 'RU', 'US', 'BY', 'DE', 'ID', 'PL', 'RU', 'US', 'BY', 'DE', 'ID', 'PL', 'RU', 'US', 'BY', 'DE', 'ID', 'PL', 'RU', 'US', 'BY', 'DE', 'ID', 'PL', 'RU', 'US'] val = [35989, 64488, 72879, 73586, 192538, 54474, 137322, 227274, 307893, 249741, 683455, 288863, 179319, 287662, 455944, 321588, 854791, 342946, 207263, 326290, 558362, 361792, 981566, 390313, 224863, 369141, 637215, 415884, 1031772, 429145, 272623, 419612, 702541, 497348, 1160243, 462813] df_tmp = pd.DataFrame([day_date, country_code, val]).T df_tmp.columns = ['day_date','country_code','val'] df_tmp.head() # Plot fig, ax = plt.subplots() for name, group in df_tmp.groupby('country_code'): ax.plot(group.day_date, group.val, label=name) ax.legend() plt.show() ``` [![enter image description here](https://i.stack.imgur.com/yI7jS.png)](https://i.stack.imgur.com/yI7jS.png)
https://Stackoverflow.com/questions/33875476
33,875,476
Revise your inner loop like this: ``` for($l=0;$l<$table;$l++){ $mark = false; for($y=0; $y<$count_absences; $y++){ $start = $absences[$y]['start']; $end = $absences[$y]['end']; $dStart = new DateTime($start); $dEnd = new DateTime($end); $dDiff = $dStart->diff($dEnd); $diff = $dDiff->days + 1; $start_day = date('d', strtotime($start)) - 1; $start_month = date('m', strtotime($start)); $lString = $year.'-'.$month.'-'.($l+1); $lDate = new DateTime($lString); if($lDate>=$dStart && $lDate<=$dEnd){ $mark = true; break; } } if($mark){ echo "<td>X</td>"; } else { echo "<td></td>"; } unset($employee); } ``` That way on each iteration the specific day we're on for the employee will be checked against all date spans of their absence, even if absence spans across months.
2015/11/23
Using jQuery you can toggle the class upon clicking with this: ``` $('.cell').click(function() { //catch clicks on .cell $('.cell').removeClass('activeCell'); //remove class "activeCell" from all $(this).addClass('activeCell'); //add class "activeCell" to .cell clicked }); ``` Apply `position: relative;` to `.top` and `.bottom`: ``` .top, .bottom { position: relative; } ``` And use the psuedoclass `:before` to create a image under the `.activeCell` ``` .activeCell:before { content: ""; position: absolute; bottom: -20px; height: 20px; width: 20px; background-image: url("https://www.shareicon.net/data/512x512/2016/01/17/704754_people_512x512.png"); background-size: 20px 20px; } ``` And remove this: ``` .walkingMan { width: 20px; height: 20px; display: inline-block } ``` And this: ``` <img src="https://www.shareicon.net/data/512x512/2016/01/17/704754_people_512x512.png" alt="walkingMan" class='walkingMan'/> ``` And to add space between the divs `.top` and `.bottom` put a `<br>` between them. ```js $('.cell').click(function() { $('.cell').removeClass('activeCell'); $(this).addClass('activeCell'); }); ``` ```css .cell { display: inline-block; border: 1px solid black; cursor: pointer; } .top, .bottom { position: relative; } .activeCell { background-color: lightgrey; } .activeCell:before { content: ""; position: absolute; bottom: -20px; height: 20px; width: 20px; background-image: url("https://www.shareicon.net/data/512x512/2016/01/17/704754_people_512x512.png"); background-size: 20px 20px; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <div> <div class='top'> <a class='cell activeCell'>One</a> <a class='cell'>One</a> <a class='cell'>One</a> <a class='cell'>One</a> </div> <br> <div class='bottom'> <a class='cell'>One</a> <a class='cell'>One</a> <a class='cell'>One</a> <a class='cell'>One</a> </div> </div> ```
true
**What I want to do:** I want to add a "walkingMan" image **under** an element when its class is changed to `activeCell`. I know how to do it when the image is added to the front or back of the element using pseudo class, but as far as I know, there isn't something like `:below` that I can use to achieve the same effect. Is there a way in css I can use to micmic this? **What I have done:** I have added image below every upper cell and make it visible when the class is changed to `activeCell`. But I hope to find a more simple solution. **What it looks like:** [![enter image description here](https://i.stack.imgur.com/EhXbU.png)](https://i.stack.imgur.com/EhXbU.png) **Code: [Simplified Code Example](https://jsfiddle.net/147prwy5/)**
https://Stackoverflow.com/questions/46257873
46,257,873
What about this: <https://jsfiddle.net/147prwy5/3/> HTML ``` <div class="cell active"> <a>One</a> <img src="https://www.shareicon.net/data/512x512/2016/01/17/704754_people_512x512.png" alt="walkingMan" /> </div> <div class="cell"> <a>One</a> <img src="https://www.shareicon.net/data/512x512/2016/01/17/704754_people_512x512.png" alt="walkingMan" /> </div> <div class="cell"> <a>One</a> <img src="https://www.shareicon.net/data/512x512/2016/01/17/704754_people_512x512.png" alt="walkingMan" /> </div> <div class="cell active"> <a>One</a> <img src="https://www.shareicon.net/data/512x512/2016/01/17/704754_people_512x512.png" alt="walkingMan" /> </div> ``` CSS ``` .cell { display: inline-block; } .cell a { border: 1px solid black; } .cell.active a { background-color: lightgrey; } .cell img { width: 20px; height: 20px; display: none; } .cell.active img { margin-top: 5px; width: 20px; height: 20px; display: block; } ```
2017/09/16
The `or` in Kotlin and `|` in Java used with numbers are not related to boolean operators (`bool1 | bool2` and `bool1 || bool2`). These are [bitwise operators](https://kotlinlang.org/docs/reference/basic-types.html#operations). The bit operators in Kotlin are defined as `infix` functions, see `or`: ``` public infix fun or(other: Int): Int ``` As a result you can execute this function in two ways: ``` result1 = number1.or(number2) result2 = number1 or number2 ```
true
I've made this small bot which processes through a list of search parameters. It works fine until there are several results on the page: `product_prices_euros` gives a list of items where half are empty. So when I concatenate with `product_prices_cents`, I have an output like the following: ``` 'price' : '',76 ``` for half results. Is there a simple way to prevent empty items for being collected? My output for `product_prices_euros` looks like: ``` [' 1', ' ', ' 2', ' ', ' 2', ' ', ' 1', ' ', ' 1', ' ', ' 1', ' ', ' 2', ' '] ``` I'd like to keep only '1', '2', etc... Here is what looks like CSS. There might be something on this side : ``` < span class="product-pricing__main-price" > 2 < span class="cents" >,79€< /span > < /span > ``` And my code: ``` def start_requests(self): base_url="https://new.carrefour.fr/s?q=" test_file = open(r"example", "r") reader = csv.reader(test_file) for row in reader: if row: url = row[0] absolute_url = base_url+url print(absolute_url) yield scrapy.Request(absolute_url, meta={'dont_redirect': True, "handle_httpstatus_list": [302, 301]}, callback=self.parse) def parse(self, response): product_name = response.css("h2.label.title::text").extract() product_packaging = response.css("div.label.packaging::text").extract() product_price_euros = response.css("span.product-pricing__main-price::text").extract() product_price_cents = response.css("span.cents::text").extract() for name, packaging, price_euro, price_cent in zip(product_name, product_packaging, product_price_euros, product_price_cents): yield { 'ean' : response.css("h1.page-title::text").extract(), 'name': name+packaging, 'price': price_euro+price_cent} ``` Any idea? :)
https://Stackoverflow.com/questions/53065523
53,065,523
Think of the method `setRawInputType` as accepting a bunch of bits, instead of an integer value. There are many methods like this one. This pattern is used when the method wants the caller to specify a bunch of "options". By passing `InputType.TYPE_TEXT_FLAG_CAP_SENTENCES or InputType.TYPE_CLASS_TEXT`, you are passing this: ``` 0000 0000 0000 0000 0100 0000 0000 0001 ``` See the two `1`s? Now let's look out the values of `InputType.TYPE_TEXT_FLAG_CAP_SENTENCES` and `InputType.TYPE_CLASS_TEXT`: ``` InputType.TYPE_TEXT_FLAG_CAP_SENTENCES 0000 0000 0000 0000 0100 0000 0000 0000 InputType.TYPE_CLASS_TEXT 0000 0000 0000 0000 0000 0000 0000 0001 ``` If we do the OR operation on each of those bits, we get `0000 0000 0000 0000 0100 0000 0000 0001`. The method basically checks which bits are 1s and does different stuff based on that. By using the `|` or `or` operator, you are kind of saying "I want this bit and this bit to be `1`". So by saying `or`, you actually mean "and". Counterintuitive, huh? The `||` operator only works for `boolean` operands because it is a logical operator, so it can't be used here.
2018/10/30
Just in case you want a faster regex alternative, you can use a negated character (`^)`) regex instead of laziness (`?`). It's faster as it [doesn't require backtracking](http://www.regular-expressions.info/repeat.html). ``` const uppercase = str => str.toUpperCase().replace(/\([^)]+\)/g, m => m.toLowerCase()); ```
true
I am trying to make a variable string uppercase and letters that are within () lower case. string will be what ever the user enters so do not know what it will be ahead of time. user entry examples What is entered (H)e(L)lo what is expected outcome (h)E(l)LO What is entered (H)ELLO (W)orld what is expected outcome (h)ELLO (w)ORLD here is what i have tried but can only get it to work if the () are at the end of the string. ``` if(getElementById("ID")){ var headline = getElementById("ID").getValue(); var headlineUpper = headline.toUpperCase(); var IndexOf = headlineUpper.indexOf("("); if(IndexOf === -1){ template.getRegionNode("Region").setValue(headlineUpper); } else{ var plus = parseInt(IndexOf + 1); var replacing = headlineUpper[plus]; var lower = replacing.toLowerCase(); var render = headlineUpper.replace(headlineUpper.substring(plus), lower + ")"); getElementById("Region").setValue(render); } } ``` Do to our system i am only able to use vanilla javascript. i have asked a similar question before with one () but now we are expecting more then one () in the string.
https://Stackoverflow.com/questions/63343766
63,343,766
You can use the [`.replace()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Using_an_inline_function_that_modifies_the_matched_characters) method with a regular expression. First you can make your string all uppercase using `.toUpperCase()`. Then, you can match all characters in-between `(` and `)` and use the replacement function of the `replace` method to convert the matched characters to lowercase. See example below: ```js function uppercase(str) { return str.toUpperCase().replace(/\(.*?\)/g, function(m) { return m.toLowerCase(); }); } console.log(uppercase("(H)e(L)lo")); // (h)E(l)LO console.log(uppercase("(H)ELLO (W)orld")); // (h)ELLO (w)ORLD ``` If you can support ES6 you can clean up the above function with arrow functions: ```js const uppercase = str => str.toUpperCase().replace(/\(.*?\)/g, m => m.toLowerCase()); console.log(uppercase("(H)e(L)lo")); // (h)E(l)LO console.log(uppercase("(H)ELLO (W)orld")); // (h)ELLO (w)ORLD ```
2020/08/10
You can try [GWT App](http://www.gwtapp.org/) with html templates generated and binded on run-time, no compiling-time.
false
What's the best way to **externalize large quantities of HTML** in a GWT app? We have a rather complicated GWT app of about 30 "pages"; each page has a sort of guide at the bottom that is several paragraphs of HTML markup. I'd like to externalize the HTML so that it can remain as "unescaped" as possible. I know and understand how to use **property files** in GWT; that's certainly better than embedding the content in Java classes, but still kind of ugly for HTML (you need to backslashify everything, as well as escape quotes, etc.) **Normally this is the kind of thing you would put in a JSP**, but I don't see any equivalent to that in GWT. I'm considering just writing a widget that will simply fetch the content from html files on the server and then add the text to an HTML widget. But it seems there ought to be a simpler way.
https://Stackoverflow.com/questions/744137
744,137
I'd say you load the external html through a [Frame](http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/com/google/gwt/user/client/ui/Frame.html). ``` Frame frame = new Frame(); frame.setUrl(GWT.getModuleBase() + getCurrentPageHelp()); add(frame); ``` You can arrange some convention or lookup for the *getCurrentPageHelp(*) to return the appropriate path (eg: */manuals/myPage/help.html*) Here's an [example](http://examples.roughian.com/index.htm#Panels~Frame) of frame in action.
2009/04/13
In addition to the response by @Thang Le You can configure your time out of read operations, adding this line: > > jedisClientConfigurationBuilder.readTimeout(Duration.ofSeconds(1)); > > > This is the value that you can obtain when use: > > jedisConFactory.getTimeout() > > >
false
I'm using two libraries, let's call them "*NoQ*" and "*WithQ*" (you'll see why). Both depend on the same object class, both have classes where they expect Spring to inject this object via `@Autowired`. So far so good. But *NoQ* library uses plain `@Autowired`, no qualifier, and also includes a `@Component` class that implements the bean; *WithQ* uses `@Autowired` `@Qualifier("name")`, and expects me to provide the bean. When I try to let the `@Component` inject into both libraries, *WithQ* fails because the qualifier isn't present. When I provide my own `@Bean("name")` supplier, then *NoQ* fails because there are two objects that could both satisfy its `@Autowired`. I also tried using XML syntax and `autowired="byName"`, hoping that would force *NoQ* to ignore the second bean, but no luck, I still get the error about two beans on startup. I can't really change either library. How can I use them both? I'm OK with them sharing the object, or with them each getting their own version of it - either of them is OK. I just want a way to get both of them to start up together in my application.
https://Stackoverflow.com/questions/49022017
49,022,017
``` @Bean JedisConnectionFactory jedisConnectionFactory() { RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(); redisStandaloneConfiguration.setHostName("localhost"); redisStandaloneConfiguration.setPort(6379); redisStandaloneConfiguration.setDatabase(0); redisStandaloneConfiguration.setPassword(RedisPassword.of("password")); JedisClientConfigurationBuilder jedisClientConfiguration = JedisClientConfiguration.builder(); jedisClientConfiguration.connectTimeout(Duration.ofSeconds(60));// 60s connection timeout JedisConnectionFactory jedisConFactory = new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration.build()); return jedisConFactory; } ```
2018/02/28
I believe it may be that you are checking arr[i].length instead of arr.length because you only check if arr[i].length is 0 and if then the function returns 0, otherwise shortestElement is still equal to infinity and is returned.
false
``` // Should equal 0 when an empty Array is entered function getLengthOfShortestElement(arr) { var shortestElement = Infinity; for(var i=0; i < arr.length; i++) { if(arr[i].length < shortestElement) { shortestElement = arr[i].length; } else if (arr[i].length === 0) { return 0; } } return shortestElement; } var output = getLengthOfShortestElement([]); console.log(output); ``` Judging by the code why isn't it outputting 0? Instead it outputs Infinity..
https://Stackoverflow.com/questions/66607638
66,607,638
You should move the `arr.length === 0` outside of the loop, or else it will never run. Try this instead ``` function getLengthOfShortestElement(arr) { var shortestElement = Infinity; for(var i=0; i < arr.length; i++) { if(arr[i].length < shortestElement) { shortestElement = arr[i].length; } } if (arr.length === 0) { return 0; } return shortestElement; } var output = getLengthOfShortestElement([]); console.log(output); ```
2021/03/12
The @PathVariable annotation should be passed in with the name of the field in speechmarks "" as the argument for findByUsername before "String username"
false
So I have an area in my js quiz where it displays the question. I would like to know how I can centre that area and put a box around it, to make it look fancy. Would be great if someone can help. Thanks (code and screenshot of the area I would like to be entered is below). ```js // This initialises a request to the trivia database API var xmlhttp = new XMLHttpRequest(); var url = "//opentdb.com/api.php?amount=25&category=21&type=multiple"; var score = 0; var livesTaken = 0; var question; var type; var correctAnswer; var incorrect1; var incorrect2; var incorrect3; // This requests the data xmlhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { var jsondata = JSON.parse(this.responseText); getData(jsondata); } }; xmlhttp.open("GET", url, true); xmlhttp.send(); // This function is used to extract the received data function getData(data) { // This is the question: question = data.results[0].question; // This is the question type eg. multiple choice type = data.results[0].type; // This is the correct answer correctAnswer = data.results[0].correct_answer; // These are the three incorrect answers incorrect1 = data.results[0].incorrect_answers[0]; incorrect2 = data.results[0].incorrect_answers[1]; incorrect3 = data.results[0].incorrect_answers[2]; // randomly select answer and other options and place in array // then display elements from array on the buttons var randoms = []; // an array to store unique random numbers var random; // loop runs four times... for (i = 0; i < 4; i++) { // generates a random number between 0 and 3 random = Math.floor(Math.random() * 4); // checks if random number already in array... while (randoms.includes(random)) { // generates another random number random = Math.floor(Math.random() * 4); } // adds random number to array randoms.push(random); } var options = []; console.log(randoms); options[randoms[0]] = correctAnswer; options[randoms[1]] = incorrect1; options[randoms[2]] = incorrect2; options[randoms[3]] = incorrect3; console.log(options); // This displays the question and answer options document.getElementById("trivia").innerHTML = question; for (i = 0; i < options.length; i++) { let btn = document.createElement("button"); let br = document.createElement("br"); btn.classList.add("trivia-btn"); // We're adding the class here btn.setAttribute("onclick", `checkAnswer("${options[i]}", this)`); btn.innerHTML = options[i]; document.getElementById("trivia").append(br, btn); // You can now use the trivia div as a container for the generated button and your br //document.getElementsByClassName("trivia-btn").disabled = false; } } function checkAnswer(selected, element) { document.querySelectorAll(".trivia-btn").forEach((e) => { e.disabled = true }); console.log("User selected: " + selected); console.log("The correct answer is: " + correctAnswer); if (selected == correctAnswer) { score++; console.log("You got it right!"); element.style.background = "green"; setTimeout(function () { getNewQuestion(); }, 2000); } else { livesTaken++; console.log("Sorry, that's incorrect"); element.style.background = "red"; if (livesTaken == 3) { quizFailed(); } else { setTimeout(function () { getNewQuestion(); }, 10); } } console.log(score) console.log(livesTaken) } function getNewQuestion() { document.getElementById("score").style.display = "block"; document.getElementById("score").style.float = "right"; document.getElementById("trivia").style.float = "left"; document.getElementById("score").style.align = "right"; document.getElementById("score").innerHTML = "score:" + score; document.getElementById("trivia").style.display = "block"; document.getElementById("endingText").style.display = "none"; // This requests the data xmlhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { var jsondata = JSON.parse(this.responseText); getData(jsondata); } }; xmlhttp.open("GET", url, true); xmlhttp.send(); } getNewQuestion() function quizFailed() { document.getElementById("endingText").style.display = "block" document.getElementById("score").style.display = "none" document.getElementById("trivia").style.display = "none" document.getElementById("endingText").innerHTML = "You have run out of lives, you scored " + score + " pretty bad ngl" + " <button onClick = getNewQuestion() >click to restart</button>" score = 0; livesTaken = 0; } document.getElementById("score") ``` ```css .trivia-btn { background-color: "blue"; padding: 0.7rem 2rem; color: black; margin-top: 0.4rem; } ``` ```html <html> <head> <link rel="stylesheet" href="Sport.css"> <title>Sport Quiz (Medium)</title> <meta charset="utf-8" /> <script src="Sport.js"></script> <div id="trivia"></div> <div id ="endingText"></div> <div id ="score"></div> <div id ="exittext"></div> </head> <body> </body> </html> ``` [I would like this to be centred in the middle of the page.](https://i.stack.imgur.com/zWc9F.png)
https://Stackoverflow.com/questions/63391471
63,391,471
You need to use @PathVariable, ``` public List<Data> findByUsername(@PathVariable("username") String username) ```
2020/08/13
You can use `method-lookup`: You abstract class: ``` public abstract class AbstractConnector { private abstract WebServiceTemplate getWebServiceTemplate(); protected Object send(Object message) { return getWebServiceTemplate().marshalSendAndReceive(); } ``` Your configuration: ``` <bean id="webServiceTemplate" scope="prototype" class="com.example.WebServiceTemplate" /> <bean id="connector" class="com.example.AbstractConnector" <lookup-method name="webServiceTemplate" bean="webServiceTemplate" /> </bean> ``` Spring will wire you abstract class to return a fresh `webServiceTemplate` if the method `getWebServiceTemplate()` is called.
true
How I can inject my `webServiceTemplate` in the implementing class? My example: ``` public abstract class AbstractConnector { protected WebServiceTemplate webServiceTemplate; protected Object send(Object message) { return webServiceTemplate.marshalSendAndReceive(); } ``` } And in my concrete implementation I would like to set my `webServiceTemplate` like this. ``` public class MyConnector extends AbstractConnector { @Resource(name = "myWebService") private WebServiceTemplate webServiceTemplate; } ``` But this is not OK. If I call the `send()`, then I will get NPE because `webServiceTemplate` is null. How to set this dependency in implementation which will be accessible in the `send()` method?
https://Stackoverflow.com/questions/27795392
27,795,392
I do not see why field injection would be any less simple here: ``` public abstract class AbstractConnector { protected WebServiceTemplate webServiceTemplate; public void setWebServiceTemplate(WebServiceTemplate template) { this.webServiceTemplate = template; } } public class MyConnector extends AbstractConnector { @Autowired("myWebService") @Override public void setWebServiceTemplate(WebServiceTemplate template) { super.setWebServiceTemplate(template); } } ```
2015/01/06
Because WWW::Mechanize does not speak javascript, you either need to do as suggested and figure out what the javascript does and go around its back or you can use something like [WWW::Mechanize::Firefox](https://metacpan.org/module/WWW%3a%3aMechanize%3a%3aFirefox) that will allow you to control a browser.
false
I have the following html piece from this website: <http://catalogue.bl.uk/F/NTBK6NCP3LK56BPNU2NJ4FF4MBLIRUNMFX66JLHKBDV1RNCAAB-02920?func=short-0&set_number=151530> ``` <form name="XXX000001" method="GET"><input type="checkbox" name="ckbox" onclick="javascript:select_record(this.form);" onkeypressed="javascript:select_record(this.form);"></form> ``` I was wondering if there is anyway I can use mechanize to tick the checkboxes? It seems that these boxes are not formed using the normal html. I don't know javascript
https://Stackoverflow.com/questions/7604400
7,604,400
Maybe you should check [WWW::Selenium](http://search.cpan.org/~mattp/Test-WWW-Selenium-1.25/lib/WWW/Selenium.pm) in order to deal with JavaScript web pages. `WWW::Selenium` is a kind of remote control for browsers. From the documentation: *Selenium Remote Control (SRC) is a test tool that allows you to write automated web application UI tests in any programming language against any HTTP website using any mainstream JavaScript-enabled browser. SRC provides a Selenium Server, which can automatically start/stop/control any supported browser. It works by using Selenium Core, a pure-HTML+JS library that performs automated tasks in JavaScript; the Selenium Server communicates directly with the browser using AJAX (XmlHttpRequest).* After you have downloaded and installed the Selenium server ( a Java apllication ), you can use the module `WWW::Seletion`, to control the server which will use browsers to interact with complex JavaScript enabled web sites. With an instance of the class `WWW::Selenium` ``` my $sel = WWW::Selenium->new( host => "localhost", port => 4444, browser => "*iexplore", browser_url => "http://www.google.com", ); ``` almost every kind of interaction with a web site become possible. One has to define a *locator* to pinpoint an element in the page, in order to issue a command ( select, click, ... ). You'll find detailed help in the module documentation.
2011/09/29
Just posting my solution based on Brian Huey's [suggestion](https://stackoverflow.com/a/35244739/3128336). ``` from datetime import datetime, timedelta import statsmodels.api as sm delta = timedelta(days=7) def calc_mad_mean(row): start = row['ts'] end = start + delta subset = df['score'][(start <= df['ts']) & (df['ts'] < end)] return pd.Series({'mad': sm.robust.mad(subset), 'med': np.median(subset)}) first_wk = df.ts.iloc[0] + delta results = df[first_wk < df.ts].apply(calc_mad_mean, axis=1) df.join(results, how='outer') ``` Results ``` person score ts mad med 0 A 9 2000-01-01 NaN NaN 1 B 2 2000-01-01 NaN NaN 2 C 1 2000-01-10 0.000000 1.0 3 B 3 2000-01-20 3.706506 5.5 4 A 8 2000-01-25 2.965204 6.0 5 C 4 2000-01-30 0.000000 4.0 6 A 2 2000-02-08 0.741301 2.5 7 B 3 2000-02-12 1.482602 2.0 8 C 1 2000-02-17 5.930409 5.0 9 A 9 2000-02-20 0.000000 9.0 ```
true
I have a pandas dataframe with irregularly spaced dates. Is there a way to use 7days as a moving window to calculate [median absolute deviation](http://statsmodels.sourceforge.net/devel/generated/statsmodels.robust.scale.mad.html), median etc..? I feel like I could somehow use `pandas.rolling_apply` but it does not take irregularly spaced dates for the window parameter. I found a similar post <https://stackoverflow.com/a/30244019/3128336> and am trying to create my custom function but cannot still figure out.. Can anyone please help? ``` import pandas as pd from datetime import datetime person = ['A','B','C','B','A','C','A','B','C','A',] ts = [ datetime(2000, 1, 1), datetime(2000, 1, 1), datetime(2000, 1, 10), datetime(2000, 1, 20), datetime(2000, 1, 25), datetime(2000, 1, 30), datetime(2000, 2, 8), datetime(2000, 2, 12), datetime(2000, 2, 17), datetime(2000, 2, 20), ] score = [9,2,1,3,8,4,2,3,1,9] df = pd.DataFrame({'ts': ts, 'person': person, 'score': score}) ``` df looks like this ``` person score ts 0 A 9 2000-01-01 1 B 2 2000-01-01 2 C 1 2000-01-10 3 B 3 2000-01-20 4 A 8 2000-01-25 5 C 4 2000-01-30 6 A 2 2000-02-08 7 B 3 2000-02-12 8 C 1 2000-02-17 9 A 9 2000-02-20 ```
https://Stackoverflow.com/questions/35242829
35,242,829
You can use a time delta to select rows within your window and then use apply to run through each row and aggregate: ``` >>> from datetime import timedelta >>> delta = timedelta(days=7) >>> df_score_mean = df.apply(lambda x: np.mean(df['score'][df['ts'] <= x['ts'] + delta]), axis=1) 0 5.500000 1 5.500000 2 4.000000 3 4.600000 4 4.500000 5 4.500000 6 4.555556 7 4.200000 8 4.200000 9 4.200000 ```
2016/02/06
Perhaps, you might want to try this <https://hub.docker.com/r/timbru31/java-node> one to create the docker file. This docker image comes with both Java and Node pre-installed. It comes in handy when both are required as a dependency. Something like, ``` FROM timbru31/java-node:<tag> ```
true
I am not sure why I expected this to work: ``` # Dockerfile FROM node:6 FROM java:8 ``` but it doesn't really work - looks like the first command is ignored, and second command works. Is there a straightforward way to install both Node.js and Java in a Docker container? Ultimately the problem I am trying to solve is that I am getting an ENOENT error when running Selenium Webdriver - ``` [20:38:50] W/start - Selenium Standalone server encountered an error: Error: spawn java ENOENT ``` And right now I assume it's because Java is not installed in the container.
https://Stackoverflow.com/questions/43769730
43,769,730
The best way for you is to take java (which is officially deprecated and it suggests you use `openjdk` image) and install node in it. So, start with ``` FROM openjdk:latest ``` This will use the latest openjdk image, which is `8u151` at this time. Then install `node` and other dependencies you might need: ``` RUN apt-get install -y curl \ && curl -sL https://deb.nodesource.com/setup_9.x | bash - \ && apt-get install -y nodejs \ && curl -L https://www.npmjs.com/install.sh | sh ``` You might want to install things like grunt afterwards, so this might come in handy as well. ``` RUN npm install -g grunt grunt-cli ``` In total you will get the following Dockerfile: ``` FROM openjdk:latest RUN apt-get install -y curl \ && curl -sL https://deb.nodesource.com/setup_9.x | bash - \ && apt-get install -y nodejs \ && curl -L https://www.npmjs.com/install.sh | sh \ RUN npm install -g grunt grunt-cli ``` You may clone the Dockerfile from my gitlab repo [here](https://gitlab.com/flexbox/docker/java-nodejs)
2017/05/03
``` public static class Webdriver { public static void ExecuteJavaScript(this IWebDriver driver, string scripts) { IJavaScriptExecutor js = (IJavaScriptExecutor)driver; js.ExecuteScript(scripts); } public static T ExecuteJavaScript<T>(this IWebDriver driver, string scripts) { IJavaScriptExecutor js = (IJavaScriptExecutor)driver; return (T)js.ExecuteScript(scripts); } } ``` In your code you can then do: ``` IWebDriver driver = new WhateverDriver(); string test = driver.ExecuteJavaScript<string>(" return 'hello World'; "); int test = driver.ExecuteJavaScript<int>(" return 3; "); ```
true
How is this achieved? [Here](http://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions#Q%3a_How_do_I_execute_Javascript_directly?) it says the java version is: ``` WebDriver driver; // Assigned elsewhere JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("return document.title"); ``` But I can't find the C# code to do this.
https://Stackoverflow.com/questions/6229769
6,229,769
I prefer to use an extension method to get the scripts object: ``` public static IJavaScriptExecutor Scripts(this IWebDriver driver) { return (IJavaScriptExecutor)driver; } ``` Used as this: ``` driver.Scripts().ExecuteScript("some script"); ```
2011/06/03
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
51